【问题标题】:How to access a JButton based on button text如何根据按钮文本访问 JButton
【发布时间】:2012-08-21 05:14:42
【问题描述】:

我有一组按 GridLayout 排列的按钮。我想根据其文本访问特定按钮。有没有办法根据其文本检索按钮?

【问题讨论】:

  • “我想根据其文本访问特定按钮。” 为什么?这有一种不好的代码味道。

标签: java swing awt jbutton gettext


【解决方案1】:

您必须遍历面板中的组件并查找它。比如:

for (Component comp : panel.getComponents())
    if (comp instanceof JButton && searchText.equals(((JButton) comp).getText()))
        return (JButton) comp;

但是,我建议您在创建和添加按钮时填写 Map<String, JButton> buttonMap。然后,您只需执行 buttonMap.get(searchText) 即可获得您的按钮:

JPanel panel = new JPanel(new GridLayout(3, 3));
for (int i = 1; i <= 9; i++) {
    JButton button = new JButton("Button " + i);
    panel.add(button);

    // save it to a map for easy retrieval
    buttonMap.put(button.getText(), button);
}

【讨论】:

  • hmm ... 看不出保留地图有什么好处。相反:它需要额外的努力才能与真实的 ui 保持同步。走真实的东西就好了,其他一切都不必要的混乱。
【解决方案2】:

遍历面板中的组件并简单地过滤结果。

for (Component component : getComponents()) {
    if (component instanceof JButton &&
       ((JButton) component).getText().equals(searchText)) {
        return component;
    }
}

【讨论】:

    【解决方案3】:

    您可以创建 JButton 名称到 JButton 对象的映射

    Map&lt;String, JButton&gt; mbutt = new HashMap&lt;String, JButton&gt;();

    您可以像这样通过迭代访问 String 和 JButton。

    for(Map.Entry<String,JButton> map : mbutt.entrySet()){
    
           String k = map.key();  // Key 
    
           JButton bu = map.value();  // JButton
    
    
    }
    

    【讨论】:

      【解决方案4】:
      public void actionPerformed(ActionEvent e) {
      String name= e.getActionCommand();
      }
      

      将 actionListener 添加到所有按钮后。 上面代码中的名称字符串获取写在文本上的文本字符串。 之后,您可以根据其文本处理按钮。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-20
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多