b1,b2是构造函数中的局部变量,actionPerformed方法中当然不能访问。
简单的解决方法是把b1,b2定义为该类的私有字段就行了

解决方案 »

  1.   

    同意
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;public  class ButtonTest
    {
             JButton b1,b2;
    public static void main(String[] args)
    {
    ButtonFrame f=new ButtonFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.show();

    }
    }
    class ButtonFrame extends JFrame
    {
    public ButtonFrame()
    {
    setTitle("wwww");
    setSize(300,200);
    ButtonPanel panel1=new ButtonPanel();
    Container contentPane=getContentPane();
    contentPane.add(panel1);
    }
     
    }
    class ButtonPanel extends JPanel
    implements ActionListener
    {
    public ButtonPanel()
    {
    b1=new JButton("yellow");
    b2=new JButton("red");

    add(b1);
    add(b2);

    b1.addActionListener(this);
    b2.addActionListener(this);

    }

    public void actionPerformed(ActionEvent Event)
    {
    Object s=Event.getSource();
    if(s==b1)
    {
    setBackground(Color.YELLOW);
    }
    else if(s==b2)
    {
    setBackground(Color.RED);
    }
    }

    }