gpt4 book ai didi

java - 如何设置JButton的默认背景颜色?

转载 作者:行者123 更新时间:2023-11-30 07:01:40 29 4
gpt4 key购买 nike

我在将 JButton 的默认颜色设置为黄色时遇到问题?

此外,一旦单击该按钮,它应该变成红色,如果它已经是红色,可以单击它以变回黄色。关于我应该做什么有什么想法吗?

private void goldSeat1ActionPerformed(java.awt.event.ActionEvent evt){                                          

// TODO add your handling code here:

goldSeat1.setBackground(Color.YELLOW);

}

private void goldSeat1MouseClicked(java.awt.event.MouseEvent evt) {

// TODO add your handling code here:

goldSeat1.setBackground(Color.red);

}

最佳答案

enter image description here

要设置 JButton 的背景颜色,可以使用 setBackground(Color)

如果您想切换按钮,则必须向按钮添加一个 ActionListener,这样当单击它时,它就会发生变化。您不必必须使用MouseListener

我在这里所做的是设置一个 boolean 值,每次单击按钮时该值都会自行翻转。 (点击后 TRUE 变为 FALSE,FALSE 变为 TRUE)。 XOR 已用于实现这一目标。

由于您想要比原始 JButton 更多的属性,因此您可以通过从 JButton 扩展它来自定义自己的属性。

这样做可以让您享受 JComponent 的好处,同时允许您添加自己的功能。

我的自定义按钮示例:

class ToggleButton extends JButton{

private Color onColor;
private Color offColor;
private boolean isOff;

public ToggleButton(String text){
super(text);
init();
updateButtonColor();
}

public void toggle(){
isOff ^= true;
updateButtonColor();
}

private void init(){
onColor = Color.YELLOW;
offColor = Color.RED;
isOff = true;
setFont(new Font("Arial", Font.PLAIN, 40));
}

private void updateButtonColor(){
if(isOff){
setBackground(offColor);
setText("OFF");
}
else{
setBackground(onColor);
setText("ON");
}
}
}

包含自定义按钮的 JPanel 示例:

class DrawingSpace extends JPanel{

private ToggleButton btn;

public DrawingSpace(){
setLayout(new BorderLayout());
setPreferredSize(new Dimension(200, 200));
btn = new ToggleButton("Toggle Button");
setComponents();
}

private void setComponents(){
add(btn);
btn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
btn.toggle(); //change button ON/OFF status every time it is clicked
}
});
}
}

驱动代码的运行器类:

class ButtonToggleRunner{
public static void main(String[] args){

SwingUtilities.invokeLater(new Runnable(){
@Override
public void run(){
JFrame f = new JFrame("Toggle Colors");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new DrawingSpace());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}

关于java - 如何设置JButton的默认背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40807415/

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