d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Java Button Questions
Add Reply New Topic New Poll
Member
Posts: 33,402
Joined: Feb 19 2006
Gold: 312.85
Apr 28 2014 10:28pm
If you create a button like

text.add(new JButton("Example"));

how do you code what happens on that button press if the button doesn't have a name?
Member
Posts: 32,925
Joined: Jul 23 2006
Gold: 3,804.50
Apr 28 2014 10:42pm
JButton myButton = new JButton("Example");
myButton.addActionListener(whoeverHandlesEvents);
text.add(myButton);

where whoeverHandlesEvents implements the ActionListener interface. could be your panel, inner class, anonymous class, or none of the above.

when you say "doesn't have a name", i assume you mean you don't have a variable to hold the reference to the object. So create a variable to hold the reference.

This post was edited by carteblanche on Apr 28 2014 10:44pm
Member
Posts: 4,728
Joined: Jan 15 2008
Gold: 4,102.02
Apr 29 2014 09:39am
While far from ideal, you could use the text of your button to filter which button was pressed in your event handling class/whatever youre using for it.

IE In a class implementing ActionListener where you usually check the source of your event and compare it to your buttons by the variable holding the actual object, you could simply do (event is your ActionEvent parameter)

if(((JButton) event.getSource()).getText().equals("Example")){
// Actions
}

or

JButton target = (JButton) event.getSource();

if (target.getText().equals("Example"))
{
// Actions
}

Which is clearer if you're validating more than one button at once, but this is only if you have a situation where you can't assign a variable to it and just compare the objects afterwards (which I can't think of any situation where this would happen)

This post was edited by sBPuR3 on Apr 29 2014 09:51am
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll