gpt4 book ai didi

java - 在多个面板之间导航

转载 作者:行者123 更新时间:2023-12-01 17:31:00 27 4
gpt4 key购买 nike

谁能告诉我如何在多个 JPanel 类之间进行编码,从对象(面板)本身获取来自 JButton 的事件触发器?我读过有关 CardLayout 的内容。该面板可以根据父面板中发生的事件进行交换。我想要实现的是单击嵌入在面板中的按钮,它应该消失或者应该显示所需的面板。似乎找不到解决方案。

最佳答案

CardLayout 中没有任何内容可以阻止卡内子级操作切换卡。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Testing extends JFrame {

private JPanel cardHolder;
private CardLayout cards;
private static final String cardA = "A";
private static final String cardB = "B";

private class Switcher implements ActionListener{
String card;
Switcher(String card) { this.card = card; }
@Override
public void actionPerformed(ActionEvent e) {
cards.show(cardHolder, card);
}
}

private void run() {
setDefaultCloseOperation(EXIT_ON_CLOSE);

JPanel pa = new JPanel();
JButton ba = new JButton("Switch to B");
ba.addActionListener(new Switcher(cardB));
pa.add(ba);
pa.setBackground(Color.CYAN);

JPanel pb = new JPanel();
JButton bb = new JButton("Switch to A");
bb.addActionListener(new Switcher(cardA));
pb.add(bb);
pb.setBackground(Color.MAGENTA);

cardHolder = new JPanel();
cards = new CardLayout();
cardHolder.setLayout(cards);
cardHolder.add(pa, cardA);
cardHolder.add(pb, cardB);
add(cardHolder);
pack();
setVisible(true);
}

public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
new testing().run();
}
});
} catch (Exception ex) { }
}
}

关于java - 在多个面板之间导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10901352/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com