我以这个示例为例,该程序在面板上显示鼠标的协调性,并且可以正常工作,而我在每个“ paintComponent”示例中始终收到的问题是,显示永远不会干净,刷新不会发生,这是代码:
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class mousedrag extends JFrame {
public mousedrag() {
drag canvas = new drag("JAVA");
add(canvas);
}
public static void main(String[] args) {
mousedrag f = new mousedrag();
f.setTitle("events");
f.setSize(300, 200);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
static class drag extends JPanel {
String name = "welcome to java";
int x = 20, y = 20;
public drag(String s) {
this.name = s;
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
x = e.getX();
y = e.getY();
repaint();
}
@Override
public void mouseDragged(MouseEvent e) {
}
});
}
@Override
protected void paintComponent(Graphics g) {
g.drawString(String.format("%03d %03d", x, y), x, y);
}
}
}
这是我的问题:
您声明:
显示屏永远不干净刷新没有发生
原因是您没有在paintComponent方法中调用super方法,因此该组件永远无法完成其图像清理工作。因此,要解决此问题,请通过以下方法调用super的方法:
@Override
protected void paintComponent(Graphics g){
g.drawString(String.format("%d %d", x,y), x, y);
}
到
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g); // **********
g.drawString(String.format("%d %d", x,y), x, y);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句