这是我的代码。我想在按下鼠标时绘制一个蓝色矩形。矩形将以鼠标指针为中心。我是活动的小伙子,所以我很感激帮助和解释。
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();
}
}
答案 0 :(得分:1)
编辑您的方法:
// 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();
}
您的代码使用默认点(150,150)处的方块绘制Jpanel
。随着编辑。您将默认值(150,150)更改为鼠标的坐标,然后告诉JPanel
它应该重新绘制自己将调用paintComponent
方法的方法,该方法将在鼠标位置绘制方形。