我想知道是否可以在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();
}
如果你想保留原生按钮,那么这取决于操作系统。
frame.setUndecorated(true);
并自己复制按钮。这样就可以在所有的平台上工作,但要实现原生的外观,你必须为每个平台单独实现它。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#invokeLater
或 SwingUtilities#invokeAndWait
.
你去掉标题栏但保留按钮的目的到底是什么?