我正在编写一个应用程序,它有一个 JLayeredPane(称为层),其中包含不同层中的两个 JPanel。我覆盖了底部JPanel 的paintComponent 方法(称为grid_panel),因此它绘制了一个网格,并覆盖了顶部JPanel 的paintComponent 方法(称为circuit_panel),因此它绘制了一个电路。
以下是结构的摘要:
layers -
|-circuit_panel (on top)
|-grid_panel (at bottom)
我希望 grid_panel 保持静态,即不进行任何重绘(最初的重绘除外),因为它不会改变。
问题是,每当我调用 circuit_panel.repaint() 时,grid_panel 也会被重新绘制! 这绝对是没有效率的。
我认为这是由于 JLayeredPane 的热切绘画行为。有没有办法在 JLayeredPane 中禁用此功能?
如果你有兴趣看看上面的效果,我写了一个小演示程序:
public class Test2 extends JFrame {
public Test2() {
JLayeredPane layers = new JLayeredPane();
layers.setPreferredSize(new Dimension(600, 400));
MyPanel1 myPanel1 = new MyPanel1();
MyPanel2 myPanel2 = new MyPanel2();
myPanel1.setSize(600, 400);
myPanel2.setSize(600, 400);
myPanel1.setOpaque(false);
myPanel2.setOpaque(false);
myPanel2.addMouseListener(new MyMouseListener(myPanel2));
layers.add(myPanel1, new Integer(100)); // At bottom
layers.add(myPanel2, new Integer(101)); // On top
this.getContentPane().add(layers, BorderLayout.CENTER);
this.setSize(600, 400);
}
class MyPanel1 extends JPanel {
Color getRandomColor() {
int r = (int) (256 * Math.random());
int g = (int) (256 * Math.random());
int b = (int) (256 * Math.random());
return new Color(r, g, b);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getRandomColor());
g2d.fillRoundRect(30, 30, 60, 60, 5, 5);
}
}
class MyPanel2 extends JPanel {
Color getRandomColor() {
int r = (int) (256 * Math.random());
int g = (int) (256 * Math.random());
int b = (int) (256 * Math.random());
return new Color(r, g, b);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(getRandomColor());
g2d.fillRoundRect(45, 45, 75, 75, 5, 5);
}
}
class MyMouseListener extends MouseAdapter {
JPanel panel;
MyMouseListener(JPanel panel) {
this.panel = panel;
}
@Override
public void mouseClicked(MouseEvent e) {
panel.repaint();
}
}
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
(new Test2()).setVisible(true);
}
});
}
}