java - 听Java中的类

标签 java

这是我从书中摘录的代码:

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();
    }
}

据我了解,RandGen 类正在“监听”seedButtongenButton 中出现的一些更改,以及何时发生,应用 actionPerformed 并检查事件源。我不明白 seedButtongenButton 会发生什么。

他们需要应用哪种方法来通知监听器某些内容已更改?

最佳答案

通过调用 addActionListener 为监听器注册按钮。

  genButton.addActionListener(this);

在这一行,genButton 正在被注册,以便如果触发该操作,则“this”对象将处理该事件。这是指该类的当前实例。在此类中,您将找到将在按钮操作上执行的 actionPerformed 方法。

关于java - 听Java中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6374071/

相关文章:

java - 如何解决 klov -Extent 报告中的 FileSizeLimitExceededException

java - 无法使用 Firebase 云消息传递发送通知

javascript - 在客户端JS中加密请求参数,在Java中解密请求参数(Spring Controller )

java - eclipse Java : Define final variable based on build configuration

java - JTable 使用行号?

java - 为什么我无法使用 'outer' catch 捕获嵌套 catch 子句中抛出的异常?

java - 将 Httpsurlconnection 与 REST "POST"函数一起使用时,找不到文件异常

java - Android Studio 单元测试支持与 robolectric

java - 无法在我的 JPanel 中绘制图像

java - 使用 Kryo 序列化任意 Java 对象(获取 IllegalAccessError)