简体   繁体   English

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

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

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.但是在 Mac OS 上,这种方法似乎被忽略了。 The button just stays the default color.按钮只是保持默认颜色。

How can the color of a JButton be set on the Mac OS?如何在 Mac OS 上设置 JButton 的颜色?

Have you tried setting JButton.setOpaque(true)?您是否尝试过设置 JButton.setOpaque(true)?

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

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 :)

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 的背景颜色。

I own a mac too!我也有mac! here is the code that will work:这是可以工作的代码:

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!那应该是将外观和感觉更改为跨平台的外观和感觉,希望对我有所帮助! :) :)

Based on your own purposes, you can do that based on setOpaque(true/false) and setBorderPainted(true/false);根据您自己的目的,您可以基于 setOpaque(true/false) 和 setBorderPainted(true/false); try and combine them to fit your purpose尝试将它们结合起来以符合您的目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM