我正在尝试为我的java编码实现GUI功能,这是我第一次尝试。但我尝试了一个"创建播放器功能"在我的代码但它不写入文件可以有人帮忙吗?谢谢
private class createListener implements ActionListener{
public void actionPerformed(ActionEvent event){
JFrame frame = new JFrame("Create Player");
JPanel panel = new JPanel();
JPanel mainpanel = new JPanel();
JButton create;
JLabel welcome = new JLabel("Create Player");
JLabel name = new JLabel("Enter Player Name");
nameP = new JTextField();
JLabel pass = new JLabel("Enter Player Password");
password = new JTextField();
JLabel chips = new JLabel("Enter Player Chips");
chipsP = new JTextField();
buttonCreate = new JButton("Create Player");
setSize(400,350);
setLocation(500,280);
panel.setLayout(new GridLayout(0,1,10,10));
panel.add(name);
panel.add(nameP);
panel.add(pass);
panel.add(password);
panel.add(chips);
panel.add(chipsP);
panel.add(buttonCreate);
mainpanel.add(panel);
getContentPane().removeAll();
getContentPane().add(mainpanel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
buttonCreate.addActionListener(new createListener());
}
}
private class playerListener implements ActionListener{
public void actionPerformed(ActionEvent event){
String username = nameP.getText();
String userpass = password.getText();
String hasheduserP = Utility.getHash(userpass);
String userchip = chipsP.getText();
String userContent = username + "|" + hasheduserP + "|" + userchip;
File file = new File("players.dat");
try{
//adding of user details
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("players.dat", true)));
out.println(userContent);
out.close();
JOptionPane.showMessageDialog(null,"User Created");
} catch (IOException ex){
System.out.println("Error Writing to File");
}
}
}
答案 0 :(得分:0)
代码中与文件相关的部分没有任何问题。
提示:改善它:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class SOPlayground {
public static void main(String[] args) throws Exception {
String userContent = "foo";
try {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("/tmp/players.dat", true)))) {
out.println(userContent);
}
} catch (IOException ex) {
System.err.println("Error Writing to File: " + ex.getMessage());
}
}
}
/tmp/players.dat
的内容现在是
foo