user2422104
user2422104

Reputation: 3

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

Upvotes: 0

Views: 67

Answers (3)

fge
fge

Reputation: 121710

If I were you I'd go with a redesign: create a class which wraps a JPanel and make it implement Iterable<JTextField>. Create two .addComponent() method: one to add a JTextField specifically, another to add a Component. Store the JTextField elements in a List.

The implementation of Iterable<JTextField> is then as simple as:

@Override
public Iterator<JTextField> iterator()
{
    return textFields.iterator();
}

and you can use a foreach loop:

for (final JTextField textField: activeCenter)
    // use textField.getText()

Upvotes: 1

Matthias Van Eeghem
Matthias Van Eeghem

Reputation: 329

You could cast it to a JTextField:

((JTextField) c).getText();

Upvotes: 0

Keppil
Keppil

Reputation: 46219

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.

Upvotes: 4

Related Questions