thrax thrax - 27 days ago 7
Java Question

paintComponent unclear display

I made this example as a practise this program displays the coordination of the mouse on the panel it works fine and the problem that i keep receiving with every "paintComponent" example is that the display is never clean the refresh isn't happening here's the code :

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);
}
}
}


and here's my problem :

screen

enter image description here

Answer

You state:

the display is never clean the refresh isn't happening

The reason is that you don't call the super method in your paintComponent method and so the component never gets to do its image cleaning housekeeping. So to fix that, call the super's method by changing:

@Override   
protected void paintComponent(Graphics g){
    g.drawString(String.format("%d %d", x,y), x, y);
}

to

@Override   
protected void paintComponent(Graphics g){
    super.paintComponent(g); // **********
    g.drawString(String.format("%d %d", x,y), x, y);
}