各位前辈们,Java实现菜单对面板的切换,但我写的代码为什么切换不了面板,求解答!
编程的人 2015-06-19 09:26:28 import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.HeadlessException;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JPanel;
public class CutPanel1 extends JFrame{
public static void main(String[] args){
new CutPanel1().setVisible(true);
}
private JMenuBar menuBar;
private JCheckBoxMenuItem jcm1;
private JCheckBoxMenuItem jcm2;
private CardLayout layout = new CardLayout(0,0);
private JPanel panel = new JPanel();;
public CutPanel1(){
getContentPane().add(panel,BorderLayout.CENTER);
panel.setLayout(layout);
menuBar = createMenu();
this.setJMenuBar(menuBar);
this.setSize(400,300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//this.setVisible(true);
}
public JMenuBar createMenu() {
// TODO Auto-generated method stub
JMenuBar menubar = new JMenuBar();
JMenu menu = new JMenu("面板切换");
menu.add(jcm1 = new JCheckBoxMenuItem("red"));
jcm1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JPanel panel1 = new JPanel();
//panel1.add(new JButton("xx"));
panel.add(panel1,"red");
layout.show(panel, e.getActionCommand());
}
});
menu.add(jcm2 = new JCheckBoxMenuItem("yellow"));
jcm2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
JPanel panel2 = new JPanel ();
//panel2.add(new JButton("yy"));
panel.add(panel2,"yellow");
layout.show(panel,e.getActionCommand());
}
});
menubar.add(menu);
return menubar;
//JCheckBoxMenuItem jcm1 = new JCheckBoxMenuItem("red");
//JCheckBoxMenuItem jcm2 = new JCheckBoxMenuItem("yellow");
}
}