0

I've made a simple program where you should be able to hold and drag the mouse to paint something. Now, this program works fine on my Windows, but when I try the exact same code on my Mac, the 10x10 dot I'm trying to draw with just follows the cursor, but doesn't leave a track behind it.

First, I thought it was a problem with the JDK, so I've reinstalled and installed different versions. Same with both Eclipse And Netbeans, reinstalled multiple times, but it did not work.

public class panelDraw extends JPanel {

int x, y;

/**
 * Create the panel.
 */
public panelDraw() {
    addMouseMotionListener(new MouseMotionAdapter() {
        @Override
        public void mouseDragged(MouseEvent e) {
            x = e.getX();
            y = e.getY();
            repaint();
        }
    });

}
public void paintComponent(Graphics g) {
    g.fillRect(x, y, 10, 10);
}

Here is the panel that I then put in a JFrame to run the program. As I said, no problem on my Windows, but on the Mac, it doesn't "draw" anything the dot just follows the cursor.

Thank you for the help!

SteveFerg
  • 3,466
  • 7
  • 19
  • 31
  • 1
    1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) In all cases of custom painting, **always** call the `super` method first. – Andrew Thompson May 24 '19 at 07:44
  • 1
    *"you should be able to hold and drag the mouse to paint something."* If I'm reading that correctly, and the intent is to have past squares remain, the Windows JRE is doing exactly what the code intends, but the code is broken. OTOH the Mac JRE is somehow correcting the code problem. The **correct** way to go about this is to either a) store the list of points in an expandable collection such as an `ArrayList` and each time when painting, call the super method then iterate the array. b) Alternately, make each paint to a `BufferedImage` displayed in a label and `repaint()` the label. – Andrew Thompson May 24 '19 at 08:09
  • @AndrewThompson Do you have any examples of how you could make this program with your alternatives? – Lillieskold May 24 '19 at 08:22
  • Yes, lots. Your search facility for SO is as good as mine, so have at it. – Andrew Thompson May 24 '19 at 08:23
  • Follow [this answer](https://stackoverflow.com/a/46577656/3992939) to see how clicked points are stored in an `ArrayList` and used for painting. – c0der May 24 '19 at 12:36
  • 1
    @AndrewThompson Thank you for the help I got it to work with an ArrayList! – Lillieskold May 24 '19 at 13:26
  • 1
    @Lillieskold, see [Custom Painting Approaches](https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/) for two examples. One using an ArrayList and one using a BufferedImage. – camickr May 24 '19 at 13:54

0 Answers0