0

ユーザー名とパスワードを取得してテキスト ファイルに保存する簡単なプログラムを作成しています。ただし、ハードドライブをチェックするまで、プログラムは正常に動作します。テキストファイルはありますが、テキストはありません。

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

}

私はこれがおそらく不十分に書かれていることを知っていますが、私は初心者であり、いくつかの助けを求めています. ありがとうございました

4

1 に答える 1

2

ファイルへの書き込みの部分は機能するはずです。問題は、がロードされた直後に実行されることです。JFrame

ActionListenerを押したときに実行されるハンドラーにコードを移動する必要がありますJButton

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

    // do the writing here
}

JFrameまた、インメモリの 2 つのインスタンスを作成し、 1 つだけをロードしています。なんで?1つだけ作成してください。

于 2015-11-20T23:24:37.940 に答える