如何将多个JPanel添加到具有不同大小的JFrame

时间:2014-06-11 08:56:47

标签: java swing layout jframe jpanel

我尝试从stackoverflow执行此操作:

adding multiple jPanels to jFrame

但是这似乎没有像示例那样有效,有人能告诉我我做错了什么吗? 我试图将各自各自大小的多个JPanel添加到JFrame中。我也希望能够给每个JPanel特定的尺寸和能力,让它们放在我想要的确切位置。

我尝试制作的图片: Mockup

这是我的代码到目前为止:      public ReserveringenGUI(ReserveringController controller){         this.controller = new ReserveringController();         makeFrame();     }

public void makeFrame() {
    JFrame frame1 = new JFrame();
    frame1.setTitle("Reserveringen");
    frame1.setSize(800, 500);
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel container = new JPanel();
    container.setLayout(new BoxLayout(container, BoxLayout.X_AXIS));

    JPanel willekeurigPanel = new JPanel();
    willekeurigPanel.setSize(400, 500);
    willekeurigPanel.setBackground(Color.YELLOW);
    willekeurigPanel.setVisible(true);

    JPanel overzichtPanel = new JPanel();
    overzichtPanel.setSize(400, 500);
    overzichtPanel.setBackground(Color.red);
    overzichtPanel.setVisible(true);

    DateFormat format = new SimpleDateFormat("dd-MM-yyyy");
    DateFormatter df = new DateFormatter(format);
    JFormattedTextField dateBeginField = new JFormattedTextField(df);
    dateBeginField.setPreferredSize(new Dimension(250, 20));
    dateBeginField.setValue(new Date());

    JFormattedTextField dateEndField = new JFormattedTextField(df);
    dateEndField.setPreferredSize(new Dimension(250, 20));
    dateEndField.setValue(new Date());

    JTextField klantnummer = new JTextField();
    klantnummer.setPreferredSize(new Dimension(250, 20));
    JTextField artikelnummer = new JTextField();
    artikelnummer.setPreferredSize(new Dimension(250, 20));

    JLabel dateBeginLabel = new JLabel("Begin Datum ");
    JLabel dateEndLabel = new JLabel("Eind datum: ");
    JLabel klantID = new JLabel("Klant nummer: ");
    JLabel artikelID = new JLabel("Artikel nummer: ");

    JButton voegReserveringToe = new JButton("Voeg toe");

    voegReserveringToe.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            voegReserveringToeActionPerformed(evt);
        }
    });

    willekeurigPanel.add(dateBeginLabel);
    willekeurigPanel.add(dateBeginField);

    willekeurigPanel.add(dateEndLabel);
    willekeurigPanel.add(dateEndField);

    willekeurigPanel.add(klantID);
    willekeurigPanel.add(klantnummer);

    willekeurigPanel.add(artikelID);
    willekeurigPanel.add(artikelnummer);

    willekeurigPanel.add(voegReserveringToe);



    container.add(willekeurigPanel);
    container.add(overzichtPanel);

    frame1.add(container);
    frame1.setVisible(true);
}

1 个答案:

答案 0 :(得分:2)

正如here所述,不要随意设置组件的大小和位置。相反,让布局按要求执行工作nesting。使用GroupLayout显示here标记的输入字段。将每个添加到CENTER面板的BorderLayout,并在左侧的SOUTH中添加一个按钮。最后,将两个面板添加到具有GridLayout(1, 0)的封闭面板。