Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Taking a label from a JButton?

Status
Not open for further replies.

jisoo22

Programmer
Apr 30, 2001
277
US
Hello all =)

Does anyone know if there is a method that will take in a JButton's label as a string? I've looked through the java API everywhere and can't seem to find one that'll do the job. What I'm doing is making a simple calculator that, when a number button is clicked, it will invoke an ActionListener method which will toss the appropriate number into the text field. But instead of creating a new ActionListener method for each number, I'd like to make it cleaner and just make a single one that'll do all the jobs. Hence the method that returns a JButton label. A short example of what I'm doing is below. If anyone has any other suggestions, I'm open to them =)

Thanks!
Jisoo22

Code:
//JButton construction
JButton zeroButton = new JButton("0");
zeroButton.setPreferredSize(new Dimension(40, 20));
zeroButton.addActionListener(new numListener());
....
//ActionListener method
class numListener implements ActionListener
{
	public void actionPerformed(ActionEvent e)
	{
        String str = ??? //Take in label here
		displayField.setText(str);
		num1 = 0;
	}
}
 
Hi Jisoo22,

JButton extends AbstractButton, which has a method getText(), which will return the button label. You may experience difficulty referencing your JButton from the inner ActionListener class. The following does the same but uses an anonymous inner class to get access to the getText() method.

//JButton construction
final JButton zeroButton = new JButton("0");
zeroButton.setPreferredSize(new Dimension(40, 20));
zeroButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String str = zeroButton.getText();
displayField.setText(str);
num1 = 0;
}
});

HTH,
scrat


 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top