Search code examples
javaarraysjtextfieldshortest-path

Reading from multiple JTextFields into array


I'm working on shortest path alghoritm, and wanted to create a gui version for my program. This is my method creating fields to input distances between vertices. When all JTextFields are filled I want to convert all of it into two dimensional array and here is my problem. How to read all values from n amount of JTextFields if they're all created on the same variable which is tekst in my case.

void Wypelnij() {
int n = 1;
int x = 0;
for (int i = 1; i <= wierzcholki; i++) {

    if (x == 0) {
        mojPanel.add(new JLabel(""));
        for (int j = 1; j <= wierzcholki; j++) {
            if (n == wierzcholki) {
                mojPanel.add(new JLabel("" + j), "wrap");
                n = 1;
                x = 1;
            } else {
                mojPanel.add(new JLabel("" + j));
                n++;
            }
        }
    }
    mojPanel.add(new JLabel("" + i));
    for (int j = 1; j <= wierzcholki; j++) {
        JTextField tekst = new JTextField();
        tekst.setPreferredSize(new Dimension(20, 20));
        if (n == wierzcholki) {
            mojPanel.add(tekst, "wrap");
            n = 1;
        } else {
            mojPanel.add(tekst);
            n++;

        }
        if (i == j) {
            tekst.setText("0");
            tekst.setHorizontalAlignment(JTextField.CENTER);
            tekst.setEditable(false);
        }
    }
}

Solution

  • You can create a List<JTextField> and iterate over that list to get text from all the JTextFields.

    Other way is, you can use Components[] JPanel#getComponents() to get all components of panel(i.e. Container) and iterate over the components to read from the JTextFields. But in this case your panel may contain other components(better to use separate panel for JTextFields) and moreover you need to cast Component to JTextField. But, you can iterate over Components[] based on the indexes on which you have added JTextFields in your panel.