簡體   English   中英

Java AWT如何延遲繪制對象

[英]Java AWT How to draw objects with delay

我想每2秒繪制一個新的隨機形狀。

我已經有一個窗口,可以立即顯示一些形狀。 我試圖弄亂Timer,使新的東西在幾秒鍾后出現在窗口中,但是它不起作用,或者整個程序死機了。 使用Timer是個好主意嗎? 我應該如何實施它以使其起作用?

import javax.swing.*;
import java.awt.*;
import java.util.Random;

class Window extends JFrame {

    Random rand = new Random();
    int x = rand.nextInt(1024);
    int y = rand.nextInt(768);
    int shape = rand.nextInt(2);

    Window(){
        setSize(1024,768);
        setVisible(true);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        super.paint(g);
        g.setColor(new Color(0, 52, 255));
        switch(shape) {
            case 0:
                g.fillOval(x, y, 50, 50);
                break;
            case 1:
                g.fillRect(x,y,100,100);
                break;
        }
        repaint();
    }
}

public class Main {
    public static void main(String[] args) {
        Window window = new Window();
    }
}

我也想畫一些隨機的形狀。 為此可以在塗料中使用開關嗎? 我將創建一個隨機變量,如果為1,則將繪制矩形,如果為2,則將繪制橢圓等。

首先,不要繼承JFrame; 子類化JPanel,然后將該面板放在JFrame中。 其次,不要覆蓋paint()-而是覆蓋paintComponent()。 第三,創建一個Swing Timer,並在其actionPerformed()方法中進行所需的更改,然后調用yourPanel.repaint()

首先,不要更改JFrame的繪制方式(換句話說,不要覆蓋JFrame paintComponent() )。 創建一個擴展的JPanel類,並繪制JPanel 其次,不要重寫paint()方法。 覆蓋paintComponent() 第三,始終使用SwingUtilities.invokeLater()運行Swing應用程序,因為它們應在自己的名為EDT(事件調度線程)的線程中運行。 最后,您正在尋找javax.swing.Timer

看一下這個例子。 每1500毫秒隨機繪制一次X,Y的橢圓形。

預習:

預習

源代碼:

import java.awt.BorderLayout;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class DrawShapes extends JFrame {
    private ShapePanel shape;

    public DrawShapes() {
        super("Random shapes");
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(shape = new ShapePanel(), BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);
        setLocationRelativeTo(null);

        initTimer();
    }

    private void initTimer() {
        Timer t = new Timer(1500, e -> {
            shape.randomizeXY();
            shape.repaint();
        });
        t.start();
    }

    public static class ShapePanel extends JPanel {
        private int x, y;

        public ShapePanel() {
            randomizeXY();
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.fillOval(x, y, 10, 10);
        }

        public void randomizeXY() {
            x = (int) (Math.random() * 500);
            y = (int) (Math.random() * 500);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new DrawShapes().setVisible(true));
    }
}

暫無
暫無

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

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