【问题标题】:Set user defined color of JButton设置 JButton 的用户定义颜色
【发布时间】:2014-06-23 19:45:19
【问题描述】:

目前我在做:

private static JButton button;
button = new JButton();
button.setBackground(Color.RED);

这让我的按钮变成了红色。

我希望用户设置其颜色,并且用户输入的颜色存储在String color = "blue" 中。我想要button.setBackground(color); 之类的东西,这样它就可以在blue 中给我button

我该怎么做?

【问题讨论】:

    标签: java swing colors jpanel jbutton


    【解决方案1】:

    问题归结为:如何从字符串中获取 java.util.Color。使用反射直接从 Color 类中执行此操作有很多奇特的方法,但最好创建一个简单的 Map,例如 HashMap<String, Color>,以便您可以将您的字符串与相应的颜色相关联。那么当你在ActionListener中获取用户的String时,你可以通过Map获取对应的Color,然后在你的JButton上调用setBackground(...)时使用Color。

    【讨论】:

      【解决方案2】:

      使用Color 类将字符串转换为颜色。您可以使用它的方法将字符串表示形式转换为颜色,也可以使用反射来查找保留名称。您还可以考虑 Swing 颜色选择器支持。如果您想处理一个相当随机的颜色名称列表,您必须按照 Hovercraft 的回答自己处理。

      【讨论】:

      • 你是在推荐他使用反射?
      猜你喜欢
      • 2011-12-13
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 2017-04-05
      • 2015-02-22
      • 2013-08-12
      相关资源
      最近更新 更多