1

Below are my code to add label and textfield. i want to add it such that its [label] [textfield] in 2 column

i know i can do it by using gridlayout but the number of rows need to be fixed, hence is there another method to add it such that no matters how many [label] [textfield] i add in, it will be 2 column

the picture shows the expected view

but currently it is [label] [textfield] [label2] [textfield2] [label3] [textfield3]

  public WizardPage page1() {
           WizardPage page1 = new WizardPage("1", "Page 1") {
               {
                   JTextField txt1 = new JTextField();
                   JTextField txt2 = new JTextField();
                   JTextField txt3 = new JTextField();
                   JTextField txt4 = new JTextField();

                   txt1.setName("text1");
                   txt2.setName("text2");
                   txt3.setName("text3");
                   txt4.setName("text4");

                   txt1.setPreferredSize(new Dimension(50, 20));
                   txt2.setPreferredSize(new Dimension(50, 20));
                   txt3.setPreferredSize(new Dimension(50, 20));
                   txt4.setPreferredSize(new Dimension(50, 20));

                   add(new JLabel("text1"));
                   add(txt1);
                   add(new JLabel("text2"));
                   add(txt2);
                   add(new JLabel("text3"));
                   add(txt3);
                   add(new JLabel("text4"));
                   add(txt4);
               }
           };
           return page1;
       }



>    public WizardPage(String title, String description){
>        
>        PropertyConfigurator.configure("config/log4j.properties");
>        log = Logger.getLogger(WizardPage.class);
>       
>       _title = title;
>       _description = description;
>       
> 
>     setLayout(new FlowLayout()); );


      addContainerListener(new WPContainerListener());
      this.setDoubleBuffered(true);
   }

enter image description here

4

1 回答 1

3

在网格中具有未指定行数的最简单方法是使用GridLayout0 作为行数:

setLayout(new GridLayout(0, 2));

这将产生 2 列,并根据需要添加行。缺点GridLayout是标签和文本字段将具有相同的宽度,这可能不是您想要的。

另一种简单的方法是嵌套布局:您可以将每个标签 + 文本字段组合放置到 JPanel,然后根据需要继续将这些面板添加到垂直BoxLayout。这既不是完美的,也可能导致如下布局:

label | text
-----------------
long label | text

如果您需要一个可以使列和行的宽度不同的网格,请研究其他基于网格的布局:GridBagLayout带有标准库,并且能够处理此类网格,但使用起来有点复杂。如果您发现自己制作了很多这样的布局,请考虑使用第三方布局管理器,例如MiGLayout

于 2013-09-20T11:47:35.747 回答