日期:2014-05-19 浏览次数:21398 次
public class LoadTxt extends JFrame {
private static final String FILE_NAME = "C:\\Hello.java"; // 文件名,可修改
JButton btnLoad;
JTextArea txtArea;
public LoadTxt() {
this.setTitle("Text File Loader");
// 按钮,放在JFrame下方(南部区域)
btnLoad = new JButton("Click Here to Load File");
btnLoad.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(e.getActionCommand());
loadFile(FILE_NAME);
}
});
this.add(btnLoad, BorderLayout.SOUTH);
// 文本区,放在JFrame中部区域
txtArea = new JTextArea();
this.add(txtArea, BorderLayout.CENTER);
}
private void loadFile(String filename) {
Scanner sc = null;
try {
sc = new Scanner(new File(filename));
txtArea.setText(""); // 清空
while (sc.hasNextLine()) {
txtArea.append(sc.nextLine());
txtArea.append("\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (sc != null)
sc.close();
}
}
public static void main(String[] args) {
LoadTxt wnd = new LoadTxt();
wnd.setSize(600, 500);
wnd.setVisible(true);
}
}
------解决方案--------------------
示例参见 %JAVA_HOME%\demo\jfc\Notepad\Notepad.jar
代码参见 %JAVA_HOME%\demo\jfc\Notepad\src