Overlap JPanels with WindowBuilder for eclipse

梦想的初衷 提交于 2019-12-02 05:10:42

问题


I am using WindowBuilder Pro for eclipse, and I would like to have two Jpanels that perfectly overlap each other. I would then be able to toggle their visibilty based on the selection of a combox box. When I try and acheive this in the gui builder, the first panel gets displaced by the second panel. And advice please?


回答1:


I would like to have two Jpanels that perfectly overlap each other. I would then be able to toggle their visibilty based on the selection of a combox box

See: How to Use Card Layout for an example that does exactly this.




回答2:


It is possible using groupLayout, according to the tutorial .

What you must do is add the components to a mother JPanel , and set that panel to use GroupLayout.

Then add the components to the layout as a ParallelGroup in both the horizontal and vertical spacing. This means they will occupy the same X and Y space. Then disable/enable as needed, hiding the JPanels as well.

I believe the way it would work is so:

        JPanel panel1, panel2, panel3;
        //initialize panel3, etc
        panel1=new JPanel();
        panel2 = new JPanel();
        panel1.add(new JTextField("Panel1"));
        panel2.add(new JTextField("PANEL2"));

        groupLayout = new GroupLayout(panel3);

        panel3.setLayout(groupLayout);

        groupLayout.setHorizontalGroup(
        groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(panel1)
            .addComponent(panel2)
        );
        groupLayout.setVerticalGroup(
            groupLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addComponent(panel1)
            .addComponent(panel2)
        );
        panel1.setEnabled(false);
        panel1.setVisible(false);

then add a jCheckBox with an ActionPerformed method containing:

if(panel1.isEnabled()) {
    panel1.setEnabled(false);
    panel1.setVisible(false);
    panel2.setEnabled(true);
    panel2.setVisible(true);

}else
 if(panel2.isEnabled()) {
    panel2.setEnabled(false);
    panel2.setVisible(false);
    panel1.setEnabled(true);
    panel1.setVisible(true);

}

That produced the desired behaviour for me. You should be able to switch the JComboBox for the JCheckBox fairly easily.

EDIT: Removed the necessity of having "Jpanel of their own". That should not be the case, and the above method allows you to get the benefits of both GroupLayout and CardLayout.




回答3:


I would like to have two Jpanels that perfectly overlap each other.

I believe the CardLayout is there exactly for that reason.

Basically, you can nest different panels or 'Cards' using the CardLayout and set the appropriate card to be displayed programmatically (on some event).



来源:https://stackoverflow.com/questions/8594306/overlap-jpanels-with-windowbuilder-for-eclipse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!