gpt4 book ai didi

java - 背景颜色不会应用于 JButton

转载 作者:行者123 更新时间:2023-11-29 07:37:23 24 4
gpt4 key购买 nike

我有一个带有 jcolorchooser 一些文本字段和一个按钮的简单程序。当我按下按钮时,会出现 jcolorchooser,然后我选择一种颜色。现在假设我想采用我选择的背景颜色并将其应用于我的按钮,如下所示:

public class Slide extends JFrame{

Color bgColor;
JButton colorButton=new JButton();
JColorChooser colorPicker=new JColorChooser();
public Slide(){
JPanel panel=new JPanel();
panel.setLayout(new MigLayout("", "[][][][][]", "[][][][][][]"));
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JColorChooser.showDialog(null, "title", null);
bgColor=colorPicker.getBackground();
colorButton.setBackground(bgColor);
}
});
colorButton.setText("Pick a color");
panel.add(colorButton, "cell 0 5");
this.setSize(400, 400);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String args[]){
new Slide();
}
}

问题是我的 bgcolor 不会应用到我的 colorButton。有什么想法吗?

最佳答案

用户从 JColorChooser 对话框中选择的颜色作为 showDialog() 方法的返回值返回给您。

要使用从对话框中选择的颜色更新 JButton,您应该将代码更改为:

colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
Color color = JColorChooser.showDialog(null, "title", null);

if (color != null) {
colorButton.setBackground(color);
}
}
});

请注意,如果用户取消,方法 showDialog() 将返回 null,这就是为什么我们需要在分配颜色之前检查它的值。

方法 getBackground()Component 类中的一个方法,所以前面的代码 bgColor=colorPicker.getBackground() 很简单返回 JColorChooser 对话框组件的实际颜色。

关于java - 背景颜色不会应用于 JButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33982245/

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