简体   繁体   English

设置背景色Java JButton

[英]Set background color Java JButton

I tried to modify the background color of my JButton (and the size) but it doesn't work (the foreground is by the way ok) 我试图修改我的JButton的背景颜色(及其大小),但是它不起作用(前景很好)

public class boutondesign extends JButton implements MouseListener {
private String name; 


public boutondesign(String nom){
        super(nom);
        this.name = nom; 
        this.setSize(100, 100); 
        this.addMouseListener(this); 
        this.setBackground(Color.BLACK);
        this.setForeground(Color.white);

thanks in advance for yours answers 预先感谢您的回答

following the first advice : 遵循第一个建议:

public boutondesign(String nom){
    super(nom);
    this.name = nom;  
    this.addMouseListener(this); 
    this.setForeground(Color.white);
    this.setBackground(Color.BLACK);
    this.setContentAreaFilled(false);
    this.setOpaque(false);
    this.setBorderPainted(false);
    this.setFocusPainted(false);

}

not working either 也不工作

Trying with overriding paintComponent : 尝试覆盖paintComponent:

public boutondesign(String nom){
    super(nom);
    this.name = nom;  
    this.addMouseListener(this); 
    this.setForeground(Color.white);
    this.setOpaque(false);
    this.setBorderPainted(false);
    this.setFocusPainted(false);

}
public void paintComponen(Graphics g){
    g.setColor(Color.BLACK);
}

not working either :( (I also tried g.setColor(getBackground().setColor(Color.Black)) 也不起作用:((我也尝试过g.setColor(getBackground()。setColor(Color.Black))

This will make a black button with white text 这将使一个带有白色文本的黑色按钮

this.setForeground(Color.WHITE);
this.setBackground(Color.BLACK);
this.setOpaque(true);
this.setBorderPainted(false);

But it is a very crude one, here it is in comparison with a basic JButton 但这是一个非常粗糙的版本,与基本的JButton相比

在此处输入图片说明

Following the comment of user3437460 , I looked the specifics of Mac and JButton, 按照user3437460的评论,我查看了Mac和JButton的细节,

there is the code working 有代码在工作

public boutondesign(String nom){
    super(nom);
    this.name = nom;  
    this.addMouseListener(this); 
    this.setForeground(Color.white);
    this.setBackground(Color.black);
    this.setOpaque(true);
    this.setBorderPainted(false);
    this.setFocusPainted(false);

}

It seems that on Mac, Opaque attribute needs to be true, without overriding paintComponents and FocusPainted on "False" 在Mac上,似乎Opaque属性必须为true,而不能覆盖paintComponents和FocusPainted为“ False”

Thanks All for your help 感谢你的帮助

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

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