简体   繁体   English

用户操作时显示的“ Swing Card Layout”更改面板

[英]Swing Card Layout change panel displayed on action by user

I'm currently writing an interface where a have a JFrame class and two JPanel classes. 我目前正在编写一个接口,其中有一个JFrame类和两个JPanel类。 When the script is first executed, Panel A is shown. 首次执行脚本时,将显示面板A。 I have a JButton in Panel A which I would like, when clicked, to display Panel B instead of Panel A. 我在面板A中有一个JButton ,当我单击该按钮时,我想显示面板B而不是面板A。

Is there any way I could do this? 有什么办法可以做到吗?

Read tutorial for that. 阅读教程

You can use next() method of CardLayout for showing next card, 您可以使用CardLayout next()方法显示下一张卡片,

or you can use show(...); 或者您可以使用show(...); for showing specific card. 用于显示特定的卡片。

Simple example: 简单的例子:

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

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM