Using addMouseListener() and paintComponent() for JPanel
- by Alex
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.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MainClass1{
private static PaintClass22 inst2 = new PaintClass22();
public static void main(String args[]){
JFrame frame1 = new JFrame();
frame1.add(inst2);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setTitle("NewPaintToolbox");
frame1.setSize(200, 200);
frame1.setLocationRelativeTo(null);
frame1.setVisible(true);
}
}
class PaintClass11 extends MouseAdapter{
int xvar;
int yvar;
static PaintClass22 inst1 = new PaintClass22();
public PaintClass11(){
inst1.addMouseListener(this);
inst1.addMouseMotionListener(this);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
xvar = arg0.getX();
yvar = arg0.getY();
inst1.return_paint(xvar, yvar);
}
}
class PaintClass22 extends JPanel{
private static int varx;
private static int vary;
public void return_paint(int input1, int input2){
varx = input1;
vary = input2;
repaint(varx,vary,10,10);
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.setColor(Color.RED);
g.fillRect(varx, vary, 10, 10);
}
}