代码之家  ›  专栏  ›  技术社区  ›  Stefan Dollase

Java2D OpenGL图形加速不工作

  •  3
  • Stefan Dollase  · 技术社区  · 10 年前

    我想将Swing与Java2DOpenGL图形加速一起使用。然而,它不起作用。

    我自己回答了这个问题,因为我花了很长时间寻找解决方案。

    这是我的代码:

    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class OpenGLTest {
        public static void main(String[] args) throws ClassNotFoundException,
                InstantiationException, IllegalAccessException,
                UnsupportedLookAndFeelException {
            // set system look and feel
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    
            // activate opengl
            System.setProperty("sun.java2d.opengl", "true");
    
            // create and show the GUI in the event dispatch thread
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    
        private static void createAndShowGUI() {
            JFrame frame = new JFrame();
            frame.setTitle("OpenGL Test");
            frame.setSize(400, 300);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
        }
    }
    
    1 回复  |  直到 10 年前
        1
  •  4
  •   Stefan Dollase    10 年前

    问题

    上述代码的问题在于,它在属性之前与Swing类交互 "sun.java2d.opengl" 设置为 "true" 。设置外观和感觉已经算作这样的交互。

    验证问题

    您可以通过设置属性 “sun.java2d.opengl” 到 "True" 而不是 “真实” 。如中所述 Java2D Properties Guide ,这会导致Java在激活OpenGL图形加速时向控制台输出以下消息:

    OpenGL pipeline enabled for default config on screen 0
    

    在属性设置为的情况下执行问题中的代码 “正确” 不输出此消息。这表示OpenGL图形加速未激活。

    解决方案

    要解决此问题,请在设置外观之前设置属性。

    替换此

            // set system look and feel
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    
            // activate opengl
            System.setProperty("sun.java2d.opengl", "true");
    

    通过这个

            // activate opengl
            System.setProperty("sun.java2d.opengl", "True");
    
            // set system look and feel
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    

    这会导致代码显示上面给出的调试消息,这表明OpenGL图形加速确实已激活。