0

I have an application with jTabbedPane. There are two tab (JPanel) in jTabbedPane. First tab includes canvas and second one includes simple JLabel. Button draws rectangle into canvas.

Every thing is fine until then. However, when switching tabs, canvas would lose everything. It should be repainted by itself.

Rectangle should exist after changing tabs. Do you have any idea about the problem?

My button code is here:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    Graphics g = canvas1.getGraphics();
    g.drawRect(10, 10, 100, 100);
}

Thanks in advance.

Blessed Geek
  • 21,058
  • 23
  • 106
  • 176
  • 1
    don't paint on the graphics returned by jcomponent.getGraphics, it's very volatile. Instead, store the rectangle coordinates somewhere, override paintComponent to draw it and call repaint in the action – kleopatra Feb 24 '13 at 16:34

1 Answers1

0

First of all, you shouldn't put AWT components inside Swing components. Use JComponent or JPanel instead of Canvas.

Second, no, it shouldn't repaint itself. When the button is clicked, you should simply store what should be painted in some variable, and the paintComponent() method should be overridden in order to paint what is stored in this variable. This way, every time the component is repainted, it will repaint what has been stored last in this variable.

For example:

public class RectangleComponent extends JComponent {

    private boolean shouldPaintRectangle = false;

    public void setShouldPaintRectangle(boolean b) {
        this.shouldPaintRectangle = b;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (shouldPaintRectangle) {
            g.drawRect(10, 10, 100, 100);
        }
    }
}

In general, you should never ask the Graphics of a component and paint on it. Instead, you should override paintComponent() and paint the component using the Graphics passed as argument.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255