Hello,
I have a window that has two layers: a static background and a foreground that contains moving objects. My idea is to draw the background just once (because it's not going to change), so I make the changing panel transparent and add it on top of the static background. Here is the code for this:
public static void main(String[] args) {
JPanel changingPanel = new JPanel() {
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(100, 100, 100, 100);
}
};
changingPanel.setOpaque(false);
JPanel staticPanel = new JPanel();
staticPanel.setBackground(Color.BLUE);
staticPanel.setLayout(new BorderLayout());
staticPanel.add(changingPanel);
JFrame frame = new JFrame();
frame.add(staticPanel);
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
This piece of code gives me the correct image I want, but every time I repaint changingPanel
, staticPanel
gets repainted as well (which is obviously against the whole idea of painting the static panel just once). Can somebody show me what's wrong?
FYI I am using the javax.swing.Timer to recalculate and repaint the changing panel 24 times every second.