When I run my code, a rectangle shows up only when the mouse is clicked in the top left corner of the JPanel
. When it shows up, it is warped out of shape. If I change fillRect
to fillOval
, it does not show up at all. My goal is to have a circle filled at the mouse's location when it is clicked. My code is:
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class PaintProgram {
JFrame frame;
JPanel panel;
Point p;
int x;
int y;
int diameter;
public PaintProgram(){
frame = new JFrame();
frame.setSize(500,500);
panel = new JPanel();
diameter = 100;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.addMouseListener(new MListener());
panel.add(new DrawCircle());
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args){
PaintProgram p = new PaintProgram();
}
class UBListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent a){
}
}
class MListener implements MouseListener{
public void mousePressed(MouseEvent e){
p = panel.getMousePosition();
x = (int) p.getX();
y = (int) p.getY();
panel.add(new DrawCircle());
frame.repaint();
frame.revalidate();
System.out.println(x + "," + y);
}
public void mouseReleased(MouseEvent e){
}
public void mouseClicked(MouseEvent e){
}
public void mouseExited(MouseEvent e){
}
public void mouseEntered(MouseEvent e){
}
}
class DrawCircle extends JPanel{
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.orange);
g.fillRect(x,y,diameter,diameter);
System.out.println(x + "," + y);
}
}
}