用Java在CardLayout中显示面板
我编写了下面的代码,用于显示三个面板,具体取决于单击了三个按钮中位于底部的按钮用Java在CardLayout中显示面板,java,awt,panel,layout-manager,cardlayout,Java,Awt,Panel,Layout Manager,Cardlayout,我编写了下面的代码,用于显示三个面板,具体取决于单击了三个按钮中位于底部的按钮 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.Ac
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();
}
}
处理这三个按钮的方法会被调用,并且它们会打印到终端上单击哪个按钮,但面板不会改变。只显示第一个p 第一个!=cLayout.showcardPanel中的第一名,第一名;!=cLayout.showcardPanel,firstP;,删除actionPerformed中所有三种情况下的最后一个字符P,hmmm AFAIK awt.Frame可以从WindowListener终止,然后使用extends JFrame而不是extends Frame使用Swing JComponents而不是awt