我想要一个程序来保存您在输入对话框中输入的内容(在您在第一个消息对话框上单击否之后),以便您下次运行该程序时使用。下次我运行程序并在选项对话框上单击“是”时,我试图让文本字段说出用户上次输入时输入的内容。底部的代码只是出于某种原因将文本字段设置为空白..
public static String fn;
public static String sn;
public static int n;
File f = new File("test.txt");
public void actionPerformed (ActionEvent e){
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == 1){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
writeToFile();
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
if (n == 0){
writeToFile();
String fullName = writeToFile();
text.setText("Welcome " + fullName + ".");
}
}
//text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
b.setEnabled(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
pnlButton.setBackground(Color.DARK_GRAY);
}
private String writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
String savedName = "";
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
if (n==0){
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
savedName = br.readLine();
}
if (n==1){
text.setText("Welcome " + fn + ".");
}
//text.setText("Welcome " + savedName + " " + sn + ".");
//System.out.println(savedName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
return savedName;
}