M.Meuris
M.Meuris

Reputation: 41

Getting the text property from an object in java

I'm working on a project in java where I have a Vector which contains objects which contains JTextFields, CheckBoxes or blobs. Now i need to be able to get the text property from such a textfield.

I have this code:

for(int i = 0; i < gridValues.size(); i++) {
        Object value = gridValues.elementAt(i);
        if (value instanceof JTextField)
        {

        }
} 

I'm not sure how to get the text from the value Object. When i go through the list the first itemis of type JTextField so it comes in the if statement, but now I should get the text property from tis object but I have no idea how. The gridValues is the Vector with the possible textfields, checkboxes and blobs.

Upvotes: 2

Views: 1712

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You would get text from value by first casting it to a JTextField and then calling getText() on it:

// after checking that value in fact refers to a JTextField
String text = ((JTextField)value).getText();

e.g.,

if (value instanceof JTextField) {
    String text = ((JTextField)value).getText();
    // here use text for whatever it's needed for
}

But you should consider changing your program design, since it's use of mixed types in collections makes for a very brittle program, in other words, a program that is likely to have bugs any time a minor change is made.

Upvotes: 0

manub
manub

Reputation: 4100

As per the javadoc, it's possible to get the text of a JTextComponent by calling the getText() method.

Upvotes: 2

Related Questions