Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing addMouseListener() and paintComponent() for JPanel
    primarykey
    data
    text
    <p>This is a follow-up to my <a href="https://stackoverflow.com/questions/12175174/paintcomponent-vs-paint-and-jpanel-vs-canvas-in-a-paintbrush-type-gui">previous</a> question. I've simplified things as much as I could, and it still doesn't work! Although the good thing I got around using <code>getGraphics()</code>. </p> <p>A detailed explanation on what goes wrong here is massively appreciated. My suspicion is that something's wrong with the the way I used <code>addMouseListener()</code> method here. </p> <p>EDIT completely rewrote the code. Still does not work properly though. </p> <pre><code>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); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload