【问题标题】:Java2D OpenGL graphics acceleration not workingJava2D OpenGL 图形加速不起作用
【发布时间】:2016-02-26 09:09:08
【问题描述】:

我想将 Swing 与 Java2D OpenGL 图形加速一起使用。但是,它不起作用。

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

这是我的代码:

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);
    }
}

【问题讨论】:

    标签: java swing opengl look-and-feel


    【解决方案1】:

    问题

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

    验证问题

    您可以通过将属性"sun.java2d.opengl" 设置为"True" 而不是"true" 来查看这一点。如Java2D Properties Guide 中所述,这会导致 Java 在激活 OpenGL 图形加速时向控制台输出以下消息:

    OpenGL pipeline enabled for default config on screen 0
    

    在属性设置为"True" 的情况下执行问题中的代码不会输出此消息。这表明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图形加速。

    【讨论】:

    • 你不会通过命令行使用-D 正常传递属性吗?
    • -D 参数与setProperty 方法基本相同。但是,并不总是可以使用该参数。例如,如果您在没有安装程序且没有针对每个操作系统的附加启动脚本的情况下交付可执行 jar 文件。
    • 是的,我只是认为打开和关闭它更容易(而且我通常将我的程序包装在 .exe 或 .app 包中)
    • 这当然是解决同一问题的另一种可行的解决方案。我猜每个解决方案都涵盖了一个略有不同的用例。此外,您只需提供 .exe 和 .app 文件,就会错过 Linux 用户。
    猜你喜欢
    • 1970-01-01
    • 2010-12-06
    • 2018-01-22
    • 2013-10-29
    • 2011-05-16
    • 2012-03-13
    • 1970-01-01
    • 2015-01-05
    • 1970-01-01
    相关资源
    最近更新 更多