有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在点击鼠标后绘制一个椭圆形

我想在面板中单击鼠标时画一个椭圆形。我点击按钮后可以画画。但是出现了一个问题:按钮的副本被绘制在面板的左上角

这是我的代码:

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

共 (2) 个答案

  1. # 1 楼答案

    I want to draw append. previos oval doesn't disappear

    参见Custom Painting Approaches了解两种常见的增量绘制方法:

    1. 保留要绘制的所有对象的列表,然后在组件的paintComponent()方法中遍历该列表
    2. 使用BuffereImage并在BuffereImage上绘制对象,然后在paintComponent()方法中绘制BuffereImage
  2. # 2 楼答案

    你把油漆链弄断了

    在进行任何自定义绘制之前添加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