gpt4 book ai didi

Java - JToggleButton - 虽然无限循环 - 无法单击按钮两次

转载 作者:行者123 更新时间:2023-12-02 02:49:28 25 4
gpt4 key购买 nike

我需要请帮忙。我有一个 Java 代码,其中有一个小 GUI。我不能点击按钮两次。我只能激活 while 循环,但无法停用它。

这是我的代码:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Test2 {

public static void main(String[] args) {

JFrame Frame = new JFrame("");
Frame.setBounds(100, 100, 450, 300);
Frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Frame.setVisible(true);

JPanel Panel = new JPanel();
Frame.add(Panel);

JToggleButton toggle = new JToggleButton("");
Panel.add(toggle);
toggle.setPreferredSize(new Dimension(50,50));
toggle.addActionListener(new ActionListener() {


public void actionPerformed(ActionEvent arg0) {
int zufallszahl;
if(toggle.isSelected()) {
while(toggle.isSelected()) {

zufallszahl = (int)(Math.random() * 10 +1);
System.out.println(zufallszahl);
}

}
}
});
}

}

最佳答案

您的问题在这里:

            while(toggle.isSelected())      {

zufallszahl = (int)(Math.random() * 10 +1);
System.out.println(zufallszahl);
}

据我了解,您希望在选择按钮时生成随机数。要实现它,您需要 SwingWorkerTimer .

这是一个带有计时器的示例:

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JToggleButton;
import javax.swing.Timer;

public class Test2 {

public static void main(String[] args) {

JFrame frame = new JFrame("");
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);

JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER));
frame.add(panel);

final Timer timer = new Timer(300, new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
int zufallszahl = (int)(Math.random() * 10 +1);
System.out.println(zufallszahl);
}
});
final JToggleButton toggle = new JToggleButton("Go");
panel.add(toggle);
toggle.addActionListener(new ActionListener() {


@Override
public void actionPerformed(ActionEvent arg0) {
if (toggle.isSelected()) {
timer.restart();
} else {
timer.stop();
}
}
});
}

}

关于Java - JToggleButton - 虽然无限循环 - 无法单击按钮两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44068182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com