我做了这个例子作为练习,这个程序在面板上显示鼠标的协调,它工作正常,我在每个“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);
}
}
}
这是我的问题:
最佳答案
您声明:
the display is never clean the refresh isn't happening
原因是您没有在 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);
}
关于java - PaintComponent显示不清楚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25995054/