GGrela
GGrela

Reputation: 25

Read data from file into Textfields java

Hello i've got a problem
I would like to read data from text file, every single data is in diffrent line, it looks like this

599
1188
1189
998
1998
2598
2899
3998
998
628
1178
1198
399
385
294
1380

I've as much as lines is textfields
jTextField1, jTextField2...
I'd like to put into these datas... I literally dont know how to deal with it
jTextField1 should have value 599
jTextField2 shoulv have value 1188
No clue how to do it. Can u help me guys please :)

Upvotes: 0

Views: 57

Answers (1)

khachik
khachik

Reputation: 28703

You can read the file line-by-line using FileReader/BufferedReader or Scanner:

String filename = "path/to/the/file/with/numbers.txt";
try(BufferedReader reader = new BufferedReader(new FileReader(filename))) {
    String line;
    int currentIndex = 1;
    while((line = reader.readLine()) != null) {
        // see further on how to implement the below method
        setTextFieldValue(currentIndex, line.trim());
        currentIndex++
    }
}

To implement setTextFieldValue, you have a couple of options:

  1. write a switch case to map the index to the corresponding field
  2. make a map of index -> field, or an array (as suggested by @zlakad in the comments)
  3. Use reflection to get fields by their names

All of the above options have their pros and cons which depends on the context. Below I'll show how to implement it using reflection, because the other two options are quite straightforward:

void setTextFieldValue(int index, String value) {
    // assuming the fields belong to the same class as this method
    Class klass = this.getClass(); 
    try {
        Field field = klass.getField("jTextField" + index);
        JTextField text = (JTextField)field.get(this);
        text.setText(value);
    } catch (NoSuchFieldException | IllegalAccessException e) {
        // throw it further, or wrap it into appropriate exception type
        // or just and swallow it, based on your use-case.
        // You can throw a custom checked exception
        // and catch in the caller method to stop the processing 
        // once you encounter index that has no corresponding field
    }
}

Upvotes: 1

Related Questions