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

时间:2017-07-28 04:32:54

标签: java swing

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页,圆圈应涂抹在框架中......但实际上,当我跑步时,它只是移动而没有涂抹。那是为什么? 顺便说一句,如果这些代码无法制作涂抹圆圈,我怎么能做一个涂抹的呢?

欢呼

1 个答案:

答案 0 :(得分:2)

如图所示here,&#34;如果您不尊重opaque property,您可能会 看到视觉瑕疵。&# 34;实际上,在Mac OS X上使用Java 6运行您的示例会产生一系列看起来被涂抹的圆圈。&#34;

image

  

我怎么能弄脏一个?

代码:

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);
        }
    }
}

强调我的。