Swing Card Layout更改面板由用户显示

时间:2013-12-13 12:23:44

标签: java swing jpanel cardlayout

我正在编写一个接口,其中有一个JFrame类和两个JPanel类。首次执行脚本时,将显示Panel A.我在面板A中有一个JButton,我希望在点击时显示面板B而不是面板A.

我有什么方法可以做到这一点吗?

1 个答案:

答案 0 :(得分:5)

为此阅读tutorial

您可以使用next() CardLayout方法显示下一张卡片,

或者您可以使用show(...);来显示特定的卡片。

简单示例:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Example {

    public static void main(String[] args){
        JFrame frame = new JFrame();

        final JPanel panel = new JPanel(new CardLayout());

        JLabel l1 = new JLabel("1");
        JLabel l2 = new JLabel("2");
        JLabel l3 = new JLabel("3");

        panel.add(l1,"l1");
        panel.add(l2,"l2");
        panel.add(l3,"l3");

        JButton btn = new JButton("next");
        btn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                CardLayout layout = (CardLayout) panel.getLayout();
                layout.next(panel);
            }
        });

        JButton btnSpec = new JButton("l3");
        btnSpec.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                CardLayout layout = (CardLayout) panel.getLayout();
                layout.show(panel, "l3");
            }
        });

        frame.add(panel);
        frame.add(btn,BorderLayout.SOUTH);
        frame.add(btnSpec,BorderLayout.NORTH);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

}