当我在面板中单击鼠标时,我想画一个椭圆形。单击按钮后允许绘图。但是会出现问题:按钮的副本在面板的左上角绘制。
这是我的代码:
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);
}
}
答案 0 :(得分:3)
你打破了油漆链。
在进行任何自定义绘画之前添加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 Painting和Painting in AWT and Swing了解详情
答案 1 :(得分:1)
我想绘制追加。普遍的椭圆形不会消失
有关增量绘画的两种常用方法,请参阅Custom Painting Approaches: