[英]Javax.swing.timer with GUI (Eclipse)
我想制作一個代碼,從面板的左側到面板的右側進行正方形移動...我意識到你可以簡單地使圖像出現在代碼塊中然后在下一個塊中代碼使圖像與完全相同的正方形重疊,只是與背景顏色相同...為此,我需要一個像代碼一樣的計時器,使圖像出現,然后1秒后它重疊然后新圖像就會出現在它旁邊
意識到sleep.thread不適合gui我正在使用Javax.Swing.Timer
我只想讓它現在旁邊出現一個方框
但是我沒有使用它的經驗,需要一些幫助才能使用我的代碼-Andrew
{
g.setColor(Color.GREEN);
g.fillRect(50, 100, 100, 100); //first box on a red background
//Timer goes here
g.setColor(Color.RED);
g.fillRect(50, 100, 100, 100);//overlapps the first box
g.setColor(Color.GREEN);
g.fillRect(50, 110, 100, 100);//sets a new box right beside it
}
}
實際上創建javax.swing.Timer
非常簡單。 您不必自己擔心線程,因為調度在后台線程中自動發生,但您實現的偵聽器的代碼在GUI線程中執行。 因此,您可以使用偵聽器正文中所需的任何swing組件。
int interval = 1000; // repeating every 1000 ms
new Timer(interval, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// do whatever painting that you want
}
}).start();
你初始化它:
Timer <timernamegoeshere> = new Timer(<delayinmilis>,<actionlistener>);
因此,您在計時器中輸入的每一毫秒都會執行一個動作。
這意味着你可以簡單地將你的更新代碼放入actionPerformed
並使變量增加你移動平方的像素數和布爾值,從true
切換到false
, true
是它繪制它,並且false
它將它設置為背景的顏色。
我不確定這是否是最佳方式,但您可以輕松地重新定義一個正方形以獲得位置。 反過來,您可以讓計時器更新方形實例的位置,然后調用repaint()。 這意味着paint方法只是在新位置繪制背景和相同的方塊,而不是每次都創建一個新的方塊。
你的繪畫方法可能會有類似的東西:
g.drawRect(referenceToSquare.getLocation().getX(), referenceToSquare.getLocation().getY(), 100, 100)
您使用以下命令初始化計時器:
Timer timer = new Timer(delayInMillis);
timer.add(new ActionListener());
然后在同一個班級有......
actionPerformed(ActionEvent e) {
if(e.getSource() == timer) {
referenceToSquare.getLocation().getX()++;
}
frame.repaint();
}
http://docs.oracle.com/javase/6/docs/api/java/awt/event/ActionListener.html
我建議你使用ExecutorService
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html
例如,你可以做類似的事情
private static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
scheduledThreadPool.scheduleAtFixedRate(new DrawingTask(), 1000, 1000 TimeUnit.MILLISECONDS);
您的繪圖任務可能類似於以下內容:
public class DrawingTask extends TimerTask {
@Override
public void run() {
// previous co ordinates. This should be static
// sleep for a second
// re draw the old one
// draw the new one
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.