动态GUI大小

时间:2011-05-05 12:22:18

标签: java resize jpanel jlayeredpane

我在GUI应用程序中调整某些JPanel的大小时出现此问题。该应用程序有一个主JLayeredPane,其中包含2个其他JPanel。在JPanel 1中,我有一个登录表单和一个按钮。当我按下按钮时,我想让第一个JPanel不可见,第二个JPanel可见(此面板比第一个更大),但仍保持相同的大小。贝娄是一些相关的代码。任何人都可以帮助我吗?

int width=300, height=300;
JLayeredPane mainPanel;
JPanel panel1;
JPanel panel2;

panel1.setBounds(0,0,width,height);
panel1.setBackground(new Color(251, 249, 236));
mainPanel.add(panel1, JLayeredPane.DEFAULT_LAYER);

panel2.setBounds(0, 0, width+200, height+200);
panel2.setBackground(new Color(255, 0, 0));
mainPanel.add(panel2, JLayeredPane.DEFAULT_LAYER);

点击按钮代码:

setSize(width+200, height+200);
    panel1.setVisible(false);
    panel2.setVisible(true);
    mainPanel.setSize(width+200, height+200);
    mainPanel.validate();
    mainPanel.repaint();

以下是JLayredPane的一些代码:

GroupLayout mainLayout=new GroupLayout(getContentPane());
        getContentPane().setLayout(mainLayout);

        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, width, GroupLayout.PREFERRED_SIZE))
        );
        mainLayout.setVerticalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, height, GroupLayout.PREFERRED_SIZE))
        );

LE

按钮:

setSize(width+200, height+200);

        mainPanel.setSize(width+200, height+200);
        mainPanel.remove(panel1);
        mainPanel.remove(panel2);
        mainPanel.add(panel2, JLayeredPane.DEFAULT_LAYER);
        actualizare();
        mainPanel.validate();
        mainPanel.repaint();
        validate();
        repaint();

功能:

void actualizare(){
        GroupLayout mainLayout=new GroupLayout(getContentPane());
        getContentPane().setLayout(mainLayout);

        mainLayout.setHorizontalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, width+200, GroupLayout.PREFERRED_SIZE))
        );
        mainLayout.setVerticalGroup(mainLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addGroup(mainLayout.createSequentialGroup()
                    .addComponent(mainPanel, GroupLayout.PREFERRED_SIZE, height+200, GroupLayout.PREFERRED_SIZE))
        );

    }

2 个答案:

答案 0 :(得分:1)

尝试在最后调用validate()和repaint()。

答案 1 :(得分:0)

使用CardLayout