[英]drawing an oval after clicking the mouse
I want to draw an oval when I click the mouse in my panel. 当我在面板中单击鼠标时,我想绘制一个椭圆形。 And drawing is allowed after I click the button.
单击按钮后,即可进行绘图。 But a problem is occurs: a copy of the button is drawn in the top left of the panel.
但是出现了一个问题:在面板的左上方绘制了按钮的副本。
This is my code: 这是我的代码:
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);
}
}
You broke the paint chain. 您打破了油漆链。
Add super.paintComponent(g)
before you do any custom painting 在执行任何自定义绘画之前,添加
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
is a shared resource. Graphics
是共享资源。 It is provided to everything that is painted within a given paint cycle, meaning, that unless you clear it first, it will contain other things that have already been painted before you. 它在给定的绘画周期内提供给所有要绘画的东西,这意味着,除非您先清除它,否则它将包含您之前已经绘画过的其他东西。
One of the jobs of paintComponent
is to prepare the Graphics
context for painting, but clearing it (filling it with the components background color) paintComponent
的工作之一是准备要绘画的Graphics
上下文,但清除它(用组件背景色填充它)
Take a closer look at Performing Custom Painting and Painting in AWT and Swing for more details 详细了解如何在AWT和Swing中执行自定义绘画和绘画
I want to draw append.
我想画追加。 previos oval doesn't disappear
previos椭圆形不会消失
See Custom Painting Approaches for the two common ways to do incremental painting: 有关进行增量绘画的两种常用方法,请参见“ 自定义绘画方法 ”:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.