6/26/10

Copying selected text from one text area to another.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

  public class  TextExample extends JFrame {

    private JTextArea t1,  t2;
    private JButton copy;
    private Font font24 = new Font("Serif",
            Font.BOLD, 24);
    private Font font18 = new Font("Serif",
            Font.ITALIC, 18);

   public static void main(String args[]) {
        new TextExample();
    }

    public TextExample() {
        super("TextArea Demo");
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        String s = "This is a demo string to \n illustrate copying text \n from one TextArea to \n" +
                "another TextArea using an\n" +
                "external event\n";
        t1 = new JTextArea(s, 10, 20);
        c.add(new JScrollPane(t1));
        t1.setFont(font24);
        t1.append("Test Font Size 24");
        t1.setForeground(Color.red);
        t1.append("Test color red");
        t1.setFont(font18);
        t1.append("\nTest Font Size 18");
        t1.setForeground(Color.blue);
        t1.append("Test color blue");
        copy = new JButton("Copy >>>");
        copy.addActionListener(
                new ActionListener() {

                    public void actionPerformed(ActionEvent e) {
//t2.setText( t1.getSelectedText() );
                        t2.append(t1.getSelectedText());
                    }
                });
        c.add(copy);
        t2 = new JTextArea(10, 40);
        t2.setEditable(false);
        t2.setLineWrap(true);
        c.add(new JScrollPane(t2));
        setSize(425, 200);
        setVisible(true);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    }
}

No comments:

Post a Comment

Popular Posts