Is there a way to hide the title bar, but keep the buttons in JFrame

蓝咒 提交于 2021-01-29 16:27:13

问题


I was wondering if I could hide the title bar in Java Swing, but keep the maximize, minimize, and close buttons.

I've tried adding frame.setUndecorated(true); but it removes the maximize, minimize, and close buttons completely.

Here is my code:

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

回答1:


If you want to keep the native buttons then it depends on the operating system.

  • Windows: No, you will have to use frame.setUndecorated(true); and replicate the buttons yourself. This would then work on all platforms, but to achieve a native look you’d have to implement it for each individually.
  • macOS: If you use jdk 12 or newer you can achieve it using:
rootPane.putClientProperty(“apple.awt.fullWindowContent“, true);
rootPane.putClientProperty(“apple.awt.transparentTitleBar“, true);

This is taken from the jdk test cases:

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

Note that all creation and modification of the ui should happen on the Swing main thread using SwingUtilities#invokeLater or SwingUtilities#invokeAndWait.

What exactly is your goal in removing the title bar but keeping the buttons?



来源:https://stackoverflow.com/questions/61373284/is-there-a-way-to-hide-the-title-bar-but-keep-the-buttons-in-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!