简体   繁体   English

Java-JFrame保存多行

[英]Java - JFrame saving multiple lines

I've been banging my head against the wall last couple of hours trying to get my program to work, but to no success. 最近几个小时,我一直在努力地使自己的程序正常运行,但是没有成功。

I'm working on a simple JFrame based program that should open the window, let me input the variables and then if I press Save, save them to selected .csv file. 我正在开发一个简单的基于JFrame的程序,该程序应打开窗口,让我输入变量,然后按“保存”,将它们保存到选定的.csv文件中。

The problem however arises when I try to save 2 or more sets of variables, the first one always gets overwritten and only new one is there. 但是,当我尝试保存2组或更多组变量时,就会出现问题,第一个变量总是被覆盖,而只有新的变量在那里。

For example instead of: 例如,代替:

Mark, 100, 2, John, 50, 1 马克,100、2,约翰,50、1

In the file I only find 在文件中我只能找到

John 50, 1 约翰50,1

I'm guessing it has to do with new bufferedwriter being created every time I click 'Save' button but I have no idea how to get around doing that, I tried multiple positions of placing it but it never works because I get error if it's outside the Action method. 我猜想这与每次单击“保存”按钮时都会创建新的bufferedwriter有关,但我不知道该如何解决,我尝试过多次放置它,但是它永远无法正常工作,因为如果出现错误在Action方法之外。

Here's the code: 这是代码:

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

Each time you click save , the file and it's contents are been overwritten. 每次单击save ,文件及其内容都会被覆盖。 You need to tell the FileWriter that you wish to append to the end of the file, for example... 您需要告诉FileWriter您希望附加到文件末尾,例如...

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

See FileWriter(File, boolean) for more details 有关更多详细信息FileWriter(File, boolean)请参见FileWriter(File, boolean)

BufferedWriter also has a newLine method, which can write a new line to the file... BufferedWriter还有一个newLine方法,可以将新行写入文件...

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

You're also not managing your resources very well. 您也不能很好地管理资源。 If you open a resource, you should make every attempt to close it, otherwise you could end up with leaking resources and other strange problems 如果打开资源,则应尽一切努力关闭它,否则可能会导致资源泄漏和其他奇怪的问题

Luckily in Java 7+, it's very easy to manage these types of resources 幸运的是,在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");
     }       

See The try-with-resources Statement for more details 有关更多详细信息,请参见try-with-resources语句

您可以在启动时清除/删除文件并附加到文件中,如下所示: 如何在Java中将文本附加到现有文件中

i will suggest you one other writer(i have worked on this): 我会建议你另一位作家(我已经为此工作):

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

if you want to leave some space or write something use: writer.printf("."); 如果您想留一些空间或写点东西,请使用: writer.printf(“。”);

if you want to leave a line use writer.println(); 如果要离开一行,请使用writer.println();。

Of course it has and other fuctions to use with this writer.. 当然,与该作者一起使用还有其他功能。

Let me know if it does your job..... 让我知道它是否能完成您的工作.....

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

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