This is a follow-up to my previous question. I’ve simplified things as much as I could, and it still doesn’t work! Although the good thing I got around using getGraphics().
A detailed explanation on what goes wrong here is massively appreciated. My suspicion is that something’s wrong with the the way I used addMouseListener() method here.
EDIT completely rewrote the code. Still does not work properly though.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class RunClass{
static MainClass1 inst1 = new MainClass1();
public static void main(String args[]){
JFrame frame1 = new JFrame();
frame1.add(inst1);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setTitle("NewPaintToolbox");
frame1.setSize(200, 200);
frame1.setLocationRelativeTo(null);
frame1.setVisible(true);
}
}
class MainClass1 extends JPanel implements MouseListener, MouseMotionListener{
int xvar=30;
int yvar=30;
//static PaintClass22 inst1 = new PaintClass22();
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
xvar = arg0.getX();
yvar = arg0.getY();
repaint(xvar,yvar,10,10);
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent arg0) {
// TODO Auto-generated method stub
xvar = arg0.getX();
yvar = arg0.getY();
repaint(xvar,yvar,10,10);
}
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(xvar, yvar, 10, 10);
}
}
You must add the mouseListener to the panel. That doesn’t happen by default as you might have expected 😉
BTW: it’s not recommended to expose public api that’s only meant to be used internally. So instead of letting the panel implement MouseListener (which enforces the public exposure), let the panel create and use a MouseListener:
BTW 2: calling the repaint on the limited area isn’t exactly what you want (?) – it temporarily adds the squares to the painting, they are lost whenever the whole panel is repainted (same effect as with getGraphics). Depending on what you really want,