How can I draw a blue rectangle when the mouse is pressed?
Abby:
Here is my code. I want to draw a blue rectangle when the mouse is pressed. The rectangle will be centered around the mouse pointer. I'm new to events so any help would be greatly appreciated.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MouseDemo extends JPanel implements MouseListener {
int x, y; // location of mouse
int sx=25, sy=25; // size of shape
JFrame frame;
void buildIt() {
frame = new JFrame("MouseDemo");
frame.add( this );
this.x = 150;
this.y = 150;
this.addMouseListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocation(200, 200);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor( Color.blue );
g.fillRect(x - sx/2, y - sy/2, sx, sy);
}
// the method from MouseListener we're interested in this time
@Override
public void mousePressed( MouseEvent e) {
e.getX();
e.getY();
}
// the other four methods from MouseListener
// we don't use them, but they have to be present
@Override public void mouseReleased( MouseEvent e) { }
@Override public void mouseClicked( MouseEvent e) { }
@Override public void mouseEntered( MouseEvent e) { }
@Override public void mouseExited( MouseEvent e) { }
public static void main(String[] args) {
new MouseDemo().buildIt();
}
}
Tadija Bagarić:
Edit your method to this:
// the method from MouseListener we're interested in this time
@Override
public void mousePressed( MouseEvent e) {
this.x = e.getX();
this.y = e.getY();
this.repaint();
}
Your code draws with a square Jpanel
at the default point (150, 150) . With editing. You change the default (150, 150) to your mouse coordinates, then tell JPanel
it that it should redraw itself, which calls the method that paintComponent
will draw the square at the mouse position .