有人能告诉我如何在多个JPanel
类之间进行导航编码,从对象(面板)本身获取JButton
的事件触发器吗?我读过CardLayout
。可以从父面板中发生的事件交换面板。我想要实现的是点击面板中嵌入的按钮,它应该消失或应该显示所需的面板。似乎无法找到解决方案。
答案 0 :(得分:3)
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) { }
}
}
答案 1 :(得分:2)
您可以使用JMenu with JMenuItems代替使用JButton切换卡片