我在将我在子类中创建的JPanel添加到我在驱动程序类中创建的JFrame时遇到了一些麻烦。我不知道为什么,但是面板没有显示它应该如何工作,而我可以使它工作的唯一方法是在子类和驱动程序类中定义JFrame,但是最后我得到了两个不同的JFrame,一个是我想要的东西它和一个空白的。有任何想法吗?我已经从两个类中添加了代码,还添加了图像的外观和外观的图像。
我的驱动程序类;
public class GUIDriver extends JFrame {
public static void main(String[] args) {
GUIDesign newOrder = new GUIDesign();
//frame
JFrame myframe = new JFrame("ROFA: Royal Furniture Ordering System");
myframe.setLayout(new BorderLayout());
myframe.setVisible(true);
myframe.setSize(900,600);
myframe.setResizable(false);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myframe.add(newOrder);
}
和我的GUI类;
public class GUIDesign extends JPanel implements ActionListener {
GUIDesign(){
JButton chair = new JButton("Add Chair");
JButton desk = new JButton("Add Desk");
JButton table = new JButton("Add Table");
JButton clear = new JButton("Clear All");
JButton save = new JButton("Save file");
JButton load = new JButton("Load file");
GridBagLayout layout = new GridBagLayout();
JPanel panelLeft = new JPanel(layout);
panelLeft.setLayout(layout);
panelLeft.setBorder(BorderFactory.createEtchedBorder(Color.lightGray, Color.black));
this.add(panelLeft, BorderLayout.WEST);
GridBagConstraints c = new GridBagConstraints(0, 0, 0, 1, 1.0, 1.0,
GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, new Insets(
0,0,0,0), 0, 0);
c.fill = GridBagConstraints.BOTH;
panelLeft.add(save, c);
c.gridx = 0;
c.gridy = 1;
panelLeft.add(load, c);
c.gridx = 0;
c.gridy = 2;
panelLeft.add(chair, c);
c.gridx = 0;
c.gridy = 3;
panelLeft.add(table, c);
c.gridx = 0;
c.gridy = 4;
panelLeft.add(desk, c);
c.gridx = 0;
c.gridy = 5;
panelLeft.add(clear, c);
}
@Override
public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated
methods, choose Tools | Templates.
}
这就是它的外观:
这就是我最终得到的:
谢谢。
默认情况下,JPanel使用FlowLayout
。 FlowLayout
将以其首选大小显示组件,默认设置为中心对齐,可以将其更改为左侧或右侧。
this.add(panelLeft, BorderLayout.WEST);
添加组件时不能只使用BorderLayout约束。
代码应为:
this.setLayout( new BorderLayout() );
this.add(panelLeft, BorderLayout.LINE_START); // new recommendation instead of using "WEST".
现在应该将面板与面板的左侧对齐。
此外,使用GridLayout并不比使用GridBagLayout容易。
将按钮添加到面板的代码很简单:
JPanel panelLeft = new JPanel( new GridLayout(0, 1) );
panelleft.add(save);
panelLeft.add(load);
不需要任何约束。