Painting on JTabbedPanes
I have code which reads rectangle tags from an svg file and displays them on a canvas in a tabbed pane, when I first click on the tabbed pane the image appears but when I click on another tab then go back to this tab the rectangle is not there. It does not appear to be repainting. How do I set my tabbed pane up so that when a user clicks on a tab the canvas is repainted?
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Painting
{
JTabbedPane tabbedPane;
public Painting()
{
double[][] coords = {
{ 1.0/4, 1.0/4, 1.0/2, 2.0/3 }, { 1.0/3, 1.0/4, 1.0/3, 3.0/8 }
};
Color[] colors = { Color.blue, Color.red };
tabbedPane = new JTabbedPane();
tabbedPane.addTab("blue", getPanel(coords[0], colors[0]));
tabbedPane.addTab("red", getPanel(coords[1], colors[1]));
}
private JPanel getPanel(final double[] d, final Color color)
{
JPanel panel = new JPanel()
{
/**
* swing always calls this method when your component
* needs to be rendered so whatever you want to paint
* will always show up if you put the code in here
*/
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int w = getWidth();
int h = getHeight();
double x= d[0] * w;
double y= d[1] * h;
double width = d[2] * w;
double height = d[3] * h;
g2.setPaint(color);
g2.draw(new Rectangle2D.Double(x, y, width, height));
}
};
return panel;
}
public static void main(String[] args)
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(new Painting().tabbedPane);
f.setSize(400,400);
f.setLocation(200,200);
f.setVisible(true);
}
}