用另一个替换面板

时间:2016-11-20 15:29:40

标签: java swing jframe jpanel

如何替换JPanelJFrame&amp;它的内容与另一个通过简单的按钮点击同一个容器?<​​/ p>

2 个答案:

答案 0 :(得分:0)

技巧是使用CardLayout或修改面板可见性。 请查看以下修改面板可见性的示例。

public class PanelExample {
private JPanel _myPanel1,_myPanel2;
public void init() {
    JFrame frame = new JFrame("Testing");
    JPanel mainPanel = new JPanel(new GridBagLayout());

    _myPanel1 = new JPanel();
    _myPanel1.add(new JLabel("Panel 1"));
    _myPanel1.setVisible(true);

    _myPanel2 = new JPanel();
    _myPanel2.add(new JLabel("Panel 2"));
    _myPanel2.setVisible(false);

    JButton button = new JButton("Switch to Panel2");
    button.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            if(_myPanel1.isVisible()) {
                _myPanel1.setVisible(false);
                _myPanel2.setVisible(true);
                button.setText("Switch to Panel1");
            } else {
                _myPanel1.setVisible(true);
                _myPanel2.setVisible(false);
                button.setText("Switch to Panel2");
            }

        }
    });

    GridBagConstraints gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 0;
    gbc.anchor = GridBagConstraints.PAGE_START;
    gbc.fill = GridBagConstraints.HORIZONTAL;
    gbc.weightx = 1;
    gbc.weighty = 0;

    mainPanel.add(button,gbc);

    gbc = new GridBagConstraints();
    gbc.gridx = 0;
    gbc.gridy = 1;
    gbc.anchor = GridBagConstraints.CENTER;
    gbc.fill = GridBagConstraints.BOTH;
    gbc.gridwidth = 2;
    gbc.gridheight = 2;
    gbc.weightx = 1;
    gbc.weighty = 1;
    mainPanel.add(_myPanel1,gbc);
    mainPanel.add(_myPanel2,gbc);

    frame.add(mainPanel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}
public static void main(String[] args) {
    PanelExample exmp = new PanelExample();
    exmp.init();
}

}

答案 1 :(得分:0)

这里有一个简单的示例,您可以关注,请尽快显示代码,以便我们可以通过不知情的来源(旧的)快速跟踪您的问题

inputFields