我有一个有两层的窗口:一个静态背景和一个包含移动对象的前景。我的想法是只绘制一次背景(因为它不会改变),所以我让改变面板透明并将其添加到静态背景之上。这是此的代码:
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);
}
这段代码为我提供了我想要的正确图像,但每次我 repaint时changingPanel
,staticPanel
也会重新绘制(这显然违背了只绘制一次静态面板的整个想法)。有人可以告诉我有什么问题吗?
仅供参考,我正在使用 javax.swing.Timer 每秒 24 次重新计算和重新绘制更改面板。