2017-09-27 125 views
0

。我的尝试&是否捕获到事件处理程序方法中的正确位置,还是应该将它的一部分放在构造函数中?如果我在JTextArea中输入文本并单击“保存”按钮,则JTextArea文本应该写入/保存到.txt文件中,从而将JTextArea保存为带有按钮的.txt文件

这是我的代码:提前

package exercises; 

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.FileWriter; 
import java.io.IOException; 
import java.io.PrintWriter; 

import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JTextArea; 

public class SimpleNotePadApp extends JFrame implements ActionListener { 

JButton button1 = new JButton("Open"); 
JButton button2 = new JButton("Save"); 

public SimpleNotePadApp(String title) { 
    super(title);        
    setDefaultCloseOperation(EXIT_ON_CLOSE); 
    setSize(300, 350);       
    setLayout(null); 


    JTextArea newItemArea = new JTextArea(); 
    newItemArea.setLocation(3, 3); 
    newItemArea.setSize(297, 282); 
    getContentPane().add(newItemArea); 

    button1.setLocation(30,290); 
    button1.setSize(120, 25); 
    getContentPane().add(button1); 

    button2.setLocation(150,290); 
    button2.setSize(120, 25); 
    getContentPane().add(button2); 

} 

public static void main(String[] args) { 
    SimpleNotePadApp frame; 

    frame = new SimpleNotePadApp("Text File GUI");  
    frame.setVisible(true);        
} 

public void actionPerformed(ActionEvent e) { 

    if(e.getSource() == button1) 
    { 
     try { 
      PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")); 
      newItemArea.getText(); 
      newItemArea.write(out); 
      out.println(newItemArea); 
      out.flush(); 
      out.close(); 

     } catch (IOException e1) { 
      System.err.println("Error occurred"); 
      e1.printStackTrace(); 
     } 
    } 
} 
} 

感谢

+3

'是我试着抓在正确的地方......' - 为什么会在构造函数中?你是否从构造函数执行你的代码?另外,使用JTextArea.write(...)方法将数据保存到文件中。 – camickr

+0

Java GUI必须在不同的语言环境中使用不同的PLAF来处理不同的操作系统,屏幕大小,屏幕分辨率等。因此,它们不利于像素的完美布局。请使用布局管理器或[它们的组合](http://stackoverflow.com/a/5630271/418556)以及[white space]的布局填充和边框(http://stackoverflow.com/a/17874718/ 418556)。 –

回答

0

try ... catch是在正确的位置,但内容应该仅仅是:

 PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")); 
     newItemArea.write(out); 
     out.close(); 

考虑使用try-与资源,并且.close()变得不必要:

try (PrintWriter out = new PrintWriter(new FileWriter("TestFile.txt")) { 
     newItemArea.write(out); 
    } catch (IOException e1) { 
     System.err.println("Error occurred"); 
     e1.printStackTrace(); 
    } 

另外,你需要在施工期间给ActionListener连接到JButton

button2.addActionListener(this); 

thisSimpleNotePadApp实例,它实现ActionListener

最后,你会想:

if(e.getSource() == button2) 

...因为button2是你的“保存”按钮(不是button1

+0

感谢您的帮助!但是,由于某些原因,它仍然没有保存到文本文件中。这绝对是通过“尝试”部分,因为我已经通过打印到控制台上进行了测试...... – Caiz

+0

您确定它没有写入文本文件吗?为了进行调试,我建议对问题中的代码进行一些更改。例如。改变'PrintWriter out = new PrintWriter(new FileWriter(“TestFile.txt”));'to'File f = new File(“TestFile.txt”); PrintWriter out = new PrintWriter(new FileWriter(f));'然后稍后(保存之后),执行'Desktop.getDesktop()。open(f);' –