簡體   English   中英

如何重新運行paint方法,使JPanel具有動畫效果?

[英]How do I re run the paint method so the JPanel is animated?

我想我需要在注釋所在的地方放置一些代碼(或者可以使用非靜態方法,但我不確定)。 main方法創建窗口,然后啟動圖形方法。 我希望藍色方塊閃爍。

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class paintTest extends JPanel{
private static JFrame theWindow = new JFrame("Window");
static boolean blueSqr = false;

public void paint(Graphics g) {
    g.setColor(Color.RED);
    g.fillRect(10, 10, 10, 10);

    if(blueSqr){
        g.setColor(Color.BLUE);
        g.fillRect(10, 10, 10, 10);
    }
}

public static void main(String[] args){
    createWindow();
    theWindow.getContentPane().add(new paintTest());
    while(true){
        blueSqr = false;

        System.out.println("off");

        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}

        blueSqr = true;
        // Needs something here
        System.out.println("on");

        try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}
        }
}

public static void createWindow(){
    theWindow.setSize(500, 500);
    theWindow.setLocationRelativeTo(null);
    theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    theWindow.setVisible(true);
}
}

任何幫助都是非常好的。

使用Swing Timer調用repaint() 另外,在JPanel重寫paintComponent() ,而不要重寫paint()

像這樣:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class PaintTest extends JPanel{

    boolean blueSqr = false;

    PaintTest() {
        setPreferredSize(new Dimension(100,25));
        ActionListener al = new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                blueSqr = !blueSqr;
                repaint();
            }
        };
        Timer timer = new Timer(1000,al);
        timer.start();
    }

    public void paintComponent(Graphics g) {
        Color c = (blueSqr ? Color.BLUE : Color.RED);
        g.setColor(c);
        g.fillRect(10, 10, 10, 10);
    }

    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame theWindow = new JFrame("Window");
                theWindow.getContentPane().add(new PaintTest());
                createWindow(theWindow);
            }
        });
    }

    public static void createWindow(JFrame theWindow){
        theWindow.pack();
        theWindow.setLocationByPlatform(true);
        theWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        theWindow.setVisible(true);
    }
}

還有其他我無法打擾的改進(代碼勝於雄辯)。 如果您有任何疑問(請先檢查文檔,然后再問)。

你的問題是

1)通過在Swing相關代碼中調用Thread.sleep(int) ,永遠不要這樣做,因為延遲了Swing(有很多關於為什么不以編程語言使用sleep的話題……)使用Swing計時器

2)您的JPanel不返回任何XxxSize

3)對於Swing,請使用paintComponent() ,只有在您有非常重要的理由時,才應使用paint()方法更多有關2D圖形教程中的重新繪制和對圖形進行動畫處理

4)Swing GUI應該內置在事件調度線程中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM