JFrame使用Windows边框进行装饰,否则即使设置了外观也感觉不到

Tim*_*mos 3 java swing jframe look-and-feel

今天是个好日子.

首先:检查此图像.

请注意,在3个框架的第一个框架中,按钮采用金属外观设计,但框架采用Windows风格.在按钮LAF与帧LAF匹配的情况下,其他2帧是"OK".

所有这些的代码(与图像的顺序相同):

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {             
            JFrame frame = new JFrame();

            frame.getContentPane().add(new JButton("button"));
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    });
}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {             
            JFrame frame = new JFrame();

            frame.setUndecorated(true);
            frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
            frame.setSize(100, 100); 

            frame.getContentPane().add(new JButton("button"));
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    });
}

public static void main(String[] args) {

    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            try {
                // 0 => "javax.swing.plaf.metal.MetalLookAndFeel"
                // 3 => the Windows Look and Feel
                String name = UIManager.getInstalledLookAndFeels()[3].getClassName();
                UIManager.setLookAndFeel(name);
            } catch (Exception ex) {
                ex.printStackTrace();
            }

            JFrame frame = new JFrame();

            frame.getContentPane().add(new JButton("button"));
            frame.setVisible(true);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

现在困扰我的是我从未被迫使用这些线条frame.setUndecorated(true); frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);,因为设置外观只是使用该UIManager.setLookAndFeel()方法.通常情况下,JFrame本身也会被设计样式,但这似乎不再是这种情况,因为我得到了一个Windows风格的框架(第一张图片,1个代码片段).

为什么是这样?这是Java 7中的新功能吗?这看起来很奇怪.

通常,在不涉及涉及外观和感觉的代码的情况下,程序应该从Metal Look and Feel开始,因为这是标准的Java外观.那么为什么第一个程序从Windows框架开始呢?

Dre*_*rew 6

在初始化JFrame之前,在main方法中添加此行

JFrame.setDefaultLookAndFeelDecorated(true);
Run Code Online (Sandbox Code Playgroud)

前一段时间我开始使用物质时注意到了同样的事情,但这条线就是修复它所需要的.

如前面的代码片段所示,您必须在创建希望影响其装饰的帧之前调用setDefaultLookAndFeelDecorated方法.您使用setDefaultLookAndFeelDecorated设置的值将用于随后创建的所有JFrame.您可以通过调用JFrame.setDefaultLookAndFeelDecorated(false)切换回使用窗口系统装饰.有些外观可能不支持窗户装饰; 在这种情况下,使用窗户系统装饰.

这是来自Oracle参考该行代码.

这是Java的一个特性,默认情况下JFrame Window边框不会被装饰,但使用上面提到的函数允许设置外观来装饰Window.据我所知,这个功能在1.4中实现.

编辑:

此外,如果要将自定义外观应用于JDialog窗口边框,可以在JDialog类上使用与JFrame上调用它相同的静态方法:

JDialog.setDefaultLookAndFeelDecorated(true);
Run Code Online (Sandbox Code Playgroud)