I am solving a Java problem about AWT. When you click the right button of Mouse. It will create an oval. If you click the left button, it will remove the oval you clicked. I have implemented the creation of ovals, but I cannot find any built-in functions about removing shapes in AWT. My code is below:
package chapter16;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Points extends JFrame{
public Points(){
add(new NewPanel4());
}
public static void main(String[] args){
Points frame = new Points();
frame.setSize(200, 200);
frame.setTitle("Add and Remove Points");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class NewPanel4 extends JPanel{
private boolean Add = false;//add points
private int x,y;//the x,y coordinate
public NewPanel4(){
addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if(e.getButton()== MouseEvent.BUTTON3){
Add = true;
x = e.getX();
y = e.getY();
repaint();
}
else if(e.getButton() == MouseEvent.BUTTON1){
Add = false;
}
}
});
}
protected void paintComponent(Graphics g){
//super.paintComponent(g);
//Add oval if Add is true
if (Add == true){
g.fillOval(x, y, 10, 10);
}
//remove oval if Add is false
else if(Add == false){
//code to remove ovals
}
}
}
}