import java.awt.*;
import java.awt.event.*;
import javax.swing.*;class FirstPanel extends JPanel
      implements ActionListener
{     public FirstPanel()
      {      JButton redButton = new JButton("Red");//你在这个地方不应该再定义三个JButton,你把这三个button前的JButton去掉就可以了!你试试!
             JButton blueButton = new JButton("Blue");
             JButton yellowButton = new JButton("Yellow");             add(redButton);
             add(blueButton);
             add(yellowButton);             redButton.addActionListener(this);
             blueButton.addActionListener(this);
             yellowButton.addActionListener(this);
      }      public void actionPerformed(ActionEvent evt)
      {     Object source = evt.getSource();
            Color color = getBackground();
            if (source == redButton) color = Color.red;
            else if (source == blueButton) color = Color.blue;
            else if (source == yellowButton) color = Color.yellow;
            setBackground(color);
            repaint();
      }
      private JButton redButton;
      private JButton blueButton;
      private JButton yellowButton;
}
class FirstFrame extends JFrame
{     public FirstFrame()
      {      setTitle("FirstFrame");
             setSize(300, 200);
             addWindowListener(new WindowAdapter()
             {    public void windowClosing(WindowEvent e)
                  {      System.exit(0);
                  }
             });
         
          Container contentPane = getContentPane();
          contentPane.add(new FirstPanel());
      }
}public class FirstTest
{      public static void main(String[] args)
       {      JFrame frame = new FirstFrame();
              frame.setVisible(true);
       }
}

解决方案 »

  1.   

    错误在于
          private JButton redButton;
          private JButton blueButton;
          private JButton yellowButton;
    然后构造器中再
                 JButton redButton = new JButton("Red");
                 JButton blueButton = new JButton("Blue");
                 JButton yellowButton = new JButton("Yellow");
    明白 ? 一开始偶也被迷惑了. . . . .
      

  2.   

    真的阿!
    我不明白为什么要有private JButton redButton;这几句话,作用是什么阿?
    为什么有了这几句话前面加上JButton就无法改变颜色呢?请赐教!
      

  3.   

    你在构造函数中又定义了一组button,这是不对的!因为你在构造函数中定义的button只会在你的构造函数中有效,而在你的perform方法中就不知道是什么了!所以你的这组button应该在定义成成员变量,而不是一个方法中的变量!
      

  4.   

    cow
    被你打败了
    很简单,在构造器中你的JButton redButton跟private JButton redButton根本就不是同一个JButton,作用域不同 !
    看来你一点基础知识也没有呀. ..good good study,day day up !