Reputation: 39
I got a problem when adding ActionListener
to two JButtons
in the following Code.
I want to print each 1 and 2 when I click on these two Buttons (b1,b2)
But I can only print 1 or 2.
Could you please give me a solution to fix this problem?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class CCCc extends JFrame implements ActionListener{
JButton b1,b2;
JTextField f1;
CCCc(){
setSize(500,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
f1=new JTextField();
f1.setHorizontalAlignment(JTextField.RIGHT);
add("North",f1);
JPanel p1=new JPanel(new GridLayout(1,2));
add(p1);
b1=new JButton("1");
b1.addActionListener(this);
b2=new JButton("2");
b2.addActionListener(this);
p1.add(b1);
p1.add(b2);
setVisible(true);
}
public void actionPerformed(ActionEvent evt){
String s=f1.getText();
f1.setText(s+"1");
}
}
Upvotes: 2
Views: 226
Reputation: 639
I think the case is You want to know on which JButton
, the ActionEvent
is triggered, And if it is b1
, You have to join a "1"
to the textfield else "2"
.
If the case is the above, do the following:
public void actionPerformed(ActionEvent evt){
JButton temp=evt.getSource();
String s=f1.getText()+temp.getText();
f1.setText(s);
}
If the case is not the above, then I say Sorry
Upvotes: 1
Reputation: 147154
It's a bad idea to subclass classes, such as JFrame
and Thread
, unnecessarily. It's also a bad idea to implement interfaces inappropriately. (Thirdly, it's a bad idea to attempt to look at the source
of an event and the command
is nasty as well)
I suggest switching to an anonymous inner class for the listeners. You will notice you have common code for both buttons, so that can be factored into a method requiring only a single inner class. The variable holding "1" or "2" would usually be referenced via a final
local field in the method enclosing the anonymous inner class. However, you could use a non-anonymous class with a field accessed in the usual way.
Upvotes: 5
Reputation: 285405
The ActionEvent parameter has much useful information that you can use including a reference to the button pressed -- via getSource()
or to the button's text via `getActionCommand(). So you can simply get the actionCommand from the ActionEvent and use it:
public void actionPerformed(ActionEvent evt){
String s=f1.getText();
f1.setText(s+ evt.getActionCommand());
}
Upvotes: 2