0

I have jTextField named "startTextBox1"

And i use below methods can call it by name;

Creating Hashmap in class.

private HashMap componentMap;

Fill hashmap with components name.

private void createComponentMap() {
    componentMap = new HashMap<String,Component>();
    Component[] components = jDesktopPane1.getComponents();
    for (int i=0; i < components.length; i++) {
            componentMap.put(components[i].getName(), components[i]);
    }
}

For call components by their names.

public JComponent getComponentByName(String name) {
    if (componentMap.containsKey(name)) {
            return (JComponent) componentMap.get(name);
    }
    else return null;
}

When i call getComponentByName("startTextBox1").getName() it gives me startTextBox1 succesfully.

But i can't call getComponentByName("startTextBox1").getText() because mapped component is JComponent and getName() is JComponent method. But getText() is JTextComponent object.

How can i get text from my textfield in this scenario ?

martinez314
  • 12,162
  • 5
  • 36
  • 63
Black White
  • 700
  • 3
  • 11
  • 31

1 Answers1

1

How about this?

public String getTextByComponentName(String name) {
    if (componentMap.containsKey(name)) {
            JComponent comp = (JComponent) componentMap.get(name);
            if (comp instanceof JTextComponent) {
                  return ((JTextComponent)comp).getText();
            }
    }

    return null;
}
martinez314
  • 12,162
  • 5
  • 36
  • 63
  • Possible and probably solve the current issue. Any generic way for solve it? I mean not create method for every type. – Black White Aug 12 '14 at 14:11
  • i implement it to my code. But when i call this method i cant type .getText() it generate compile error. But first mentioned specific type calling method succesfully working fyi. – Black White Aug 12 '14 at 14:29