【问题标题】:Buffered writer is not writing text? [duplicate]缓冲作家不写文本? [复制]
【发布时间】:2015-11-20 23:19:20
【问题描述】:

我正在制作一个简单的程序,它接受用户名和密码并将其保存到文本文件中。但是,在我检查硬盘驱动器之前,该程序运行良好。文本文件在那里,但没有文本。

public class Main {


public static void main(String args[]){
    events jack = new events();


    events gui = new events();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setTitle("WCPSS");
    gui.setSize(1100,400);
    gui.setVisible(true);
    gui.setLocationRelativeTo(null);

    BufferedWriter bw = null;
      try {

         //Specify the file name and path here
     File file = new File("E:/myfile.txt");

     /* This logic will make sure that the file 
      * gets created if it is not present at the
      * specified location*/
      if (!file.exists()) {
         file.createNewFile();
      }

      FileWriter fw = new FileWriter(file);
      bw = new BufferedWriter(fw);
      bw.write(jack.username);
          System.out.println("File written Successfully");

      } catch (IOException ioe) {
       ioe.printStackTrace();
    }
    finally
    {  
       try{
          if(bw!=null)
         bw.close();
       }catch(Exception ex){
           System.out.println("Error in closing the BufferedWriter"+ex);
        }
    }
}

}

public class events extends JFrame {

public String username = ("");
public String password = ("");
private JLabel label;
private JButton button;
private JTextField userin = new JTextField(10);
private JTextField userpass = new JTextField(10);


public events() {
    setLayout(new FlowLayout());

    button = new JButton("Submit");
    button.setBounds(5, 435, 50, 123);
    add(button);
    label = new JLabel(
            "Please enter your username and password : ");
    add(label);
    add(userin);
    add(userpass);

    button.addActionListener((e) -> {
        sumbitAction();
    });

}

private void sumbitAction() {
    username = userin.getText();
    password = userpass.getText();
    System.out.println(username);
    System.out.println(password);
}

}

我知道这可能写得不好,但我是一个初学者,希望得到一些帮助。谢谢

【问题讨论】:

  • 好吧,你写jack.username,而jack.username是一个空字符串,所以这是意料之中的,不是吗?用户名只会在写入完成后很久,当用户决定按下按钮时才会变成别的东西。

标签: java jframe actionlistener buffered


【解决方案1】:

写入文件的部分应该可以工作。问题是它在JFrame 加载之后立即运行

您应该将代码移动到当您按下JButton 时执行的ActionListener 处理程序:

private void sumbitAction() {
    username = userin.getText();
    password = userpass.getText();
    System.out.println(username);
    System.out.println(password);

    // do the writing here
}

您还在内存中创建了两个JFrame 实例,并且只加载了一个。为什么?只需创建一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多