简体   繁体   English

从另一个JPanel内部重新绘制一个JPanel

[英]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. 因此,我正在制作一个绘画程序,我有一个主要的Paint类(用于检测鼠标输入和绘画),以及一个Tools类(其为左侧的工具栏),其中包含许多工具,例如笔刷大小更改和形状更改。 So, I want to add a clear button to the Tools class which clears the whole screen. 因此,我想向Tools类添加一个清除按钮,以清除整个屏幕。 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类持有要Paint的点的ArrayList,而我无法从Tools内重新绘制Paint

Paint class Paint

//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 Tools

//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 . 我遇到的问题是repaint()是实例方法,因此我无法从Tools内访问Paint的repaint。

Just pass a reference to the Paint instance to Tools 's constructor. 只需将对Paint实例的引用传递给Tools的构造函数。 Or, call repaint on the container ( JFrame , etc.) that contains both of them, which should cause all its children to be repainted. 或者,在包含两者的容器( JFrame等)上调用重绘,这将导致其所有子级都被重绘。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM