如何查看是否选择了JColorChooser中的按钮,以及如何将其分配给其他窗口中的文本?(Java)
我有一个java程序,我想创建一个颜色选择器,当选中它时,它会保存该颜色并将其设置为JLabel、按钮、背景等。我如何获得它?下面是代码如何查看是否选择了JColorChooser中的按钮,以及如何将其分配给其他窗口中的文本?(Java),java,swing,actionlistener,jcolorchooser,Java,Swing,Actionlistener,Jcolorchooser,我有一个java程序,我想创建一个颜色选择器,当选中它时,它会保存该颜色并将其设置为JLabel、按钮、背景等。我如何获得它?下面是代码 public class ColorChooser extends JFrame { private JLabel sampleText = new JLabel("Label"); private JButton chooseButton = new JButton("Choose Color"); public static vo
public class ColorChooser extends JFrame {
private JLabel sampleText = new JLabel("Label");
private JButton chooseButton = new JButton("Choose Color");
public static void main(String[] args) {
new ColorChooser();
}
public ColorChooser() {
this.setSize(300, 100);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
sampleText.setBackground(null);
panel1.add(sampleText);
chooseButton.addActionListener(new ButtonListener());
panel1.add(chooseButton);
this.add(panel1);
this.setVisible(true);
}
private class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(//INSERT CODE HERE){
//Set the color
}
}
}
我需要输入什么来替换//在这里插入代码,以便它注册它,以及我将如何访问该代码并替换//设置颜色?首先看一看,其中有许多示例
首先,您需要将选择器预设为用户
Color color = JColorChooser.showDialog(this, "Choose", null);
接下来,您需要测试生成的color
是否为null
(null
表示用户出于某种原因取消了对话框)
最后,应用更改
sampleText.setForeground(color);
chooseButton.setBackground(color); // This might not do what you think it does
存储结果并提供某种getter。你可能还想看看
sampleText.setForeground(color);
chooseButton.setBackground(color); // This might not do what you think it does