我想知道是否可以隐藏 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();
}
最佳答案
如果您想保留 native 按钮,则取决于操作系统。
- Windows:不,您必须使用
frame.setUndecorated(true);
并自行复制按钮。这将适用于所有平台,但要实现 native 外观,您必须为每个平台单独实现它。 - 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);
});
请注意,UI 的所有创建和修改都应使用 SwingUtilities#invokeLater
或 SwingUtilities#invokeAndWait
在 Swing 主线程上进行。
删除标题栏但保留按钮的具体目标是什么?
关于java - 有没有办法隐藏标题栏,但将按钮保留在 JFrame 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61373284/