如何编辑JFrame标题栏?保留装饰并修改样式与图标
解决方案:修改JFrame原生标题栏样式与图标
一、更换JFrame窗口图标
直接通过setIconImage()方法即可设置窗口图标,示例代码如下:
import javax.swing.JFrame; import java.awt.Image; import java.awt.Toolkit; public class CustomFrame extends JFrame { public CustomFrame() { setTitle("自定义窗口"); // 加载图标,可替换为你的图标路径,项目内资源可用getClass().getResource()加载 Image appIcon = Toolkit.getDefaultToolkit().getImage("path/to/your/icon.png"); setIconImage(appIcon); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public static void main(String[] args) { new CustomFrame(); } }
二、修改原生标题栏为黑色
原生JFrame的标题栏由操作系统窗口管理器控制,Swing没有直接修改其背景色的官方API,以下是两种可行方案:
方案1:使用第三方LookAndFeel(推荐)
推荐使用FlatLaf——一款现代Swing主题库,它支持自定义标题栏样式,同时保留原生窗口的拖拽、缩放等系统交互功能,无需自行实现。
示例代码:
import com.formdev.flatlaf.FlatDarkLaf; import com.formdev.flatlaf.FlatLaf; import javax.swing.JFrame; import java.awt.Image; import java.awt.Toolkit; public class CustomTitleBarFrame { public static void main(String[] args) { // 初始化深色主题 FlatDarkLaf.setup(); // 自定义标题栏为纯黑色,同时设置标题文字为白色增强可读性 FlatLaf.setGlobalExtraDefaults(new Object[]{ "TitlePane.background", "#000000", "TitlePane.foreground", "#ffffff" }); JFrame frame = new JFrame("黑色原生标题栏"); // 设置窗口图标 Image appIcon = Toolkit.getDefaultToolkit().getImage("path/to/your/icon.png"); frame.setIconImage(appIcon); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
注:使用前需引入FlatLaf依赖,Maven项目可在pom.xml中添加对应依赖,普通项目直接下载jar包导入即可。
方案2:跟随系统深色模式
如果目标系统(Windows 10/11、macOS等)支持系统级深色模式,可让JFrame跟随系统主题,此时标题栏会自动变为深色(接近黑色),且保留原生交互:
import javax.swing.JFrame; import javax.swing.UIManager; import java.awt.Image; import java.awt.Toolkit; public class SystemThemeFrame { public static void main(String[] args) { try { // 使用系统原生LookAndFeel UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // Windows系统下强制启用深色主题(Java 11+支持) if (System.getProperty("os.name").toLowerCase().contains("win")) { UIManager.put("win.darkMode.enabled", true); } } catch (Exception e) { e.printStackTrace(); } JFrame frame = new JFrame("跟随系统深色标题栏"); Image appIcon = Toolkit.getDefaultToolkit().getImage("path/to/your/icon.png"); frame.setIconImage(appIcon); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
内容的提问来源于stack exchange,提问作者luci_the_coder
相关产品推荐
相关产品推荐

