gpt4 book ai didi

java - 如何在 mac 中将 JMenuBar 置于顶部并更改 JButton 的背景

转载 作者:行者123 更新时间:2023-12-01 11:08:13 24 4
gpt4 key购买 nike

我正在用 java 构建 Mac 桌面应用程序。我想更改 JButton 的背景,并且还想让 JMenuBar 位于顶部。

为了将 JMenuBar 放在顶部,我添加了以下代码:

  System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty(
"com.apple.mrj.application.apple.menu.about.name", "Stack");

它成功了!

为了改变背景颜色,我使用了这个:

    JButton b = new JButton("press me!");

b.setBackground(Color.blue);

b.setContentAreaFilled(false);
b.setOpaque(true);
b.setBorderPainted(true);
try {
UIManager.setLookAndFeel(UIManager
.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {

}

而且它也有效!

问题是,当我更改颜色时,JMenuBar 不在顶部。经过一番调试后,我知道更改 LookAndFeel 是负责任的。

完整代码:

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.UIManager;

public class Main {
public static void main(String[] args) {
System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty(
"com.apple.mrj.application.apple.menu.about.name", "Stack");

JButton b = new JButton("press me!");
b.setBackground(Color.blue);
b.setContentAreaFilled(false);
b.setOpaque(true);
b.setBorderPainted(true);
try {
UIManager.setLookAndFeel(UIManager
.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {

}
JFrame f = new JFrame();
f.add(b);
JMenuBar m = new JMenuBar();
m.add(new JMenu("item"));
f.setJMenuBar(m);
f.setVisible(true);
f.setVisible(true);
}
}

所以这段代码改变了按钮的颜色,但 JMenuBar 不在顶部。如果您在尝试中注释这些行,它不会改变颜色,但会将 JMenuBar 放在顶部。

有什么帮助吗?

提前致谢!

最佳答案

我通过添加行解决了这个问题

b.setUI(new MetalButtonUI());

并删除 try catch。

它最终看起来像这样:

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalButtonUI;

public class Main {

public static void main(String[] args) {

System.setProperty("apple.laf.useScreenMenuBar", "true");
System.setProperty("com.apple.mrj.application.apple.menu.about.name",
"Stack");
JButton b = new JButton("press me!");

b.setBackground(Color.blue);

b.setContentAreaFilled(false);
b.setOpaque(true);
b.setBorderPainted(true);
b.setUI(new MetalButtonUI());


JFrame f = new JFrame();

f.add(b);



f.setBounds(0, 0, 500, 500);
JMenuBar m = new JMenuBar();

m.add(new JMenu("item"));



f.setJMenuBar(m);
f.setVisible(true);

f.setVisible(true);
}
}

关于java - 如何在 mac 中将 JMenuBar 置于顶部并更改 JButton 的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32692776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com