Reputation: 316
Here is my code. I want to draw a blue rectangle when the mouse is pressed. The rectangle would be centred around the mouse pointer. I am a noob to events, so I would appreciate help and explanations.
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();
}
}
Upvotes: 2
Views: 187
Reputation: 2701
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 the Jpanel
with the square at the default point (150, 150). With the edit. You will change the default (150, 150) to what ever coordinates your mouse is and then tell the JPanel
it should repaint itself what will call the paintComponent
method that will draw the square at your mouse position.
Upvotes: 1