简体   繁体   中英

How do I split each piece of data in a text file and place them back in their respective text fields on a Java GUI form?

So the user enters data into text fields on a form and then saves everything on a single line in a text file. Eg

Pencils, 100, 2, 600.00

Next, the user wants to load what was stored in this text file back into the form (in their corresponding fields how they were entered at first). I am not sure how to do this exactly but I have some code to start out with.

public void loadRecord()
 {
    try
    {
        FileReader fr = new FileReader(myFile);
        BufferedReader br = new BufferedReader(fr);  
        ArrayList<String> records = new ArrayList<String>();

        String line;
        while((line = br.readLine()) != null)
        {
           records.add(line);
        }

        //Goes through each line in arraylist and removes empty lines
        for(int j = 0; j < records.size(); j++)
        {
           if(records.get(j).trim().length() == 0)
           {
             records.remove(j);
           }
        }

        //Splits each record after a comma and stores each piece in separate indexes
        for(int i = 0; i < records.size(); i++)
        {
           String[] array = records.get(i).split(",");
           String name = array[0].trim();
           String number = array[1].trim();
           String cost = array[2].trim();
           String amnt = array[3].trim();

           //Display each record piece in its designated textfield
           txtItem.setText(""); //temporary, this where item value would go for example
           txtNumber.setText(""); //temporary
           txtCost.setText(""); //temporary
           txtAmount.setText(""); //temporary
        }
     }
     catch (IOException ioe)
     {
        System.out.println("Something went wrong");//temporary
     } 
  }

I think I have an idea of what to do, but not sure how to exactly code it: 1. Create a array for each piece of data(that fit in their particular text fields) 2. Store the split values in the designated arrays 3. For setting back the text field values, loop through appropriate array and use array index value.

Any adjustments/improvements to my idea are welcome.

If you need multiple lines of data, consider using a JTextArea instead of a JTextField . You can then just append each line.

while ((line = br.readLine()) != null){
    textArea.append(line + "\n");
}

Or better yet , to have a more structured look, look into using a JTable . See How to use Tables


Here's an example you can run using a JTable

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;

public class TestTable {
    String[] colNames = {"Col 1", "Col 2", "Col 3", "Col 4", "Col 5"};
    JTextArea textArea = new JTextArea(7, 30);
    JButton button = new JButton("Show Table");
    JFrame frame = new JFrame("Test Table");

    public TestTable() {
        textArea.setText(getTextForTextArea());
        textArea.setEditable(false);

        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
                TableDialog dialog = new TableDialog(frame, true);
            }
        });


        frame.add(new JScrollPane(textArea));
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private String getTextForTextArea() {
        String line = "1, 2, 3, 4, 5";
        String textForArea = "";
        for (int i = 0; i < 10; i++) {
            textForArea += line + "\n";
        }
        return textForArea;
    }

    class TableDialog extends JDialog {
        public TableDialog(final JFrame frame, boolean modal) {
            super(frame, modal);

            add(new JScrollPane(createTable()));
            pack();
            setLocationRelativeTo(frame);
            setVisible(true);

        }

        private JTable createTable() {
            String text = textArea.getText();
            DefaultTableModel model = new DefaultTableModel(colNames, 0);
            Scanner scanner = new Scanner(text);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                String[] rowData = line.split("[\\s+,]+");
                model.addRow(rowData);
            }
            return new JTable(model);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run() {
                TestTable testTable = new TestTable();
            }
        });
    } 
}

Assuming that it's possible for the file to contain multiple lines you are going to need more fields

for(int i = 0; i < records.size(); i++)
{
   String[] array = records.get(i).split(",");
   String name = array[0].trim();
   String number = array[1].trim();
   String cost = array[2].trim();
   String amnt = array[3].trim();

   //Display each record piece in its designated textfield
   JTextField txtItem = new JTextField(name);
   JTextField txtNumber = new JTextField(number);
   JTextField txtCost = new JTextField(cost);
   JTextField txtAmount = new JTextField(amnt);

   add(txtItem);
   add(txtNumber);
   add(txtCost);
   add(txtAmount);
}

Now, this is probably going to make your UI a little ugly...it's also going to make retrieving and associating the data a night mare...

Instead, you could create a simple editor class...

public class ItemEditor extends JPanel {
   private JTextField txtItem = new JTextField();
   private JTextField txtNumber = new JTextField();
   private JTextField txtCost = new JTextField();
   private JTextField txtAmount = new JTextField();

   public ItemEditor(String name, String number, String cost, String amt) {
       txtItem.setText(name)
       txtNumber.setText(number)
       txtCost.setText(cost)
       txtAmount.setText(amt)
       add(txtItem);
       add(txtNumber);
       add(txtCost);
       add(txtAmount);
   }

   // Getters to get the value of each text field...
}

Then you could use something like a List to maintain each instance of editor, making it easier to get all the information you need from them...

// Declared previously...
private List<ItemEditor> editors;
//...
editors = new ArrayList<>(records.size());
for(int i = 0; i < records.size(); i++)
{
   String[] array = records.get(i).split(",");
   String name = array[0].trim();
   String number = array[1].trim();
   String cost = array[2].trim();
   String amnt = array[3].trim();

   ItemEditor editor = new ItemEditor(name, number, cost, amnt);
   editors.add(editor);
   add(editor);

}

Now with some playing around with layouts like GridBagLayout or GridLayout you should be able to get something that works...

or you could just use a JTable , which designed for just this task

Try changing your code as in::

txtItem.setText(name);
txtNumber.setText(number);
txtCost.setText(cost);
txtAmount.setText(amnt);

As you are setting the text boxes as null by setText(""); you need to provide the variable to be set in the text boxes as in setText(name);

and for debugging purpose you can system output to seee what values your code fetched as in::

System.out.println("Name =" + name);
System.out.println("Quantity = " + number);
System.out.println("Cost = " + cost);
System.out.println("Amount = " + amnt);

Hmm I hope I understood the question right but basically, pretend I have those 4 fields: Name, number, Cost, Amount, you want it to save into a text file somewhere locally so when you open it, they show back up in the textfields?

Why arent you actually setting the name in the code? Like txtItem.setText(""); and so on?

Assuming you will always know the order in which values are saved in a file, you can load the values into string variables then use JTextField.setText('put string variable here').

Since you are storing all your values on one line, you will only be able to read one line (assuming you don't have multiple lines saved). You will then need to split up this one large string containing all the values you need by ", ".

Edit You need to change this

String line;
while((line = br.readLine()) != null){
   records.add(line);
}

to this

String line = br.readLine();
String[] output = line.split(", ");

then for each textfield

JTextField.setText(output[i]) //where output[i] is the proper string for the the text field

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM