我编写了一个代码,用于“将文本字段的内容写入文本文件”。它没有错误,但它没有在文本文件中写任何东西!任何人都可以帮助我,告诉我我的错误吗?或编辑代码并重新输入整个代码。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
jButton1.addActionListener(new ActionListener(){
public void actionPerformed(final ActionEvent e){
handleActionPerformed(e);
}
});
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
//do you really need to pass ActionEvent in this case?
protected void handleActionPerformed(ActionEvent e) {
BufferedWriter writer = null;
try
{
String text = jTextField1.getText(); //get the text from the text field
writer = new BufferedWriter(new FileWriter("D:\\Definition.txt"));
writer.write(text); //write it in the file
writer.flush(); //flush the write-buffer
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally { //always close the stream in finally block
try {
if(writer != null)
writer.close();
}
catch(IOException b) {
b.printStackTrace();
}
}
}
答案 0 :(得分:3)
handleActionPerformed(...)
什么也没做。
这应该工作我相信......
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(final ActionEvent e) {
handleActionPerformed(e);
}
}
//do you really need to pass ActionEvent in this case?
protected void handleActionPerformed(ActionEvent e) {
BufferedWriter writer = null;
try
{
String text = jTextField1.getText(); //get the text from the text field
writer = new BufferedWriter(new FileWriter("C:\\Definition.txt"));
writer.write(text); //write it in the file
writer.flush(); //flush the write-buffer
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
finally { //always close the stream in finally block
try {
if(writer != null)
writer.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}