Nick227889
Nick227889

Reputation: 91

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

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

Upvotes: 0

Views: 912

Answers (1)

weisj
weisj

Reputation: 962

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?

Upvotes: 1

Related Questions