Question

I have jTextField named "p0_1000"

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 Component getComponentByName(String name) {
    if (componentMap.containsKey(name)) {
            return (Component) componentMap.get(name);
    }
    else return null;
}

If i use directly p0_1000.setToolTipText("trying"); succesfully appear tooltiptext when mouse on releated textfield.

But if i use getComponentByName("p0_1000").setToolTipText("trying"); setToolTipText not recognized.

getComponentByName("p0_1000") succesfully working i tested. Because if i type "." after method name, avaliable action list come and i can use them (example .setVisible(false) working succesfully)

Some add, set or get commands not in avaliable action list when i call componen by name.

Any advice, idea, comments are appreciated.

Regards.

---SOLVED---

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

Above changes solve my problem.

Was it helpful?

Solution 2

Your problem is that your method is declared to return Component type, and if you look in the API for this class, you'll see that it does not have a setToolTipText(...) method. This method begins in the JComponent class. One solution is to have the Map only collect JComponents and have the method declared to return this type. Incidentally, if you declare your Map with generic parameters, you won't have to do your cast.

i.e., rather than this declaration,

private HashMap componentMap;

use,

private HashMap<String, Component> componentMap;

or if again if this will work for you:

private HashMap<String, JComponent> componentMap;

OTHER TIPS

You probably should be using JComponent which is has setToolTipText. If that's not what you want, you can check if the java.awt.Component is a JComponent and cast:

if (components[i]) instanceof JComponent) {
   JComponent jc = (JComponent) components[i];
   // now you can use setToolTipText
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top