我想繪製一個矩形,其位置每秒更新一次,因爲我有一個擴展JPanel的類,並且在其中我重寫了paint(或paintComponent)function_我已經試過_但在器件上,這個函數只被調用一次,如下面代碼所示,當我試圖用無限循環調用它時,它不會被調用,任何想法我可以做什麼?重繪在java中不工作
public class Board extends JPanel implements KeyListener{
public void setUpBoard(){
JFrame frame = new JFrame();
Board board = new Board();
frame.setVisible(true);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(600, 600);
frame.setLocation(350, 80);
frame.add(board);
}
public void paint(Graphics g){
g.setColor(Color.RED);
g.fillRect(food.getX(),200,20,20);
}
}
上述代碼圖形的一部分,下面是主要的功能,它被放置在另一個類:
public static void main(String[] args) throws InterruptedException {
Board board = new Board();
FoodGenerator food = new FoodGenerator();
board.setUpBoard();
while(true){
board.repaint();
food.adder();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
在上述food.adder代碼,其中矩形的位置是更新,我已檢查並沒有任何問題。
你是否正在修改重新調用之間的任何內容?我會檢查你的主食中的食物是否與你的烤漆方法中的食物相同。 – bakalolo
不要重寫'paint',使用'paintComponent';不要打破繪畫鏈,確保你正在調用'super.paintComponent';看看[在AWT和Swing中繪畫](http://www.oracle.com/technetwork/java/painting-140037.html)和[執行自定義繪畫](http://docs.oracle.com/javase/tutorial/uiswing/painting /)以更好地理解繪畫的工作原理。此外,請查看[使用JFC/Swing創建GUI](http://docs.oracle.com/javase/tutorial/uiswing/),以更好地瞭解Swing GUI的工作方式 – MadProgrammer
您可能還想看看[併發中的Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/),爲了簡單起見,[如何使用Swing定時器](http://docs.oracle.com/ javase/tutorial/uiswing/misc/timer.html) – MadProgrammer