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