簡體   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?

因此,用戶將數據輸入到表單上的文本字段中,然后將所有內容保存在文本文件中的單行中。 例如

鉛筆,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 。對於設置文本字段值,循環通過適當的數組並使用數組索引值。

歡迎對我的想法進行任何調整/改進。

如果需要多行數據,請考慮使用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();
            }
        });
    } 
}

假設文件可能包含多行,則需要更多字段

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

現在,這可能會讓你的用戶界面變得有點難看......它也會讓你的數據在夜間檢索和關聯......

相反,你可以創建一個簡單的編輯器類......

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這樣的布局,你應該能夠得到一些GridLayout東西......

或者您可以使用專為此任務設計的JTable

嘗試更改您的代碼,如::

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

當您通過setText("");將文本框設置為null時setText(""); 你需要在setText(name);提供要在文本框中設置的變量setText(name);

為了調試目的,您可以通過系統輸出來查看代碼中獲取的值,如::

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

嗯,我希望我理解這個問題,但基本上,假裝我有4個字段:名稱,數字,成本,金額,你希望它保存到本地某處的文本文件中,所以當你打開它時,它們會顯示在文本字段中?

為什么你實際上沒有在代碼中設置名稱? 像txtItem.setText(“”); 等等?

假設您始終知道文件中保存值的順序,您可以將值加載到字符串變量中,然后使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM