[英]swing object in front of other objects
我听说默认情况下,swing是双缓冲的。 我不是想让秋千双缓冲。 我正在使用双缓冲,我想添加一些摆动对象(现在只是将JButton添加到JPanel中,然后将其添加到JFrame中)。
问题是我渲染其他东西后抹掉了其他东西的视觉效果后,调用了框架的paint,repaint或paintComponents方法。 在呈现其他内容之前调用方法会导致其他内容位于swing对象的前面(现在只是一个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();
}
}
无需创建自己的BufferStategy !!!
如果要自定义绘画,请重写JPanel的paintComponent()方法,然后将面板添加到框架中。 阅读Swing教程上有关自定义绘画的部分,以获取更多信息和示例。
然后,您仍然可以像对其他面板一样添加组件。 面板的布局管理器将定位组件。
panel.setOpaque(false);
panel.setBackground(Color.yellow);
setBackground(...)不会执行任何操作,因为您说面板不是不透明的,这意味着将绘制父组件的背景。
panel.add("but1", but1);
这不是将组件添加到面板的方式。 正确的使用方法是:
panel.add(but1);
由于您的面板使用的是FlowLayout,因此无需指定约束。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.