How to import a Text file content to a JTextArea in a Java application?

后端 未结 5 2059
夕颜
夕颜 2020-12-18 16:19

how to import a Text file content to a JTextArea in a Java application using JFileChooser?

5条回答
  •  不知归路
    2020-12-18 16:59

    Document Viewer

    import java.awt.BorderLayout;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.File;
    
    class DocumentViewer {
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    final JFrame f = new JFrame("Document Viewer");
                    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                    final JFileChooser fileChooser = new JFileChooser();
    
                    JPanel gui = new JPanel(new BorderLayout());
    
                    final JEditorPane document = new JEditorPane();
                    gui.add(new JScrollPane(document), BorderLayout.CENTER);
    
                    JButton open = new JButton("Open");
                    open.addActionListener( new ActionListener() {
                        public void actionPerformed(ActionEvent ae) {
                            int result = fileChooser.showOpenDialog(f);
                            if (result==JFileChooser.APPROVE_OPTION) {
                                File file = fileChooser.getSelectedFile();
                                try {
                                    document.setPage(file.toURI().toURL());
                                } catch(Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    gui.add(open, BorderLayout.NORTH);
    
                    f.setContentPane(gui);
                    f.pack();
                    f.setSize(400,300);
                    f.setLocationByPlatform(true);
    
                    f.setVisible(true);
                }
            });
        }
    }
    

提交回复
热议问题