Java Reference
In-Depth Information
String message;
if (((JButton)ev.getSource()).getText().equals("Click Me!"))
message = "First button was clicked";
else
message = "Second button was clicked";
JOptionPane.showMessageDialog(null,
message, "Aw yeah!",
JOptionPane.PLAIN_MESSAGE);
}
Of course, this is a terrible way to implement the desired functionality. Not only are you mak-
ing an unsafe case (who says the source component will always be a button?), but you're also
hardcoding some text that might later be changed. This does introduce an interesting method
though: getSource() . This method allows you to get the source component for the incom-
ing event. Why not directly use this method as is? You will need to make the two buttons class
fields, however:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
public class ActionListenerExample extends JFrame implements ActionListener {
private final JButton btn1 = new JButton("Click Me!");
private final JButton btn2 = new JButton("No, click me!");
public ActionListenerExample() {
super();
this.setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn1.addActionListener(this);
btn2.addActionListener(this);
getContentPane().add(btn1);
getContentPane().add(btn2);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent ev) {
String message = "";
if (ev.getSource() == btn1)
message = "First button was clicked";
else if (ev.getSource() == btn2)
message = "Second button was clicked";
JOptionPane.showMessageDialog(null,
message, "Aw yeah!",
JOptionPane.PLAIN_MESSAGE);
Search WWH ::




Custom Search