使用值

时间:2016-04-21 09:19:25

标签: java swing jpanel layout-manager grouplayout

我目前正在尝试将Jpanel添加到JpanelLayout的水平组中。添加的自定义JPanel的数量由int值定义(将由用户定义)。我试图根据用户的要求将尽可能多的相同JPanel添加到父面板中。目前我已经尝试定义了一些自定义Jpanel,将它们添加到arraylist然后为每个循环执行a,尝试将它们添加到组中,但没有成功。这就是水平组布局代码的样子:

// initialization of custom panels and adding them to arraylist for adding into horizontalgroup.
MatchPanel customPanel1 = new MatchPanel();
    MatchPanel customPanel2 = new MatchPanel();
    MatchPanel customPanel3 = new MatchPanel();

    ArrayList<MatchPanel>panels = new ArrayList<MatchPanel>();

    panels.add(customPanel1);
    panels.add(customPanel2);
    panels.add(customPanel3);

// Panel being initialized later in program        
 javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
    jPanel5.setLayout(jPanel5Layout);
    jPanel5Layout.setHorizontalGroup(
        jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel5Layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                for(MatchPanel p : panels) {
                .addComponent(p,javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                })
            .addContainerGap(82, Short.MAX_VALUE))
        .addGroup(jPanel5Layout.createSequentialGroup()
            .addGap(233, 233, 233)
            .addComponent(jLabel1)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

有没有办法定义Horizo​​ntalGroup,然后使用程序其余部分中定义的函数向其添加组件,或者仅仅是我的语法错误的情况? 如果我可以使这个工作,我也可以将方法转移到垂直组。

感谢您提供的任何帮助。

1 个答案:

答案 0 :(得分:2)

这是一个可能的解决方案。希望对您有所帮助。

预览:

Preview of Group Layout with objects created at runtime

package sampleapp.ui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import static java.lang.Integer.parseInt;
import java.util.ArrayList;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;

/**
 *
 * @author brianson
 */

public class GroupLayoutExample extends JFrame {
    private int elementsHeight;             //the height of all objects in the panel and the gaps between them
    private int numButtons;
    private ArrayList<JButton> btnArray;    //the array object that will hold the buttons created at runtime
    private JPanel panel;
    private JLabel label1;
    private JTextField textField1;
    private JButton button1;

    public GroupLayoutExample() {
        init();
    }

    public final void init(){
        //initiallize variables
        panel = new JPanel();
        elementsHeight = 22;                //initiallized with the value of 22 ie the size of the first and last container gaps
        label1 = new JLabel("Number of buttons");
        textField1 = new JTextField("");
        button1 = new JButton("Show Buttons");

        setPreferredSize(new Dimension(800, 600));
        setSize(800, 600);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        panel.setPreferredSize(new Dimension(101, 234));
        panel.setSize(101, 294);
        panel.setBackground(new Color(153, 153, 153));

        button1.addActionListener((e) -> {
            numButtons = parseInt(textField1.getText());
            if (numButtons > 1 && numButtons < 7) {
                if (panel.getComponentCount() > 0) {
                    panel.removeAll();
                }
                makeButtons(numButtons);
            }else{
                JOptionPane.showMessageDialog(null, "Number of buttons must be greater than 1 but less than 7");
            }
        });
        textField1.setBorder(new EmptyBorder(1, 10, 1, 1));

        //main window layout
        GroupLayout mainLayout = new GroupLayout(getContentPane());
        getContentPane().setLayout(mainLayout);
        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup()
            .addGroup(mainLayout.createSequentialGroup()
                .addContainerGap(202, Short.MAX_VALUE)
                .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(mainLayout.createParallelGroup()
                    .addGroup(mainLayout.createSequentialGroup()
                        .addComponent(label1)
                        .addGap(18, 18, 18)
                        .addComponent(textField1, GroupLayout.PREFERRED_SIZE, 176, GroupLayout.PREFERRED_SIZE)
                    )
                    .addComponent(button1)
                )
                .addContainerGap(203, Short.MAX_VALUE)

            )
        );
        mainLayout.setVerticalGroup(mainLayout.createParallelGroup()
            .addGroup(mainLayout.createSequentialGroup()
                .addContainerGap(197, Short.MAX_VALUE)
                .addGroup(mainLayout.createParallelGroup()
                    .addComponent(panel, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                    .addGroup(mainLayout.createSequentialGroup()
                        .addGroup(mainLayout.createParallelGroup()
                            .addComponent(label1, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                            .addComponent(textField1, GroupLayout.PREFERRED_SIZE, 30, GroupLayout.PREFERRED_SIZE)
                        )
                        .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(button1)
                    )
                )
                .addContainerGap(112, Short.MAX_VALUE)
            )
        );
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            new GroupLayoutExample().setVisible(true);
        });
    }

    void makeButtons(int num){
        GroupLayout layout = new GroupLayout(panel);
        panel.setLayout(layout);

        //horizontal layout
        GroupLayout.ParallelGroup horizontalPara = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        GroupLayout.ParallelGroup horizontalPara1 = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        GroupLayout.SequentialGroup horizontalSeq = layout.createSequentialGroup();
        horizontalSeq.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
        btnArray = new ArrayList<>();
        for(int i = 0; i < numButtons; i++) {
            btnArray.add(new JButton(String.format("Button %d", i + 1)));
        }

        btnArray.forEach((btn) -> {
            horizontalPara1.addComponent(btn);
        });
        horizontalSeq.addGroup(horizontalPara1);
        horizontalSeq.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE);
        horizontalPara.addGroup(horizontalSeq);
        layout.setHorizontalGroup(horizontalPara);

        //Vertical layout
        GroupLayout.ParallelGroup verticalPara = layout.createParallelGroup(GroupLayout.Alignment.LEADING);
        GroupLayout.SequentialGroup verticalSeq = layout.createSequentialGroup();
        verticalSeq.addContainerGap();
        elementsHeight += (btnArray.size() * 22);   //Adding the total height of buttons. Button default height is 22
        btnArray.forEach((btn) -> {
            verticalSeq.addComponent(btn);
            int i = (btnArray.size() - 1) - btnArray.indexOf(btn);
            //displayInfo(i + "", "Case ID");
            switch (i) {
                case 0:
                    verticalSeq.addContainerGap(11, Short.MAX_VALUE);
                    break;

                case 1:
                    int gapSize = panel.getHeight() - elementsHeight;       //Calculate size of gap so that the last component is placed at the bottom baseline
                    if (gapSize <= 0) {
                        gapSize = 11;
                    }
                    verticalSeq.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED, gapSize, Short.MAX_VALUE);
                    break;

                default:
                    verticalSeq.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED);
                    elementsHeight += 11;       //The height for an unrelated component placement is 11
                    break;
            }
        });
        verticalPara.addGroup(verticalSeq);
        layout.setVerticalGroup(verticalPara);
    }
}

工作原理: 在这种情况下,首先为您的各种“组布局”方向创建变量,我有并行和顺序的组。根据要实现的布局,将在运行时创建的对象添加到相应的并行和顺序组中。有关在这些组中放置对象的更多信息,请参阅How to Use Group Layout(The Java™ Tutorials)

将组件添加到组中之后,将水平和垂直布局组设置为适当的并行和顺序组。