java - 有没有办法多次执行 paintComponent() 中的代码?
问题描述
我想根据鼠标的 x 和 y 位置在屏幕上移动图像。每次单击鼠标时,图像都应移动到该位置。
public class testSquare {
public static void main(String[] args) throws Exception {
//...
//object that stores x and y of mouse click
testSquareInfo obj = new testSquareInfo(0, 0);
//...
//panel that draws image, seems to only execute once
JPanel p = new JPanel ()
{
protected void paintComponent(Graphics a){
int x = obj.getXPos();
int y = obj.getYPos();
a.drawImage(img, x, y, 50, 50, null);
}
};
//listens for mouse click and sends x and y to object
p.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int xMouse = e.getX();
int yMouse = e.getY();
obj.changeX(xMouse);
obj.changeY(yMouse);
System.out.println(xMouse+" "+yMouse);
}
});
window.add(p);
window.setVisible(true);
}
}
//Second Class
public class testSquareInfo
{
private int x, y;
public testSquareInfo(int x, int y)
{
this.x = x;
this.y = y;
}
public void changeX(int xNew)
{
x = xNew;
}
public void changeY(int yNew)
{
y = yNew;
}
public int getXPos()
{
return x;
}
public int getYPos()
{
return y;
}
}
运行代码时,图像会在窗口的 0, 0, 坐标处绘制,因为 x 和 y 已初始化为这些值。在屏幕上单击不会移动图像,但会正确更新对象中存储的 x 和 y。在测试期间的某一时刻,图像确实移动到了屏幕上的不同位置。然而,这发生在我没有点击窗口的时候,并且从那以后我就无法复制它。我不确定它何时或如何移动。谢谢,
解决方案
p.repaint();
在您的mousePressed
方法中添加一个。这会导致面板被重绘。
但是,仅这样做只会将另一个 Image 添加到图形组件中。
如果您不想将图像保留在之前的位置,请在方法的开头
添加 a以使面板处于空白状态。super.paintComponent(a);
paintComponent
JPanel p = new JPanel() {
protected void paintComponent(Graphics a){
super.paintComponent(a);
int x = obj.getXPos();
int y = obj.getYPos();
a.drawImage(img, x, y, 50, 50, null);
}
};
//listens for mouse click and sends x and y to object
p.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int xMouse = e.getX();
int yMouse = e.getY();
obj.changeX(xMouse);
obj.changeY(yMouse);
System.out.println(xMouse+" "+yMouse);
p.repaint();
}
});
推荐阅读
- android - Moshi - 将问题 1.8.0 升级到 1.12.0
- android - 将应用程序部署到 Android 设备时强制更改启动器图标
- java - Java Apache Poi Word 在 .docx 文件的现有行中写入新值
- python - 如何使用 ldap3 从本地 AD 获取用户?
- netsuite - 销售订单项目子列表中具有特定字段的项目排序列表 NetSuite
- python - 将列表变成字典添加标题
- plotly - 仅在 x 轴上绘制日期和月份以比较年份的简单方法?
- linux - 卷创建 MAPR
- duplicates - 为什么我的那套对
包含重复项? - ios - Flutter pod安装错误与ios上的firebase消息传递