Java 如何在 Mac OS 上设置 JButton 的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1065691/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:01:39  来源:igfitidea点击:

How to Set the Background Color of a JButton on the Mac OS

javamacosswing

提问by Stephane Grenier

Normally with Java Swing you can set the background color of a button with:

通常使用 Java Swing,您可以使用以下命令设置按钮的背景颜色:

myJButton.setBackground(Color.RED);

which would cause the button to be red. But on the Mac OS, this method seems to be ignored. The button just stays the default color.

这将导致按钮为红色。但是在 Mac OS 上,这种方法似乎被忽略了。按钮只是保持默认颜色。

How can the color of a JButton be set on the Mac OS?

如何在 Mac OS 上设置 JButton 的颜色?

采纳答案by codethulhu

Have you tried setting JButton.setOpaque(true)?

您是否尝试过设置 JButton.setOpaque(true)?

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

回答by MrSmileFace

Have you tried setting the painted border false?

您是否尝试将绘制的边框设置为 false?

JButton button = new JButton();
button.setBackground(Color.red);
button.setOpaque(true);
button.setBorderPainted(false);

It works on my mac :)

它适用于我的 Mac :)

回答by JoJo

If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:

如果您不需要使用 Apple 的外观和感觉,一个简单的解决方法是在将任何 GUI 组件添加到 JFrame 或 JApplet 之前,将以下代码放入您的应用程序或小程序中:

 try {
    UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
 } catch (Exception e) {
            e.printStackTrace();
 }

That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.

这会将外观设置为跨平台外观,然后 setBackground() 方法将更改 JButton 的背景颜色。

回答by Lapis Diamond

I own a mac too! here is the code that will work:

我也有mac!这是可以工作的代码:

myButton.setBackground(Color.RED);
myButton.setOpaque(true); //Sets Button Opaque so it works

before doing anything or adding any components set the look and feel so it looks better:

在做任何事情或添加任何组件之前,先设置外观,让它看起来更好:

try{
   UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
 }catch(Exception e){
  e.printStackTrace(); 
 }

That is Supposed to change the look and feel to the cross platform look and feel, hope i helped! :)

那应该是将外观和感觉更改为跨平台的外观和感觉,希望对我有所帮助!:)

回答by Xiaogang

Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false); try and combine them to fit your purpose

根据您自己的目的,您可以基于 setOpaque(true/false) 和 setBorderPainted(true/false); 尝试将它们结合起来以符合您的目的