如何根据按钮文本访问JButton

时间:2012-08-21 05:14:42

标签: java swing awt jbutton gettext

我在GridLayout中安排了一组按钮。我想根据文本访问特定按钮。有没有办法根据文本检索按钮?

4 个答案:

答案 0 :(得分:5)

您必须遍历面板中的组件并查找它。类似的东西:

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);
}

答案 1 :(得分:2)

遍历面板中的组件,只需过滤结果。

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

答案 2 :(得分:1)

您可以为JButton对象创建JButton名称的地图

Map<String, JButton> mbutt = new HashMap<String, JButton>();

您可以通过迭代来访问String和JButton。

for(Map.Entry<String,JButton> map : mbutt.entrySet()){

       String k = map.key();  // Key 

       JButton bu = map.value();  // JButton


}

答案 3 :(得分:0)

public void actionPerformed(ActionEvent e) {
String name= e.getActionCommand();
}

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