java 按钮颜色黑边,更改JButton的背景颜色始终显示为灰色

I am making a GUI interface and I am trying to change the background and foreground color of my windows with the following code:

import java.awt.Color;

import java.awt.Component;

import java.awt.Container;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

public class Test

{

public static void changeColor(String typeOfColor, Component component, Color color)

{

if (typeOfColor.equals("Background"))

{

component.setBackground(color);

}

else if (typeOfColor.equals("Foreground"))

{

component.setForeground(color);

}

if (component instanceof Container)

{

for (Component child : ((Container) component).getComponents())

{

changeColor(typeOfColor, child, color);

}

}

}

public static void main(String[] args)

{

JPanel panel = new JPanel();

JButton cancelButton = new JButton("Cancel");

panel.add(cancelButton);

changeColor("Background", panel, new Color(0, 255, 0));

JFrame frame = new JFrame("Frame");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setContentPane(panel);

frame.setVisible(true);

frame.pack();

}

}

However, no matter what is the color I choose, the buttons still display the background color as grey. How do I change the background color properly? I have looked around and most answers mention the setBackground method, but that does not work for me.

Thanks in advance!

解决方案

Nicholas Smith solved my issue.

In the comments, he mentioned "It could be the background color for a JButton in your specific LookAndFeel can't be overridden."

I was setting the look and feel in my code and once I removed that part of the code, my buttons' background color was changed successfully.

Thanks to you!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值