Wednesday, May 9, 2012

How to use JScrollPane,ActionEvent, with JTextArea?Example code

   It is important that you will first come to understand the program before you get to start coding it. What the program will execute and how will be its logic.
   In this program,user can choose and select text elements  in the first JTextArea and can copy in other JTextArea. There are two JTextArea in an object that you will create(t1 and t2). t1  where text was written and can be set in the codes and t2 where the selected text in t1 will be pasted.
 
 
 //Filename:Copycat.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class Copycat extends JFrame{
   JTextArea t1,t2;
   JButton copy;
    public TxtAreaDemo()
    {
        super ("Tittle ng application!");
        //Box ay subclass ng java.awt.Container
        Box box=Box.createHorizontalBox();
        String stringSaLoobNgt1="Eto yung mga kokopyahin\n"+
                "na mga selected lines\n";
        t1=new JTextArea(stringSaLoobNgt1,10,15);
        //Ang JTextArea ay hindi nagpo-provide ng scrollbars
        box.add(new JScrollPane(t1));//gumawa ng scrollbar
     
        //yun selected text sa t1 will be copy sa t2
         copy=new JButton("kopyahin dito>>");
        copy.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e)
                    {
                        t2.setText(t1.getSelectedText());
                    }
                });
        box.add(copy);
     
        //set t2
        t2=new JTextArea(10,15);
         t2.setEditable(false);
        box.add(new JScrollPane(t2));
     
        //Container ay collection ng components
        Container c=getContentPane();
        c.add(box);
        setSize(425,200);
        show();//use to show the object
         }
 
    public static void main(String[] args) {
        TxtAreaDemo app=new TxtAreaDemo();
        app.addWindowListener(
                new WindowAdapter(){
                    public void widowClosing(WindowEvent e)
                    {
                        System.exit(0);
                    }
                });
     
    }
}
OUTPUT:

No comments:

Post a Comment