我怎样才能让这个 JButton 工作

How can I make this JButton work

我正在编写一个代码,当您按下按钮并输出该数字时,它将生成一个随机数。我已经编写了这段代码并且它可以编译但是当我按下按钮时没有任何效果。有人可以帮忙吗?这是我的一些代码。

public class slotmachine extends JApplet {

    JButton b1 = new JButton("START");
    JPanel p;
    int Int1;

    public slotmachine() {
        init();

    }

    public void init() {

        this.setLayout(null);
        this.setSize(1000, 1000);

        JButton b1 = new JButton("START");
        b1.setBounds(100, 100, 100, 100);

        getContentPane().add(b1);
        repaint();

    }

    public void run() {
        b1.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                Random random1 = new Random();
                int Int1 = random1.nextInt(11);

            }

        });
    }

    public void paint(Graphics g) {

        g.drawString("Your number is" + Int1, 30, 30);

    }
}
  1. 避免使用 null 布局,像素完美布局是现代 ui 设计中的一种错觉。影响组件个体大小的因素太多,none 是您可以控制的。 Swing 旨在与核心的布局管理器一起工作,丢弃这些将导致无穷无尽的问题和问题,您将花费越来越多的时间来尝试纠正
  2. 您在按钮的 ActionListener 中创建了 Int1 的局部变量。这与class的Int1没有关系。
  3. 你永远不会告诉 UI 更新
  4. 您因未能调用 super.paint 而破坏了绘画链(准备好迎接一些非常奇怪和奇妙的图形故障)
  5. 您在 b1 上犯了与 Int1 相同的错误。您创建了一个实例级字段,但是用 init 中的局部变量对其进行了隐藏,这意味着当调用 start 时,b1null,这将导致 NullPointerxception

相反,将 JLabel 添加到您的小程序,使用它的 setText 方法来显示随机值

b1.addActionListener(new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        Random random1 = new Random();
        int Int1 = random1.nextInt(11);
        lable.setText(Integer.toString(Int1));
    }

});

此外,如果可能的话,我会避免使用 JApplet,它们有自己的一系列问题,这会使学习 Swing API 时的生活变得更加困难。相反,请尝试对您的主容器使用 JPanel,然后将其添加到 JFrame.

的实例中

另外,看看:

了解更多详情