Listening to classes in Java
Here is code that I took from a book:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class RandGen extends JFrame implements ActionListener
{
private JButton genButton;
private JButton seedButton;
private JLabel randLabel;
private JTextField seedText;
private int randNumber;
public RandGen() {
super("Random number generator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
randNumber = 215;
randLabel = new JLabel("*** " + randNumber + " ***");
genButton = new JButton("Generate");
genButton.addActionListener(this);
seedButton = new JButton("Set seed");
seedButton.addActionListener(this);
seedText = new JTextField();
seedText.setColumns(10);
seedText.setText("" + randNumber);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(seedText);
getContentPane().add(seedButton);
getContentPane().add(genButton);
getContentPane().add(randLabel);
pack();
setVisible(true);
}
开发者_运维问答 public void nextRand() {
if (randNumber % 2 == 0)
randNumber = randNumber / 2;
else
randNumber = randNumber * 3 + 1;
setRandNumber(randNumber);
}
private void setRandNumber(int randnumber) {
this.randNumber = randNumber;
randLabel.setText("*** " + this.randNumber + " ***");
}
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(genButton))
this.nextRand();
if (e.getSource().equals(seedButton)) {
randNumber = Integer.parseInt(seedText.getText());
setRandNumber(randNumber);
}
}
public static void main(String args[]) {
RandGen frame = new RandGen();
}
}
As I understand it, the RandGen
class is "listening" to some changes that appear in seedButton
and genButton
, and when that happens, apply the actionPerformed
and check the source of the event. I don't understand what happens with seedButton
and genButton
.
Which method do they need to apply in order to inform the listener that something was changed?
The buttons are registered for the listener with a call to addActionListener.
genButton.addActionListener(this);
At this line, the genButton is being registered so that if the action is triggered then"this" object will handle the event. This referes to the current instance of the class. In this class you will find the actionPerformed method that will be executed on the action of the button.
It's part of the implementation of the JButton
class to call the actionPerformed()
method of all registered listeners when the button is pressed - you don't have to implement that part. Note that this will happen on the Swing Event Dispatch Thread.
The secret is that the actionPerformed() call is more like a callback.
This line registered your class with the object that generates the event.
seedButton.addActionListener(this);
It tells the seedButton to call your actionPerformed() method when it detects an event.
精彩评论