這是我在這裏的第一篇文章,所以希望它沒有問題。嘗試使用線程時程序鎖定
我在netbeans。我用鈕釦等做了一個窗口。
我有一個叫SimpleThread類,看起來像這樣:
public class SimpleThread extends Thread {
public SimpleThread()
{
}
@Override
public void run()
{
}
而且我有各種不同的子類的線程擴展simplethread(TimerThread,MouseGrabThread)。
public class MouseGrabThread extends SimpleThread{
private Point pt;
private JTextField x, y;
public MouseGrabThread(JTextField x, JTextField y)
{
super();
this.x = x;
this.y = y;
}
@Override
public void run()
{
while(this.isAlive())
{
int[] xyVal = new int[2];
xyVal = getCoords();
x.setText("" + xyVal[0]);
y.setText("" + xyVal[1]);
}
}
public int[] getCoords()
{
Point pt = MouseInfo.getPointerInfo().getLocation();
int[] retArr = new int[2];
retArr[0] = (int)pt.getX();
retArr[1] = (int)pt.getY();
return retArr;
}
public class TimerThread extends SimpleThread {
private JTextArea label;
private int time;
public TimerThread(JTextArea label, int time)
{
super();
this.label = label;
this.time = time;
}
@Override
public void run()
{
int counter = time;
while(counter != -1)
{
label.setText("You have: " + counter + " seconds until the timer ends!\n");
counter--;
try {
this.sleep(1000);
} catch (InterruptedException ex) {
System.out.println("Thread Interrupted");
}
}
stop();
}
在我的UI窗口類,我有這樣的:
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
SimpleThread timer = new TimerThread(jTextArea1, 10); //This counts down from 10 seconds and updates a status text box each second
SimpleThread mouseGrab = new MouseGrabThread(jTextField1, jTextField2); //This grabs mouse coords and updates two boxes in the UI.
timer.start();
if(timer.isAlive())
{
mouseGrab.start();
}
while(timer.isAlive())//######
{
if(!mouseGrab.isAlive())
{
mouseGrab.start();
}
}
}
程序凍結10秒鐘時,我按下按鈕。
我猜我已標記的行(// #####)是導致UI在定時器的持續時間內凍結的行,導致它在主線程中運行。我不知道如何解決這個問題。
請原諒我對編程知識的缺乏,現在我正在進入自己的線程,而我正在大學學習關於數據結構的非常簡單的課程。如果可能的話,你能儘可能地「減弱」答案嗎?另外,我知道我做這件事很糟糕,但我稱之爲stop()函數,即使它不好(不要爲此拍攝我,我不知道該怎麼辦!)如果有人能夠很好地回答這個問題,那太棒了!
如果我想繼續GUI在倒計時時可用嗎?現在,整個程序凍結,並且它不更新timerThread輸出的文本框或鼠標座標的X和Y textAreas。 – Pilapodapostache 2013-04-05 18:31:54
您的'TimerThread'可以引用'mouseGrab',因此'timer'本身可以決定何時打破它。請參閱我的(傳入)** Edit2 **的插圖。 – blint 2013-04-05 18:55:01
就是這樣,謝謝! :) – Pilapodapostache 2013-04-06 19:31:26