L1ghtShadow
L1ghtShadow

Reputation: 212

Repaint a JPanel from within another JPanel

So, I am making a painting program and I have a main Paint class which detects mouse input and paints and a Tools class which is a toolbar on the left which holds a bunch of tools, like brush size change and shape change. So, I want to add a clear button to the Tools class which clears the whole screen. My problem is that the Paint class is holding the ArrayList of points which it paints and I can't repaint Paint from within Tools.

Paint class

//imports    
public class Paint extends JPanel{
    private ArrayList<Brush> points;
    ...

    public Paint() {
        ...
    }

    public void paintComponent(Graphics page) {
        ...

        //draws all points in the arraylist
        for (Brush b : points) {
            //paint points
        }
    }
}

Tools class

//imports
public class Tools extends JPanel
{
    private JButton clear;

    public Tools() {
        clear = new JButton("Clear");
        clear.addActionListener(new BrushInput());
    }

    public void paintComponent(Graphics page) {
        ...
    }
    private class BrushInput implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == clear) {
                //clear points arraylist and repaint
            }
        }
    }

}

The issue I'm having is that repaint() is an instance method and so I can't access Paint's repaint from within Tools.

Upvotes: 0

Views: 61

Answers (1)

David Conrad
David Conrad

Reputation: 16399

Just pass a reference to the Paint instance to Tools's constructor. Or, call repaint on the container (JFrame, etc.) that contains both of them, which should cause all its children to be repainted.

For example:

public class Paint extends JPanel {
    private ArrayList<Brush> points;

    // . . .

    public void clear() {
        points.clear();
        repaint();
    }
}

public class Tools extends JPanel {
    private JButton clear;
    private Paint paint;

    public Tools(Paint paint) {
        this.paint = paint;
        // . . .
    }

    // . . .

    private class BrushInput implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == clear) {
                paint.clear();
            }
        }
    }
}

Code that creates these components:

Paint paint = new Paint();
Tools tools = new Tools(paint);

Upvotes: 1

Related Questions