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



因此,用户将数据输入表单上的文本字段中,然后将所有内容保存在文本文件中的一行中。

例如铅笔, 100, 2, 600.00

接下来,用户希望将存储在此文本文件中的内容加载回表单中(在其相应的字段中最初是如何输入的)。我不确定如何做到这一点,但我有一些代码要开始。

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
} 
}

我想我知道该怎么做,但不确定如何准确编码: 1.为每条数据创建一个数组(适合其特定的文本字段) 2. 将拆分值存储在指定的数组中 3.要设置文本字段值,请遍历适当的数组并使用数组索引值。

欢迎对我的想法进行任何调整/改进。

假设文件可能包含多行,您将需要更多字段

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);
}

现在,这可能会使您的UI有点丑陋...它还将使检索和关联数据成为一场噩梦......

相反,您可以创建一个简单的编辑器类...

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...
}

然后,您可以使用类似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);
}

现在,随着一些人使用GridBagLayoutGridLayout等布局,您应该能够获得有效的东西......

或者你可以只使用一个JTable,它专为这个任务而设计

如果需要多行数据,请考虑使用JTextArea而不是JTextField。然后,您可以只附加每一行。

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

或者更好的是,要获得更有条理的外观,请考虑使用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();
}
});
} 
}

嗯,我希望我理解正确了这个问题,但基本上,假装我有这 4 个字段:名称、数字、成本、金额,您希望它保存到本地某处的文本文件中,以便当您打开它时,它们会重新显示在文本字段中?

为什么不在代码中实际设置名称?喜欢 txtItem.setText(");等等?

尝试更改代码,如下所示:

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

当您将文本框设置为 null 时setText("");您需要在文本框中提供要设置的变量,如setText(name);

出于调试目的,您可以系统输出以查看您的代码获取的值如下:

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

假设您始终知道值在文件中的保存顺序,则可以将值加载到字符串变量中,然后使用 JTextField.setText('put string variable here')。

由于将所有值存储在一行中,因此您只能读取一行(假设您没有保存多行)。 然后,您需要通过", "拆分包含所需所有值的大字符串。

编辑 您需要更改此设置

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

对此

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

然后对于每个文本字段

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

最新更新