add lab11
This commit is contained in:
38
lab/lab11/Question2/MyPanel.java
Normal file
38
lab/lab11/Question2/MyPanel.java
Normal file
@@ -0,0 +1,38 @@
|
||||
import java.awt.Color;
|
||||
import java.awt.Graphics;
|
||||
import java.awt.event.MouseAdapter;
|
||||
import java.awt.event.MouseEvent;
|
||||
|
||||
import javax.swing.JPanel;
|
||||
|
||||
public class MyPanel extends JPanel {
|
||||
private int x = -1;
|
||||
private int y = -1;
|
||||
|
||||
public MyPanel() {
|
||||
this.addMouseListener(new MouseAdapter() {
|
||||
// Anonymous class.
|
||||
public void mouseClicked(MouseEvent e) {
|
||||
// Check whether the left mouse button is clicked
|
||||
if (e.getButton() == MouseEvent.BUTTON1) {
|
||||
x = e.getX();
|
||||
y = e.getY();
|
||||
// get the coordinate
|
||||
System.out.println("(" + e.getX() + "," + e.getY() + ")");
|
||||
// force Swing to repaint the red point
|
||||
repaint();
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void paintComponent(Graphics g) {
|
||||
// must clean the panel before drawing on it.
|
||||
super.paintComponent(g);
|
||||
g.setColor(Color.RED);
|
||||
// draw the red square
|
||||
g.drawRect(x, y, 1, 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user