簡體   English   中英

Java GridBagLayout JComponents放置

[英]Java GridBagLayout JComponents placement

我試圖在一行上放置一個標簽和一個文本字段,在第二行上放置另一個標簽和文本字段。 問題在於第二對JComponent也位於第一行。 我首先使用GridLayout(2,1),在第一行中,我將帶有兩對的GridBagLayout和JPanel放置在一起,在第二行中,我將GridBagLayout和JPanel放置在放置提交按鈕的位置。

    JDialog dialog;
    JLabel name;
    JLabel rating;

    dialog = new JDialog();                                                                            
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);           
    dialog.setSize(300, 350);
    //dialog.setResizable(false);
    dialog.setLocationRelativeTo(null);


    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new GridLayout(2,1));
    dialog.getContentPane().add(mainPanel);

    JPanel firstPanel = new JPanel();
    firstPanel.setLayout(new GridBagLayout());
    GridBagConstraints c = new GridBagConstraints();

    mainPanel.add(firstPanel);

    name = new JLabel("Name:");
    c.weightx = 0.5;
    c.gridx = 0;
    c.gridy = 0;
    firstPanel.add(name);
    JTextField label1 = new JTextField(10);
    c.gridx = 1;
    c.gridy = 0;
    firstPanel.add(label1);            

    rating = new JLabel("Rating:");
    c.weightx = 0.5;
    c.gridx = 0;
    c.gridy = 1;
    firstPanel.add(rating);
    JTextField label2 = new JTextField(10);
    c.gridx = 1;
    c.gridy = 1;
    firstPanel.add(label2);

    JPanel submit = new JPanel();
    submit.setLayout(new GridBagLayout());
    mainPanel.add(submit);
    JButton buton = new JButton("Submit");
    submit.add(buton);
    dialog.pack();
    dialog.setVisible(true);

添加組件時尚未向GridBagConstraints提供GridBagConstraints

firstPanel.add(name);

相反,使用更像

firstPanel.add(name, c);

這會將組件和約束傳遞給GridLayoutManager

有關更多詳細信息,請參見如何使用GridBagLayout

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM