0

我在 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))
        );

乐:

对于按钮:

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))
        );

    }
4

2 回答 2

1

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

于 2011-05-05T12:27:13.913 回答
0

Use a CardLayout.

于 2011-05-05T12:41:45.613 回答