[英]Why is Java Graphics2D 'drawString' stopping repaint()?
我目前正在使用Java Swing創建游戲。 我需要一個計分器,所以我使用Graphics2D方法drawString
進行繪制。
我刪除了所有不會改變代碼中問題的內容,最終我發現問題是drawString
方法。
這是我的完整代碼:(Problem / src / defaultpackage / Problem.java)
// All the imports are here
public class Problem extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
Problem problem = new Problem();
frame.add(problem);
frame.setTitle("Problem");
frame.setSize(350, 720);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.requestFocus();
frame.setVisible(true);
}
public Problem() {
Timer timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(),0,20);
// Changing '20' doesn't work
}
private void draw(Graphics g) {
System.out.println("draw");
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("S", 100, 100);
// If I remove this and replace it by:
//g2d.fillRect(0, 0, 100, 100);
// it works just fine
}
@Override
public void paintComponent(Graphics g) {
System.out.println("paintcomponent");
super.paintComponent(g);
draw(g);
}
private class ScheduleTask extends TimerTask {
@Override
public void run() {
System.out.println("repaint");
repaint();
}
}
}
我希望輸出為:
repaint
paintcomponent
draw
repaint
paintcomponent
draw
等等。 但是,相反,在程序運行的前兩秒鍾,輸出僅為:
repaint
repaint
repaint
在那兩秒鍾之后,一切都會按預期進行。
為什么會這樣?
由於計時器每秒運行50次,因此會在主線程完成GUI初始化之前觸發多次。
在GUI准備就緒之前調用repaint()
不會導致paintComponent()
被調用。
如果在調用setVisible(true)
之后才啟動計時器,則將獲得期望的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.