【问题标题】:drawing an oval after clicking the mouse点击鼠标后画一个椭圆
【发布时间】:2014-03-12 03:06:18
【问题描述】:

当我在面板中单击鼠标时,我想画一个椭圆。单击按钮后允许绘图。但是出现了一个问题:在面板的左上角绘制了一个按钮的副本。

这是我的代码:

 public class PaintPanel extends JPanel implements MouseListener, MouseMotionListener{

        private boolean draw = false;
        private JButton button;
        private Point myPoint;
        public PaintPanel(){
            this.setSize(800,600);
            button = new JButton("Allow draw");
            button.setSize(30,30);
            this.add(button);
            this.addMouseListener(this);
            this.addMouseMotionListener(this);
            button.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent arg0) {
                    draw = true;

                }
            });
        }
        @Override
        public void paintComponent(Graphics g){
            g.setFont(new Font("Arial",Font.BOLD,24));
            g.setColor(Color.BLUE);
            if(draw){
                g.drawOval(myPoint.x-10, myPoint.y-10, 20, 20);
            }
        }
        @Override
        public void mousePressed(MouseEvent e) {
            if(draw){
                myPoint = e.getPoint();
                repaint();
            }
        }
        public static void main(String[] agrs){
            JFrame frame = new JFrame("Painting on panel");
            frame.add(new PaintPanel());
            frame.setVisible(true);
            frame.setSize(800,600);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
        }
    }

【问题讨论】:

  • Swing 应用程序应该从 EDT 运行。有关详细信息,请参阅Initial Threads

标签: java swing graphics paintcomponent


【解决方案1】:

你打破了油漆链。

在进行任何自定义绘画之前添加super.paintComponent(g)

public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.setFont(new Font("Arial",Font.BOLD,24));
    g.setColor(Color.BLUE);
    if(draw){
        g.drawOval(myPoint.x-10, myPoint.y-10, 20, 20);
    }
}

Graphics 是共享资源。它提供给在给定的绘制周期内绘制的所有内容,这意味着除非您先清除它,否则它将包含在您之前已绘制的其他内容。

paintComponent 的工作之一是为绘制准备Graphics 上下文,但要清除它(用组件背景颜色填充它)

请仔细查看Performing Custom PaintingPainting in AWT and Swing 了解更多详情

【讨论】:

  • 我要画追加。 previos 椭圆形不会消失
  • 然后将它们添加到某种List 并在调用paintComponent 时重新绘制它们。在 Swing 中绘制是一个破坏性的过程,这就是 API 的工作方式,您需要在其中工作。
  • “我要画追加。previos 椭圆不会消失”。 @hjepsjga_94 参见 this example 关于 MadProgrammer 关于 List 的观点
  • @hjepsjga_94 对于example
【解决方案2】:

我想画追加。 previos 椭圆不会消失

请参阅Custom Painting Approaches 了解进行增量绘制的两种常用方法:

  1. 保留您要绘制的所有对象的列表,然后在组件的 paintComponent() 方法中遍历此列表
  2. 使用 BufferedImage 并在 BufferedImage 上绘制对象,然后在您的 paintComponent() 方法中绘制 BufferedImage。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-21
    相关资源
    最近更新 更多