日期:2014-05-20 浏览次数:20827 次
//目前实现了可以将文本内容读入到文本区并显示的功能 //问题一:在运行程序时,会有异常信息一闪而过. package Notepad_new; import javax.swing.*; import java.awt.*; import java.awt.Event.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.*; public class NotePad{ public static void main(String args[]){ try{ JFrame frame = new NoteFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }catch(Exception e){ System.out.println(e.toString()); } } } class NoteFrame extends JFrame{ public NoteFrame(){ setSize(400,600); Container c = getContentPane(); TextPanel p = new TextPanel(); area = p.area; JScrollPane scroll = new JScrollPane(area); p.add(scroll); add(p); JMenuBar menubar = new JMenuBar(); this.setJMenuBar(menubar); JMenu fileMenu = new JMenu("文件"); JMenuItem openItem = new JMenuItem("打开"); openItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.showOpenDialog(NoteFrame.this); fileName = chooser.getSelectedFile().getPath(); try{ File f = new File(fileName); BufferedInputStream in = new BufferedInputStream(new FileInputStream(f)); int n = in.available(); byte[] b = new byte[n]; in.read(b,0,n); fileText = new String(b); area.setText(fileText); }catch(IOException e1){ System.out.println(e.toString()); } } }); fileMenu.add(openItem); JMenuItem exitItem = new JMenuItem("退出"); exitItem.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ System.exit(0); } }); fileMenu.add(exitItem); menubar.add(fileMenu); pack(); area.setText(fileText); } public static String fileText,fileName; public static JTextArea area; } class TextPanel extends JPanel{ public TextPanel(){ setSize(400,400); area = new JTextArea(20,20); BorderLayout layout = new BorderLayout(); this.setLayout(layout); add(area,layout.CENTER); } public static JTextArea area; }