【发布时间】:2015-01-16 19:27:09
【问题描述】:
我正在尝试制作一个在用户按下按钮时生成随机数的程序。当用户第二次按下按钮时,它应该停止生成它们,然后它应该打印所有加在一起的随机数和平均随机数,但我不知道该怎么做。当我在循环中时,我无法按下按钮。我会感谢任何帮助。我的代码:
package Test;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Average
{
static int sizeX = 200;
static int sizeY = 200;
static int maxNum = 100;
static int minNum = 1;
static boolean running = true;
static JButton b1 = new JButton("Click me");
static void JFrame()
{
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
JFrame f = new JFrame("Test");
f.setSize(sizeX, sizeY);
f.setVisible(true);
f.setLocation((dim.width - sizeX) / 2, (dim.height - sizeY) / 2);
f.setResizable(false);
f.setAutoRequestFocus(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(b1);
}
static void ActionListener()
{
b1.addActionListener(new ActionListener()//ActionListener
{
public void actionPerformed(ActionEvent e)//Execute when button is pressed
{
int numsGenerated = 0;
double ave = 0;
if (running == true)
{
while (true)
{
double r = Math.random() * (maxNum - minNum) + minNum; //(maxNum - minNum) + minNum
numsGenerated++;
ave = ave + r;
System.out.println("Random: " + r);
if (!running)
{
break;
}
}
running = false;
}
else
{
System.out.println("");
System.out.println("All: " + ave);
System.out.println("Average: " + ave / numsGenerated);
running = true;
}
}
}); //ActionListenerEnd
}
public static void main(String[] args)//Main
{
JFrame();
ActionListener();
}
}
【问题讨论】:
-
if (running = false)->if (running == false)。或者更好,if(!running) -
因为你占用了 EDT。我已经为此写了很多次答案并投票赞成。不要在 EDT 中循环!使用不同的线程或
Timer。 The official Oracle lesson on the EDT 正是如此 -Tasks on the event dispatch thread must finish quickly; if they don't, unhandled events back up and the user interface becomes unresponsive.我强烈建议您阅读整个教程,以熟悉 EDT 工作原理的基础知识。
标签: java multithreading swing loops jbutton