Search code examples
javaclasscomponentsjtextfieldgettext

How can I use Methods of a class without knowing the type?


I have following problem: I have a JPanel named activeCenter in which I save different JPanels from time to time when using my program. In those JPanels are a bunch of JTextfields, JLabels and a JButton. Now I want to get the text of all the Textfields (amount is known). My problem is now: I use a for-loop to go through all the Components in the JPanel and check whether its a JTextfield or not. The problem here is, if it is a JTextField, how do I use the Method getText()? I only have the Component and dont know how to make use of the Methods from JTextField. Is there a way to fix this without having to save the JTextFields in an array? Here is the relevant code:

button.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    for(Component c: activeCenter.getComponents())
    {
      if(c.getClass() == JTextField.class)
      {
        //use the Method getText() on c
      }
    }
  }
});

Solution

  • You need to cast your c object like this:

    String text = null;
    if (c instanceof JTextField) {
        text = ((JTextField)c).getText();
    }
    

    Also note that you can use the instanceof keyword for your if condition.