就是按下red或blue的时候,背景的颜色不改变
import javax.swing.*;
import java.awt.*;
import java.awt.event .*;public class Test1{
public static void main(String[] args){
TestFrame frame = new TestFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}class TestFrame extends JFrame{
public TestFrame(){
setTitle("wa haha");
setSize(width,height);

JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);

JMenu editMenu = new JMenu("Edit");
menuBar.add(editMenu);
JMenu helpMenu = new JMenu("Color");
menuBar.add(helpMenu);
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem red = new JMenuItem("red");
helpMenu.add(red);
red.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
setBackground(Color.BLUE);
}
}
);
JMenuItem blue = new JMenuItem("blue");
helpMenu.add(blue);
blue.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent event){
setBackground(Color.BLUE);
}
}
);
}
private static final int width = 300;
private static final int height = 200;
}

解决方案 »

  1.   

    这样就OK了:import javax.swing.*;
    import java.awt.*;
    import java.awt.event .*;public class Test1{
    public static void main(String[] args){
    TestFrame frame = new TestFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    }
    }class TestFrame extends JFrame{
    public TestFrame(){
    setTitle("wa haha");
    setSize(width,height);JMenuBar menuBar = new JMenuBar();
    setJMenuBar(menuBar);JMenu editMenu = new JMenu("Edit");
    menuBar.add(editMenu);
    JMenu helpMenu = new JMenu("Color");
    menuBar.add(helpMenu);
    JMenu fileMenu = new JMenu("File");
    menuBar.add(fileMenu);
    JMenuItem red = new JMenuItem("red");
    helpMenu.add(red);
    red.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent event){
    getContentPane().setBackground(Color.RED);
    }
    }
    );
    JMenuItem blue = new JMenuItem("blue");
    helpMenu.add(blue);
    blue.addActionListener(
    new ActionListener(){
    public void actionPerformed(ActionEvent event){
    getContentPane().setBackground(Color.BLUE);
    }
    }
    );
    }
    private static final int width = 300;
    private static final int height = 200;
    }
      

  2.   

    setBackground(Color.BLUE);
    改成getContentPane().setBackground( Color.BLUE );
    还有你两次都是blue