你这个程序就是卡片布局了,有2个小错误就是没有对p,c1定义为final.我帮你修改好了 import java.awt.*; import java.awt.event.*; public class XtLcb extends Frame { public static void main(String args[]) { Frame frame = new Frame(); frame.setBackground(Color.lightGray); frame.setSize(400,400); frame.setVisible(true); final CardLayout cl = new CardLayout();
MenuBar menuBar = new MenuBar(); Menu menuFile = new Menu(); MenuItem menuFileExit = new MenuItem(); MenuItem menuFileOpen = new MenuItem(); MenuItem menuFileOn = new MenuItem();
final Panel p = new Panel(); p.setLayout(cl); Panel p1 = new Panel(); Panel p2 = new Panel(); p1.add(new Label(Open)); p2.add(new Label(On)); p.add(p1,1); p.add(p2,2); frame.add(p);
// Add action listener.for the menu button menuFileExit.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } } ); menuFileOpen.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { cl.show(p,1); } }
); menuFileOn.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { cl.show(p,2); } } ); menuFile.add(menuFileOpen); menuFile.add(menuFileOn); menuFile.add(menuFileExit); menuBar.add(menuFile);
frame.setMenuBar(menuBar);
// Add window listener. frame.addWindowListener ( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0);
} } ); }
/** * Shutdown procedure when run as an application. */ /*void windowClosed() {
// TODO: Check if it is safe to close the application