Java - JFrame保存多行

时间:2015-01-29 20:46:05

标签: java csv jframe save

过去几个小时我一直在撞墙,试图让我的计划工作,但没有成功。

我正在开发一个简单的基于JFrame的程序,它应该打开窗口,让我输入变量然后如果我按下Save,将它们保存到选定的.csv文件。

当我尝试保存2组或更多组变量时会出现问题,第一组变量总是被覆盖,只有新变量存在。

例如,而不是:

Mark,100,2, 约翰,50,1,

在文件中我只找到

John 50,1

我猜这与每次点击“保存”时创建的新缓冲区有关。按钮,但我不知道如何绕过这样做,我尝试了多个放置它的位置,但它永远不会起作用,因为如果它在Action方法之外我会收到错误。

以下是代码:

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

/**
 * Demonstrates etc
 */
public class Homework1 extends JFrame implements ActionListener {

   JTextField jtfName1;
   JTextField jtfName2;
   JTextField jtfName3;
   JTextField jtfName4;

   static File file = new File("121Lab1.csv"); 

   public Homework1() {
        // Set BorderLayout with horizontal gap 5 and vertical gap 10
      setLayout(new BorderLayout(10, 10));


        // Create a JPanel with FlowLayout for the South of the JFrame's BorderLayout

      JPanel jpSouth = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 3));

        // Create some buttons to place in the south area
      JButton jbCalc = new JButton("Calculate");
      JButton jbSave = new JButton("Save");
      JButton jbClear = new JButton("Clear");
      JButton jbExit = new JButton("Exit");

      jpSouth.add(jbCalc);
      jpSouth.add(jbSave);
      jpSouth.add(jbClear);
      jpSouth.add(jbExit);

      jbCalc.addActionListener(this);
      jbSave.addActionListener(this);
      jbClear.addActionListener(this);
      jbExit.addActionListener(this);


        // Place the south panel in the JFrame's south area
      add(jpSouth, BorderLayout.SOUTH);

        // Add textfields to the rest of the frame

      JPanel jpCenter = new JPanel(new GridLayout(0,2));

      jpCenter.add(new JLabel("Item name: ", SwingConstants.RIGHT));
      jtfName1 = new JTextField("", 10);
      jpCenter.add(jtfName1);
      jtfName1.addActionListener(this);

      jpCenter.add(new JLabel("Number of: ", SwingConstants.RIGHT));
      jtfName2 = new JTextField("", 10);
      jpCenter.add(jtfName2);
      jtfName2.addActionListener(this);

      jpCenter.add(new JLabel("Cost: ", SwingConstants.RIGHT));
      jtfName3 = new JTextField("", 10);
      jpCenter.add(jtfName3);
      jtfName3.addActionListener(this);

      jpCenter.add(new JLabel("Amount owed: ", SwingConstants.RIGHT));
      jtfName4 = new JTextField("", 10);
      jpCenter.add(jtfName4);
      jtfName4.addActionListener(this);

      add(jpCenter, BorderLayout.CENTER);

   }

   public void actionPerformed(ActionEvent ae) {
      String actionString = ae.getActionCommand(); // gets the string on the component
      Object actionObj = ae.getSource();


      if (actionString.equalsIgnoreCase("Calculate")) { // ae.getSource() == jbCancel
         System.out.println("You clicked Calculate");
         try {
            double value = Double.parseDouble(jtfName2.getText())*Double.parseDouble(jtfName3.getText());
            jtfName4.setText(String.format("%.2f", value));
         } 
         catch (NumberFormatException nfe) {
            jtfName4.setText("Not a number");
         }

      } 
      else if (actionString.equalsIgnoreCase("Save")) { 

         try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(file));
            writer.write(jtfName1.getText()+",");
            writer.write(jtfName2.getText()+",");
            writer.write(jtfName3.getText()+"\r\n");
            writer.flush();
            writer.close();
         } 
         catch(IOException e) {
            System.out.println("IO Error");
         }         
      } 
      else if (actionString.equalsIgnoreCase("Clear")) { 

         System.out.println("You clicked Clear");
         jtfName1.setText("");
         jtfName2.setText("");
         jtfName3.setText("");
         jtfName4.setText("");

      } 
      else if (actionString.equalsIgnoreCase("Exit")) { 


         setVisible(false);
         dispose();


      } 
      else {
         System.out.println("Unknown command: " + actionString);
         System.out.println("Unknown source:  " + actionObj);
      }
   } 




   public static void main(String[] args) throws IOException {

      Homework1 jfMain = new Homework1();
      jfMain.setTitle("Item Order Calculator");
      jfMain.setSize(450, 200);
      jfMain.setLocationRelativeTo(null);       // Center JFrame
      jfMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      jfMain.setVisible(true);


   } // end main
} // end class JPanelTester

3 个答案:

答案 0 :(得分:1)

每次点击save时,文件及其内容都会被覆盖。您需要告诉FileWriter您希望附加到文件的末尾,例如......

BufferedWriter writer = new BufferedWriter(new FileWriter(file), true);

有关详细信息,请参阅FileWriter(File, boolean)

BufferedWriter也有一个newLine方法,可以在文件中写一个新行......

writer.write(jtfName1.getText()+",");
writer.write(jtfName2.getText()+",");
writer.write(jtfName3.getText());
writer.newLine();

您还没有很好地管理资源。如果你打开一个资源,你应该尽一切努力关闭它,否则你最终可能会泄漏资源和其他奇怪的问题

幸运的是,在Java 7+中,管理这些类型的资源非常容易

    try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
        writer.write(jtfName1.getText()+",");
        writer.write(jtfName2.getText()+",");
        writer.write(jtfName3.getText());
        writer.newLine();
     } 
     catch(IOException e) {
        System.out.println("IO Error");
     }       

有关详细信息,请参阅The try-with-resources Statement

答案 1 :(得分:0)

您可以在启动时清除/删除文件并将其附加到文件中:How to append text to an existing file in Java

答案 2 :(得分:0)

我会建议你另一位作家(我已经为此工作过):

try{ 

 PrintWriter Writer = new PrintWriter(new File("path of file/file.(whatever)");

    //example
        writer.write(jtfName1.getText()+",");
        writer.printf("  "); //Leave some space
        writer.write(jtfName2.getText()+",");
        writer.printf("  "); //Leave some space
        writer.write(jtfName3.getText()+"\r\n");
        writer.printf("  "); //Leave some space

        writer.flush();
        writer.close();

} catch (FileNotFoundException e) { e.printStackTrace(); }

如果你想留一些空间或写一些东西使用: writer.printf(“。”);

如果你想留下一行,请使用 writer.println();

当然它和本作家一起使用的其他功能......

让我知道它是否能完成你的工作......