import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class Frame extends JFrame implements ActionListener
{Frame()
 {JButton button1=new JButton("yellow");
  JButton button2=new JButton("red");
  JButton button3=new JButton("blue");
  setLayout(new FlowLayout());
  add(button1);
  add(button2);
  add(button3);
    button1.addActionListener(this);
  button2.addActionListener(this);
  button3.addActionListener(this);
  setBounds(100,100,300,300);
  }
public void actionPerformed(ActionEvent e)
{if(e.getSource()==button1)
 {button1.setBackground(Color.YELLOW);
  }
 if(e.getSource()==button2)
  {button2.setBackground(Color.RED);
   }
 if(e.getSource()==button3)
   {button3.setBackground(Color.BLUE);
    }
}
JButton button1,button2,button3;}
public class Eva
{public static void main(String args[])
 {Frame frame=new Frame();
  frame.setVisible(true);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
}
我想让按钮改变颜色,为什么变不了呢。

解决方案 »

  1.   

    注意一下元件的定義~import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class Frame extends JFrame implements ActionListener
    {
    JButton button1=new JButton("yellow");
      JButton button2=new JButton("red");
      JButton button3=new JButton("blue");
    Frame()
     {
      setLayout(new FlowLayout());
      add(button1);
      add(button2);
      add(button3);
         button1.addActionListener(this);
      button2.addActionListener(this);
      button3.addActionListener(this);
      setBounds(100,100,300,300);
      }
    public void actionPerformed(ActionEvent e)
    {if(e.getSource()==button1)
     {button1.setBackground(Color.YELLOW);
      }
     if(e.getSource()==button2)
      {button2.setBackground(Color.RED);
      }
     if(e.getSource()==button3)
      {button3.setBackground(Color.BLUE);
      }
    }}
    public class Eva
    {public static void main(String args[])
     {Frame frame=new Frame();
      frame.setVisible(true);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      }
    }
      

  2.   

    如LS说的
    Frame()
     {JButton button1=new JButton("yellow"); //这里的button1,2,3是局部变量,
      JButton button2=new JButton("red");    //把前面的JButton都去掉
      JButton button3=new JButton("blue");
      

  3.   

    楼上说的对,为什么不用swt呢