【发布时间】:2015-02-01 05:29:15
【问题描述】:
我听说swing默认是双缓冲的。我不想让摆动双缓冲。我正在使用双缓冲,我想添加一些摆动对象(现在只是一个添加到 JFrame 中的 JButton)。
问题是在我渲染其他内容后调用框架的绘制、重绘或paintComponents 方法会擦除其他内容的视觉效果。在渲染其他东西之前调用这些方法会导致其他东西出现在摆动对象的前面(现在只是一个 JButton)。直接对JPanel做同样的事情似乎没有效果。
我相信我需要一种方法来绘制没有默认背景(灰色)的 Jframe 或添加到其中的 JPanel,这会导致窗口在设置为 Color(0,0,0,0) 时变为空白。
public void paint() {
// uses double buffering system.
do {
do {
Graphics2D g2d = (Graphics2D) bufferStrategy.getDrawGraphics();
g2d.fillRect(0, 0, frame.getWidth(), frame.getHeight());
try {// frame.paintComponents(g2d); // calling it here draws buttons to behind of the object
rendering(g2d); // I draw other objects in this method
// frame.paintComponents(g2d);// calling it here makes other objects disappear
} catch (NullPointerException e) {
e.printStackTrace();
}
g2d.dispose();
} while (bufferStrategy.contentsRestored());
bufferStrategy.show();
} while (bufferStrategy.contentsLost());
}// method end
这就是我设置按钮的方式:
private void setUpGUI() {
panel = new JPanel();
LayoutManager layout = new FlowLayout();
panel.setLayout(layout);
panel.setOpaque(false);//this does not seems to have any effect
panel.setBackground(Color.yellow);//this does not seems to have any effect. this is just for testing
JButton but1 = new JButton("but1");
panel.add("but1", but1);
frame.add(panel);
}
编辑: 这是解决方法/修复:
新的绘制方法:
public void paint() {
// uses double buffering system.
do {
do {
Graphics2D g2d = (Graphics2D) bufferStrategy.getDrawGraphics();
g2d.fillRect(0, 0, frame.getWidth(), frame.getHeight());
try {
frame.paint(g2d);
} catch (NullPointerException e) {
e.printStackTrace();
}
g2d.dispose();
} while (bufferStrategy.contentsRestored());
bufferStrategy.show();
} while (bufferStrategy.contentsLost());
}// method end
我已经覆盖了面板的绘制方法:
@Override
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
Main.main().rendering(g2d);
super.paint(g);
g.dispose();
g2d.dispose();
}
}
【问题讨论】:
-
那么你应该覆盖
update(Graphics)并防止swing清除你的组件 -
@msrd0 我试过了。现在显示面板的黄色背景。我已经设置了 panel.setOpaque(false)。之后只有我的按钮显示,其他对象在灰色背景下丢失
标签: java swing jframe jbutton paintcomponent