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);
}
}
# 1 楼答案
参见Custom Painting Approaches了解两种常见的增量绘制方法:
# 2 楼答案
你把油漆链弄断了
在进行任何自定义绘制之前添加
super.paintComponent(g)
Graphics
是一个共享资源。它被提供给在给定的绘制周期内绘制的所有内容,这意味着,除非您首先清除它,否则它将包含在您之前已经绘制的其他内容paintComponent
的工作之一是为绘画准备Graphics
上下文,但要清除它(用组件背景色填充)更详细地看一下Performing Custom Painting和Painting in AWT and Swing