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

public class Test1 {
int x = 70;
int y = 70;

public static void main (String[] args) {
    Test1 gui = new Test1 ();
    gui.go();
}
public void go() {
    JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    MyDrawPanel drawPanel = new MyDrawPanel();
    frame.getContentPane().add(drawPanel);
    frame.setSize(300,300);
    frame.setVisible(true);

    for (int i = 0; i < 130; i++) {
        x++; y++;
        drawPanel.repaint();
        try { Thread.sleep(50);
        } catch(Exception ex) { } }
}// close go() method

class MyDrawPanel extends JPanel {
    public void paintComponent(Graphics g) {
        g.setColor(Color.green);
        g.fillOval(x,y,40,40);
    }
} // close inner class
} // close outer class


page1 page2

根据第2页,应该将圆圈涂抹在框架中……但是实际上,当我运行它时,它只是移动而没有涂抹。怎么会这样
顺便说一句,如果这些代码不能使人涂片,我该如何使人涂片?

干杯

最佳答案

如图here所示,“如果不遵守opaque property,您很可能会看到视觉伪像。”的确,在带有Java 6的Mac OS X上运行示例会产生一系列看起来“模糊”的圆圈。

java - 为什么这个圈子没有被涂抹-LMLPHP


  我该如何涂抹?



不要依靠painting artifacts获得期望的结果;而是渲染一个List<Shape>,如下所示。
使用javax.swing.Timer调整动画速度。
仅在event dispatch thread上构造和操作Swing GUI对象。
覆盖getPreferredSize()以建立图形面板的初始几何。


码:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Test2 {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Test2()::display);
    }

    public void display() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final MyDrawPanel drawPanel = new MyDrawPanel();
        frame.add(drawPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    class MyDrawPanel extends JPanel {

        private int x = 30;
        private int y = 30;
        private final List<Shape> list = new ArrayList<>();

        public MyDrawPanel() {
            new Timer(50, (new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    x++;
                    y++;
                    list.add(new Ellipse2D.Double(x, y, 40, 40));
                    repaint();
                }
            })).start();
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            g.setColor(Color.green);
            for (Shape s : list) {
                g2d.fill(s);
            }
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(300, 300);
        }
    }
}


†强调我的。

09-15 20:57