Odd graphic error: A copy of component A is written on component B. HELP! (Java)

I created a simple drawing program in which you can use a brush tool to paint different colors and erase (just paint in white).

It works fine, but I have a very strange graphical error that causes the toolbar and the last color / tool icon hovering over the icon to draw over the drawn panel.

Implementation: the frame contains two JPanel extensions: ToolPanel and DrawPanel. ToolPanel contains two JPanels that contain color buttons and tools. Buttons are extensions of JComponent.

link to the screenshot (I am not allowed to post images):

enter image description here

: "" , , . "" , , .

2: JMenuBar, . , drawpanel , ( ) .

: ( , : P)

DrawPanel paintComponent :

    public void paintComponent(Graphics g) { 
    if(isMousePressed) {
        if(tool == "BRUSH") {
            g.setColor(color);
            g.fillOval(currentEvent.getX(), currentEvent.getY(), 30, 30);
        } else if(tool == "ERASER") {
            g.setColor(getBackground());
            g.fillOval(currentEvent.getX(), currentEvent.getY(), 30, 30);

        }
    }
}

, - , .

: super.paintComponent DrawPanels paintComponent-method, , ? , , , , , , . , . , - ? - ?

!

+5
2

, , , Graphics (g.create()) , , , , .

(, , ), SSCCE, , . .

Graphics .

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (isMousePressed) {
        // create the new Graphics context which
        // we can work with/modify independently
        g2 = g.create();
        // use "str".equals() for String comparisons
        if ("BRUSH".equals(tool)) {
            g2.setColor(color);
            g2.fillOval(currentEvent.getX(), currentEvent.getY(), 30, 30);
        } else if ("ERASER".equals(tool)) {
            g2.setColor(getBackground());
            g2.fillOval(currentEvent.getX(), currentEvent.getY(), 30, 30);
        }
        // you should always dispose() of a Graphics
        g2.dispose();
    }
}
+3

, Swing, , . , , .

( setTransparent setOpaque), , , , .

+3

All Articles