Search code examples
javaswinguser-interfacejtextfield

Taking values from JTextField created during runtime


I set up a small program that can create rows and columns at run time, its for a math class implementing sets, I already got the program to create the rows and columns but what I wanna do next is be able to get the values inside and then load another form of the same structure and get that forms values then add them and show them on a final form. Fairly new to the whole java thing, so if anyone could help it'd mean the world. Here's what I have so far..

import java.awt.*;
import java.awt.event.ActionEvent;   
import javax.swing.*;

public class Matrice extends JFrame {

protected static final int PREF_W = 200;
protected static final int PREF_H = 200;
JPanel mainPanel = new JPanel() {
  @Override
  public Dimension getPreferredSize() {
     return new Dimension(PREF_W, PREF_H);
  }
 };

 public JComponent getMainComponent() {
  return mainPanel;
   }

public Matrice(){
int rows, columns, end;

String RI, CI;

RI = JOptionPane.showInputDialog(null, "How many rows: ");
rows = Integer.parseInt(RI);
CI = JOptionPane.showInputDialog(null, "How many columns: ");
columns = Integer.parseInt(CI);
end = rows * columns;

JPanel holder = new JPanel(new GridLayout(rows, columns));
    holder.setVisible(true);
for(int i = 0; i < end; i ++){
holder.add(new JTextField("output"));
}
JPanel set = new JPanel(new GridLayout(1, 0));
JTextField r = new JTextField("rows");
JTextField c = new JTextField("columns");
set.add(r);
set.add(c);
set.add(new JButton("Set"));
mainPanel.add(set, BorderLayout.SOUTH);
mainPanel.add(holder, BorderLayout.NORTH);
}

 private static void createAndShowGui() {
   Matrice test = new Matrice();
   JFrame frame = new JFrame("Matrice");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(test.getMainComponent());
   frame.pack();
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
    }

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
     public void run() {
        createAndShowGui();
     }
    });
}

    }

never mind the buttons and the pre-set TextField


Solution

  • Simple answer to your question is that you need to define a array of TextField after getting the size:

    TextField[][] inputFields = new TextField[rows][columns];

    now add the TextFields

    getContentPane().setLayout(new GridLayout(rows, columns));
    for(int i = 0; i < rows; i++){
        for(int j = 0; j < columns; j++){
            inputFields[i][j] = new TextField("output");
            holder.add(inputFields[i][j]);
        }
    }
    

    There might be syntax errors above as I am directly typing it here.