Please Enable JavaScript!
Gon[ Enable JavaScript ]

JTextArea 예제

자바(JAVA)
반응형

Text areas

Text fields
-- edit/display/enter single line of text
Text areas
-- accept entry or display many lines of text simultaneously.

The JTextArea is a very useful component you can do many things with it, edit, display text and save or load the contents of the text area both to and from a stream.

It is powerful and yet extremely easy to use. The figure below contains some source code loaded into the JTextArea instance by using the read() method in its JTextComponent parent.

 


Example JTextArea Output

We can accomplish these results with just 27 lines of code as follows:

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

class TextAreaExample
		extends 	JFrame
{
	public TextAreaExample()
	{
		setTitle( "Text Area Application" );
		setSize( 310, 230 );
		setBackground( Color.gray );
		getContentPane().setLayout( new BorderLayout() );

		JPanel topPanel = new JPanel();
		topPanel.setLayout( new BorderLayout() );
		getContentPane().add( topPanel, BorderLayout.CENTER );

        // Create a text area
		JTextArea area = new JTextArea();

        JScrollPane scrollPane = new JScrollPane();
        scrollPane.getViewport().add( area );
		scrollPane.setBounds( 10, 10, 280, 180 );
		topPanel.add( scrollPane, BorderLayout.CENTER );

		// Load a file into the text area, catching any exceptions
		try {
		    FileReader fileStream = new FileReader( "TextAreaExample.java" );
    		area.read( fileStream, "TextAreaExample.java" );
    	}
    	catch( FileNotFoundException e )
    	{
    	    System.out.println( "File not found" );
    	}
    	catch( IOException e )
    	{
    	    System.out.println( "IOException occurred" );
    	}
	}

	public static void main( String args[] )
	{
		// Create an instance of the test application
		TextAreaExample mainFrame	= new TextAreaExample();
		mainFrame.setVisible( true );
	}
}

The main points of this program is:

  • it creates an instance of a JScrollPane, and inserts the JTextArea into it.
  • Note JTextArea does not provide scrolling capability, so you must use this technique to implement the ability to scroll.
  • The basic components such as cut and paste, editing and selection of text are fully functional although application methods will need to implement as in JTextField to handle these events.

JTextArea implements methods to insert and append text into the component's document:

public void insert(String str, int pos)
public void append(String str)
public void replaceRange(String str,
int start, int end)

The text area will pad tab characters with a specified number of spaces. The methods in this group allow the tab size to be changed or retrieved. This is useful if you want to present some custom display format:

public void setTabSize(int size)
public int getTabSize()


http://www.cs.cf.ac.uk/Dave/HCI/HCI_Handout_CALLER/node114.html#SECTION000105000000000000000
반응형
Posted by 녹두장군1
,