标签:
import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; import javax.swing.*; public class Test_17_4 extends JFrame{ private JLabel jl1 = new JLabel("Filename"); private JTextField jt1 = new JTextField("d:\\a.txt",10); private JButton jb1 = new JButton("View"); private JPanel jholdPanel = new JPanel(); private JP jp1 = new JP(); private String s; public Test_17_4(){ add(jp1); } public static void main(String[] args) { // TODO Auto-generated method stub Test_17_4 frame = new Test_17_4(); frame.setTitle("Test_17_4"); frame.setSize(400,500); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } class JP extends JPanel{ private JTextArea jt = new JTextArea(); private File file; private Scanner input; public JP(){ //set textarea jt.setLineWrap(true); jt.setWrapStyleWord(false); jt.setEditable(false); JScrollPane scro = new JScrollPane(jt); //create jscrollpanel to hole the textarea JScrollPane scrollPane = new JScrollPane(jt); jholdPanel.setLayout(new FlowLayout(FlowLayout.LEFT)); jholdPanel.add(jl1); jholdPanel.add(jt1); jholdPanel.add(jb1); jb1.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub s = jt1.getText(); try { jp1.setText(s); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); setLayout(new BorderLayout(5,5)); add(scrollPane,BorderLayout.CENTER); add(jholdPanel,BorderLayout.SOUTH); } public void setText(String s) throws FileNotFoundException{ file = new File(s); if(file.canRead() && file.exists()) { input = new Scanner(file); while(input.hasNext()) { jt.append(input.nextLine()); jt.append("\n"); } } else System.out.println("does not exists!"); input.close(); } } }
效果图:
标签:
原文地址:http://www.cnblogs.com/wanjiang/p/5751334.html