My program has 8 JButtons and 1 JTextField. Each button should change the text in the text field to something different. I started out having an action listener for each button but i would like to link all the buttons to just 1 action listener and have it recognise which button has been pressed to execute the correct action. any ideas on how this could be done?

Recommended Answers

All 6 Replies

Create an instance of an object that implements ActionListener.
Add that object as each button's action listener.

To recognize which button, use the Event getSource() method.

Deleted

JButtons, kike all JComponents have a really useful but much neglected property called "clientProperty", which is a hashtable into which you can put whatever key/vlaue pairs you want with putClientProperty(key, value), and retrieve the values with getClientProperty(key).
Depending on how your buttons are supposed to behave you can use this to store a String, or a object, or whatever else you need to do the appropriate thing for each button. This avoids the huge if/else/else... structure you would end up with if you have to test the source for being equal to each button in turn.

The following code may help you:

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;

public class MultiButtons extends JFrame implements ActionListener{
	JButton btn[] = new JButton[3];  // define and allocate for the array of 3 buttons
	String colorName[]={"RED","BLUE","GREEN"};  // the string on each button
	Color color[] = {Color.red, Color.blue, Color.green}; // Color array
    Container container;
    
    
	public MultiButtons(){
	JPanel p = new JPanel(); // create a sub container to have 3 buttons
	for (int i=0; i<btn.length;i++){ // create button and add ActionListener for each button.
		btn[i]= new JButton(colorName[i]);
		btn[i].addActionListener(this);
		btn[i].putClientProperty( "JButton.buttonType", "roundRect" ); // setup clientProperty, as JamesCherrill indicated.
		p.add(btn[i]);// put each button into the sub container
                  }
	container= getContentPane(); // The JFrame has the default layout manager: BorderLayout
	container.add(p, BorderLayout.NORTH); // the subcontainer holding 3 buttons is placed in the NORTH area
	container.setBackground(color[0]); // initial background is red in color
	setSize(400,200);
	setVisible(true);
	}	
	
	public void actionPerformed(ActionEvent e){ // the ActionListener monitoring 3 buttons.  
		for (int i=0; i<btn.length;i++) // using for loop to scan buttons
		if (btn[i]== e.getSource()){ // the button[i] is being pressed
		container.setBackground(color[i]); // re-set background color accordingly
		break;
		}
		}
	public static void main(String args[]){
	MultiButtons mb= new MultiButtons();
	mb.setDefaultCloseOperation(2);
	}
}

e.g.
In my machine, the line code:
btn.putClientProperty( "JButton.buttonType", "roundRect" );
was not working
I tried putClientProperty() in different way. It ended with no changes in buttons' apprearence at all.

Couple of comments:
Emb.setDefaultCloseOperation(2); // what is the 2 here? Use defined constants not their value

was not working

Please explain.

The idea of using a components property table is to save info for that component that can be retrieved later. For example if you wanted to save a color. Use a name/key like: "MyColor" and say a reference to a Color object: theColor
putClientProperty( "MyColor", theColor ); // save the color

Later you get the color object back by:
Color theColor = (Color)getClientProperty("MyColor"); // get what I saved earlier

line 36 is not correct.
The correct code:

mb.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);// The value of the defined constant JFrame.EXIT_ON_CLOSE is 3

Thank you, NormR1 for your coments.

was not working

I will have a close look at tutorial on the issue of putClientProperty.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.