我希望在 3D OpenGL 视图上绘制各种 HUD,但似乎在我的面板中完成的任何绘图都会被忽略,尽管它已经完成。
这是一些准系统代码。
我的框架;
public class MyFrame extends JFrame{
private static final long serialVersionUID = 1L;
public MyFrame(Labyrinth l){
super();
this.setTitle("My Frame");
this.setSize(512, 384);
this.setContentPane(new MyPanel());
//this.setVisible(true);//If needed here.
}
}
MyPanel;
public class MyPanel extends JPanel {
private static final long serialVersionUID = 1L;
public MyPanel(){
super();
this.setLayout(new BorderLayout());
MyCanvas mc=new MyCanvas(l);
mc.setFocusable(false);
this.add(this.mc, BorderLayout.CENTER);
//this.revalidate();//Doesn't seem needed in the instanciation.
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.mc.repaint();
g.setColor(new Color(128,128,128));
g.fillRect(0, 0, this.getWidth()/2,this.getHeight()/2);
//top-left quarter should be greyed away.
}
}
MyCanvas;
public class MyCanvas extends GLCanvas{
private static final long serialVersionUID = 1L;
public MyCanvas(){
super(new GLCapabilities(GLProfile.getDefault()));
}
}
绘画发生了,但没有显示在视图中。我试过覆盖 repaint()、paint(Graphics)、paintComponent(Graphics) 和 update()。有人说在“重量级”组件上绘制很复杂,我应该直接在组件中绘制或使用其他类型。我显然需要 GLCanvas 来显示 3D 渲染,同时它似乎没有提供绘制叠加层的工具。有人告诉我只需在 JFrame 的 glassPane 中进行绘图,但这似乎有点矫枉过正,而且我被告知永远不要在 glassPane 周围玩耍,因此我不打算这样做。
我已经看到许多关于绘画调用顺序的主题,但是我无法确定在覆盖这样或那样的方法时哪个是正确的,我什至不知道是否应该覆盖或应该覆盖哪种方法。是否有一种明显的方式我会错过在其 GLCanvas 组件上显示我的简单 JPanel 绘画?
首先,我真的不建议通过这些方式获得 HUD。因为我只能想象这种伤害性的表现。当然,我从未尝试过像这样混合 Java、OpenGL 和 AWT 的图形。
现在,不要使用胶带将这些类固定在一起,而是考虑使用JLayeredPane
.
JLayeredPane layeredPane = new JLayeredPane();
layeredPane.add(new MyCanvas());
layeredPane.add(new MyPanel());
frame.add(layeredPane);
现在重要的部分是您必须手动设置两个组件的边界:
canvas.setBounds(x, y, width, height);
panel.setBounds(x, y, width, height);
如果不是,您最终会遇到与以前相同的问题:
绘画发生了,但没有显示在视图中
为了演示它的工作原理,我创建了这个TestPanel
类似于您的MyPanel
.
public static class TestPanel extends JPanel {
private Color color;
public TestPanel(Color color) {
this.color = color;
}
@Override
public void paintComponent(Graphics g) {
g.setColor(color);
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
}
}
然后像这样创建两个实例:
JPanel panel1 = new TestPanel(new Color(255, 0, 0));
panel1.setBounds(25, 25, 100, 100);
JPanel panel2 = new TestPanel(new Color(0, 0, 255));
panel2.setBounds(75, 75, 100, 100);
然后将它们添加到aJLayeredPane
并将其添加到a中JFrame
,我们将看到:
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句