Problems with actionListener

Hi, I'm having som problems with getSource.

I realize that actionPerformed doesn't recognize the JButtons because of the scope, but as far as I can tell, I have done it like the examples I have followed.

package gui;

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

publicclass NumericPanelextends JPanelimplements ActionListener{

public NumericPanel(){

setLayout(new GridLayout(4,3));

//Generating Buttons

JButton b1 =new JButton("1");

JButton b2 =new JButton("2");

JButton b3 =new JButton("3");

JButton b4 =new JButton("4");

JButton b5 =new JButton("5");

JButton b6 =new JButton("6");

JButton b7 =new JButton("7");

JButton b8 =new JButton("8");

JButton b9 =new JButton("9");

JButton bClear =new JButton("Clear");

JButton b0 =new JButton("0");

JButton bEnter =new JButton("Enter");

setLayout(new GridLayout(4,3));

add(b1);

add(b2);

add(b3);

add(b4);

add(b5);

add(b6);

add(b7);

add(b8);

add(b9);

add(bClear);

add(b0);

add(bEnter);

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

b4.addActionListener(this);

b5.addActionListener(this);

b6.addActionListener(this);

b7.addActionListener(this);

b8.addActionListener(this);

b9.addActionListener(this);

b0.addActionListener(this);

bEnter.addActionListener(this);

bClear.addActionListener(this);

}

publicvoid actionPerformed(ActionEvent e){

Object button = e.getSource();

if(button = b1){// Says it doesn't recognize b1 - how am I supposed to do this?!

}

}

}

[3624 byte] By [hogla] at [2007-11-27 7:38:59]
# 1

public class NumericPanel extends JPanel implements ActionListener {

JButton b1,b2,b3;//etc

public NumericPanel(){

setLayout(new GridLayout(4,3));

//Generating Buttons

b1 = new JButton("1");

b2 = new JButton("2");

b3 = new JButton("3");

Michael_Dunna at 2007-7-12 19:19:33 > top of Java-index,Desktop,Core GUI APIs...
# 2
Thanks a lot.. Makes sense
hogla at 2007-7-12 19:19:33 > top of Java-index,Desktop,Core GUI APIs...
# 3

> I have done it like the examples I have followed.

Check out the example in the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/button.html]How to Use Buttons[/url] which uses the "action command" instead of checking the button.

An even better way is to write generic code when possible so you con't have to check which button was clicked as demonstrated in this simple example:

http://forum.java.sun.com/thread.jspa?forumID=57&threadID=609795

You can always use multiple listeners, one for the numbers on one for the other buttons.

camickra at 2007-7-12 19:19:33 > top of Java-index,Desktop,Core GUI APIs...
# 4
In your "if[/b]" in the actionListeneryou have to compare with ==not with only one =
Leo77a at 2007-7-12 19:19:33 > top of Java-index,Desktop,Core GUI APIs...