有没有一种方法可以隐藏标题栏,但在JFrame中保留按钮?

问题描述 投票:0回答:1

我想知道是否可以在Java Swing中隐藏标题栏,但保留最大化、最小化和关闭按钮。

我试过在标题栏中添加 frame.setUndecorated(true); 但它完全删除了最大化、最小化和关闭按钮。

这是我的代码。

public Display(String title, int width, int height) {
        Display.width = width;
        Display.height = height;

        Display.absWidth = width;
        Display.absHeight = height;

        Display.d = new Dimension(width, height);

        setProperties();

        image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        canvas = new Canvas();
        canvas.setPreferredSize(new Dimension(width, height));

        frame = new JFrame(title);
        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

        frame.setLayout(new BorderLayout());
        frame.add(canvas, BorderLayout.CENTER);
        frame.setIgnoreRepaint(true);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setResizable(true);

        canvas.createBufferStrategy(2);
        bs = canvas.getBufferStrategy();
        g = bs.getDrawGraphics();

        frame.getRootPane().putClientProperty("apple.awt.fullWindowContent", true);
        frame.getRootPane().putClientProperty("apple.awt.transparentTitleBar", true);

        frame.setVisible(true);

        handleResize();
        handleQuit();

        //showSplashScreen();
    }
java jframe hide titlebar
1个回答
1
投票

如果你想保留原生按钮,那么这取决于操作系统。

  • 在Windows系统中。不,你将不得不使用 frame.setUndecorated(true); 并自己复制按钮。这样就可以在所有的平台上工作,但要实现原生的外观,你必须为每个平台单独实现它。
  • macOS: 如果你使用jdk 12或更新的版本,你可以使用。
rootPane.putClientProperty(“apple.awt.fullWindowContent“, true);
rootPane.putClientProperty(“apple.awt.transparentTitleBar“, true);

这是从jdk测试案例中提取的。

SwingUtilities.invokeLater(() -> {
    frame = new JFrame("Test");
    frame.setBounds(200, 200, 300, 100);
    rootPane = frame.getRootPane();
    JComponent contentPane = (JComponent) frame.getContentPane();
    contentPane.setBackground(Color.RED);
    rootPane.putClientProperty("apple.awt.fullWindowContent", true);
    rootPane.putClientProperty("apple.awt.transparentTitleBar", true);
    frame.setVisible(true);
});

请注意,所有用户界面的创建和修改 都应该在Swing主线程上进行。SwingUtilities#invokeLaterSwingUtilities#invokeAndWait.

你去掉标题栏但保留按钮的目的到底是什么?

© www.soinside.com 2019 - 2024. All rights reserved.