Search code examples
javaswingcomponents

Java set/get all component's text in a JFrame


I'm trying to access all component's text in a JFrame, but with the method I found I cant do it.

    for(Component c : this.getComponents()) {
        c.setText(TRNASLATE(c.getText()));
        // does not work: no set and getText methods
    }

Is there any way to get or set a component's text?

Before you ask: i'm trying to translate elements on a JFrame without listing its components manually and setting their texts (it would take a long time to list them one-by-one)

Sorry for my english.


Solution

  • You could use instanceof to check if the component is a certain type, the cast that type to it. Most components have a getText() method.

    Example:

    for(Component c : this.getComponents()) {
           if(c instanceof JLabel){
               JLabel label = (JLabel) c;
               String text = label.getText();
           }
    }
    

    Repeat instanceof with as many Component types as necessary.