Reputation: 1
Trying to add a getName()
method to a setName()
based on this method void java.awt.Component.setName(String arg0)
but without luck. The button below is loaded into the contentPane.
I need to add an actionlistener to a button instantiated in this method (either based on setName or something else similar):
public JButton JButtonComponent(String btnRef) {
button = new JButton("Convert to binary");
button.setMaximumSize(new Dimension(width/4,unitHeight));
button.addActionListener(this);
button.setName("Binary"); // my set name
return button;
}
This is my actionPerformed method:
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(e.getSource());
}
And the above system print outputs:
javax.swing.JButton[Binary,270,14,90x33,alignmentX=0.0,alignmentY=0.5,flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=Convert,defaultCapable=true]
My question is how do i get the name value i've defined in JButtonComponent from the ActionEvent? - The setName value is clearly in the ActionEvent e but no method seems to be right for the object to extract the value so i can do a compare. And is this the best method to define an "id" like you would in HTML if you were to compare?
Upvotes: 0
Views: 132
Reputation: 324118
either based on setName or something else similar
Don't use getName/setName for something like this.
There is already an API that allows you to use an "action command".
For a JButton
you can use:
button.setActionCommand("Binary");
Then in the ActionListener
you use:
String command = e.getActionCommand();
The setName value is clearly in the ActionEvent
No it isn't. A reference to the source object is contained in the ActionEvent. You need to first access the source before you can access the methods of the source object:
JButton button = (JButton)e.getSource();
System.out.println( button.getName() );
Upvotes: 0
Reputation: 51445
Your JButton
definition code should be:
button.setText("Binary");
Your ActionListener
code should be:
JButton button = (JButton) event.getSource();
String text = button.getText();
You can also use the JButton
ActionCommand String
to pass along additional; information.
Upvotes: 2