我编写了以下代码,用于显示三个面板,具体取决于点击底部的三个按钮中的哪一个。
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class cart extends Frame implements ActionListener {
Panel cardPanel;
Panel firstP, secondP, thirdP;
Panel buttonP;
Button b1, b2, b3;
CardLayout cLayout;
cart() {
cardPanel = new Panel();
cLayout = new CardLayout();
cardPanel.setLayout(cLayout);
firstP = new Panel();
firstP.setBackground(Color.blue);
secondP = new Panel();
secondP.setBackground(Color.red);
thirdP = new Panel();
thirdP.setBackground(Color.yellow);
b1 = new Button("first");
b2 = new Button("Second");
b3 = new Button("Third");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
buttonP = new Panel();
buttonP.add(b1);
buttonP.add(b2);
buttonP.add(b3);
add(buttonP, BorderLayout.SOUTH);
add(cardPanel, BorderLayout.CENTER);
cardPanel.add("first", firstP);
cardPanel.add("second", secondP);
cardPanel.add("third", thirdP);
setSize(400, 500);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void WindowClosing(WindowEvent e) {
System.exit(0);
}
});
}// constructor ends here
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
cLayout.show(cardPanel, "firstP");
System.out.print("first");
}
else if (e.getSource() == b2) {
cLayout.show(cardPanel,"secondP");
System.out.print("second");
}
else if (e.getSource() == b3) {
cLayout.show(cardPanel, "thirdP");
}
}
public static void main(String args[]) {
new cart();
}
}
处理这三个按钮的方法被调用,并且它们也会打印到终端点击哪个按钮但面板不会改变。它只是可见的第一个按钮。