现在的位置: 首页 > 综合 > 正文

textarea写入内容,复制到指定的文本文档。

2014年09月05日 ⁄ 综合 ⁄ 共 1550字 ⁄ 字号 评论关闭

创建一个TextArea,TextFeild和button。

在TextArea里面写入要复制的内容,在TextFeild里面写入要目标文本文档,button用来复制TextArea里面的内容到TextFeild里面。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.FileWriter;
import java.io.IOException;

public class textarea extends JFrame implements ActionListener{
    JPanel contentPane;
    JTextArea textArea;
    JTextField tf;
    JButton button1 ;
   
    public textarea(){
        setTitle("text");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100,100,250,250);
        contentPane =new JPanel();
        contentPane.setLayout(new BorderLayout(0,0));
        setContentPane(contentPane);
        JPanel panel1 = new JPanel();
        FlowLayout f1=(FlowLayout)panel1.getLayout();
        f1.setAlignment(FlowLayout.LEFT);
        textArea=new JTextArea();
        contentPane.add(panel1,BorderLayout.NORTH);
        JScrollPane sp=new JScrollPane(textArea);
        contentPane.add(sp,BorderLayout.CENTER);
        JPanel Panel2=new JPanel();
        button1 =new JButton("copy");
        tf = new JTextField(20);
        Panel2.add(tf);
        Panel2.add(button1);
        contentPane.add(Panel2,BorderLayout.SOUTH);
        button1.addActionListener(this);            //给button1添加监听器。
    }
    @Override
    public void actionPerformed(ActionEvent e){
        if(e.getActionCommand().equals("copy")){
            String s1=textArea.getText();            //获取textarea里面的内容。
            String s2=tf.getText();                  //获取textfeild里面的路径。
            try {
                FileWriter fw=new FileWriter(s2);   //文件写入
                fw.write(s1);
                fw.flush();
            } catch (IOException ex) {
                System.out.println(ex);
            }      
        }
    }
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                try{
                textarea t=new textarea();
                t.setVisible(true);
            }
            catch(Exception ae){
            ae.printStackTrace();
        }
            }
        });
       
    }
}
疑问:
给button1添加监听器 
button1.addActionListener(this);
用netbeans编译的时候, 提示 构造函数泄露this.

【上篇】
【下篇】

抱歉!评论已关闭.