简体   繁体   English

如何在文本文件中拆分每个数据并将它们放回Java GUI表单上的各自文本字段中?

[英]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 铅笔,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. 我想我知道该怎么做,但不知道如何准确编码:1。为每个数据片段创建一个数组(适合其特定的文本字段)2。将分割值存储在指定的数组中3 。对于设置文本字段值,循环通过适当的数组并使用数组索引值。

Any adjustments/improvements to my idea are welcome. 欢迎对我的想法进行任何调整/改进。

If you need multiple lines of data, consider using a JTextArea instead of a JTextField . 如果需要多行数据,请考虑使用JTextArea而不是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 . 或者更好的是 ,要想拥有更加结构化的外观,请考虑使用JTable See How to use Tables 请参见如何使用表


Here's an example you can run using a JTable 这是一个可以使用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... 然后你可以使用类似List东西来维护编辑器的每个实例,从而更容易从中获取所需的所有信息......

// 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... 现在有些人在玩GridBagLayoutGridLayout这样的布局,你应该能够得到一些GridLayout东西......

or you could just use a JTable , which designed for just this task 或者您可以使用专为此任务设计的JTable

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(""); 当您通过setText("");将文本框设置为null时setText(""); you need to provide the variable to be set in the text boxes as in setText(name); 你需要在setText(name);提供要在文本框中设置的变量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? 嗯,我希望我理解这个问题,但基本上,假装我有4个字段:名称,数字,成本,金额,你希望它保存到本地某处的文本文件中,所以当你打开它时,它们会显示在文本字段中?

Why arent you actually setting the name in the code? 为什么你实际上没有在代码中设置名称? Like txtItem.setText(""); 像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'). 假设您始终知道文件中保存值的顺序,您可以将值加载到字符串变量中,然后使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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