如何在Java中传递颜色变量?

Joe*_*uck 2 java swing actionlistener

我有一个非常基本的java Swing窗口.我有一个内部类ActionAndMouseListener,它在JFrame结构中监听鼠标点击等,它有一个大面板,根据按下的三个可用按钮中的哪一个(红色,蓝色和黄色)改变颜色.这些按钮是空白面板,只包含标签,这些标签读取它们所代表的颜色的名称.我想在内部类中使用此方法来监听鼠标单击并在按下按钮时更改面板的颜色.我正在尝试创建一个适用于所有三个按钮的方法.到目前为止我有这个:

public void actionPerformed(ActionEvent event)
        {
            Object obj = event.getSource();
            JButton myButt = null;
            String buttonText = "";

            if (obj instanceof JButton)
            {
                myButt = (JButton)obj;
            }

            if (myButt != null)
            {
                buttonText = myButt.getText();
            }

            panel.setBackground(Color.(buttonText));
Run Code Online (Sandbox Code Playgroud)

我知道将buttonText作为Color变量传递不会像目前那样工作.为了使这项工作,我需要改变什么?有没有更好的方法来解决这个问题?

Chr*_*örz 8

你可以创建一个switch-case来检查按钮文本并创建一个颜色,因为:

Color color = null;
switch (buttonText) {
case "red":
    color = Color.red;
    break;
case "blue":
    color = Color.blue; 
    break;
case "yellow":
    color = Color.yellow; 
    break;
default:
    break;
}

panel.setBackground(color);
Run Code Online (Sandbox Code Playgroud)


cam*_*ckr 5

创建按钮时,您可以执行以下操作:

JButton red = new JButton("Red");
red.putClientProperty("color", Color.RED);
Run Code Online (Sandbox Code Playgroud)

然后在ActonListener你可以这样做:

JButton button = (JButton)e.getSource();
Color color = (Color)button.getClientProperty("color");
panel.setBackground( color );
Run Code Online (Sandbox Code Playgroud)

或者另一种方法是为您的类创建一个实例变量以包含颜色映射:

Map<Component, Color> componentColors = new HashMap<Component, Color>();
Run Code Online (Sandbox Code Playgroud)

然后你创建按钮,如:

JButton red = new JButton("Red");
componentColors.put(red, Color.RED);
Run Code Online (Sandbox Code Playgroud)

然后在 ActionListener 中:

JButton button = (JButton)e.getSource();
Color color = componentColors.get(button);
panel.setBackground( color );
Run Code Online (Sandbox Code Playgroud)