我需要menuPanel的组件在框架展开时展开。 MenuPanel使用的是GridBayLayout,我用面板的填充和重量值来修饰,但是没有任何东西看起来会导致组件随着框架调整大小。如何使用GridBagLayout强制JPanel使用JFrame进行调整
我怀疑我在显示类中添加menuPanel的方式有问题。此外,我还尝试将设置布局设置为TanksApplication,但这也不起作用。我想,我不了解一些基本的东西。
主要应用
public class TanksApplication extends JFrame{
public TanksApplication(){
super("Tanks");
}
public static void main (String args[]){
Display display = new Display();
TanksApplication frame = new TanksApplication();
frame.add(display);
frame.setSize(600,425);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
}
}
Display类
public class Display extends JPanel{
public Display(){
menuPanel = new JPanel(new GridBagLayout());
GridBagConstraints con = new GridBagConstraints();
mainMenuImageP = new JPanel();
mainMenuImageP.setBackground(Color.BLACK);
con.fill = GridBagConstraints.BOTH;
con.gridy = 0;
con.gridx = 0;
con.gridwidth = 2;
con.weightx = 0.5;
con.weighty = 0.5;
con.anchor = GridBagConstraints.CENTER;
con.ipadx = 400;
con.ipady = 300;
con.insets = new Insets(0,20,0,20);
menuPanel.add(mainMenuImageP, con);
newGameB = new JButton("New Game");
con.fill = GridBagConstraints.HORIZONTAL;
con.gridy = 1;
con.gridx = 0;
con.gridwidth = 1;
con.weightx = 0.5;
con.weighty = 0.5;
con.anchor = GridBagConstraints.CENTER;
con.ipadx = 0;
con.ipady = 0;
con.insets = new Insets(10,10,10,10);
menuPanel.add(newGameB, con);
loadGameB = new JButton("Load Game");
con.fill = GridBagConstraints.HORIZONTAL;
con.gridy = 1;
con.gridx = 1;
con.gridwidth = 1;
con.weightx = 0.5;
con.weighty = 0.5;
con.anchor = GridBagConstraints.CENTER;
con.ipadx = 0;
con.ipady = 0;
con.insets = new Insets(10,10,10,10);
menuPanel.add(loadGameB, con);
add(menuPanel);
}
这是一个好主意,谢谢。我会试一试。我没有意识到Display是一个面板,我不知道为什么我没有想到它。 – ulw1
就是这样。再次感谢。 – ulw1
@ ulw1:不客气。如果你绝对需要使用诸如menuPanel之类的内部JPanel,那么你会希望让你的DisplayPanel使用一个布局来改变其组件preferredSizes,比如BorderLayout。 –