擦除不得发生

时间:2013-12-01 20:31:48

标签: java swing graphics awt

我在这里问了一个类似的问题: Leaving a trace while painting on a transparent JPanel

有一个人确实试图帮助我,但我认为我无法说清楚,所以他误解了我想要的东西。

我想知道如何停止重绘()以清除我的面板。如果删除setOpaque(false);声明,它似乎停止了擦除 - 但是,我没有得到背景颜色。

1 个答案:

答案 0 :(得分:1)

Swing中的绘画是一个破坏性的过程。组件用于绘制自身的Graphics上下文是一个共享资源,即在组件之前和之后绘制的组件将使用相同的图形上下文。

这意味着,如果你不清楚它,你会看到在你之前画的是什么......

在开始绘画之前,您需要清除Graphics上下文...

为此,预计在调用paintComponent时,您将完全重绘您需要重新绘制的内容。

查看Performing Custom PaintingPainting in AWT and Swing

你需要停止对抗这个过程并开始学习它 - 如果你这样做,你的生活会更简单;)

更新了可能的基本方法示例

基本上,这只是在组件的范围内创建一个随机点,将该点添加到List并请求重新绘制组件。在调用paintComponent准备super.paintComponent上下文进行绘制后,Graphics方法只是遍历此列表绘制点...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class AutoPaint {

    public static void main(String[] args) {
        new AutoPaint();
    }

    public AutoPaint() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private List<Point> points = new ArrayList<>(25);

        public TestPane() {
            Timer timer = new Timer(40, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    points.add(new Point(random(getWidth()), random(getHeight())));
                    repaint();
                }
            });
            timer.start();
        }

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

        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            for (Point p : points) {
                g2d.drawLine(p.x, p.y, p.x, p.y);
            }
            g2d.dispose();
        }

        protected int random(int range) {
            return (int)Math.round(Math.random() * range);
        }

    }

}