个性化阅读
专注于IT技术分析

Java JTextArea用法

本文概述

JTextArea类的对象是显示文本的多行区域。它允许编辑多行文本。它继承了JTextComponent类

JTextArea类声明

我们来看一下javax.swing.JTextArea类的声明。

public class JTextArea extends JTextComponent

常用的构造函数:

建设者 描述
JTextArea() 创建一个文本区域, 该区域最初不显示任何文本。
JTextArea(String s) 创建一个文本区域, 该区域最初显示指定的文本。
JTextArea(int row, int column) 创建具有指定行数和列数的文本区域, 该区域最初不显示任何文本。
JTextArea(String s, int row, int column) 创建具有指定行数和列数的文本区域, 以显示指定的文本。

常用方法:

方法 描述
void setRows(int rows) 它用于设置指定的行数。
void setColumns(int cols) 用于设置指定的列数。
void setFont(Font f) 用于设置指定的字体。
void insert(String s, int position) 用于在指定位置插入指定文本。
void append(String s) 它用于将给定的文本附加到文档末尾。

Java JTextArea示例

import javax.swing.*;
public class TextAreaExample
{
	 TextAreaExample(){
	    JFrame f= new JFrame();
        JTextArea area=new JTextArea("Welcome to srcmini");
	    area.setBounds(10, 30, 200, 200);
	    f.add(area);
	    f.setSize(300, 300);
	    f.setLayout(null);
	    f.setVisible(true);
	 }
public static void main(String args[])
    {
   new TextAreaExample();
    }}

输出:

JAVA Jtextarea 1

带有ActionListener的Java JTextArea示例

import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1, l2;
JTextArea area;
JButton b;
TextAreaExample() {
    JFrame f= new JFrame();
	l1=new JLabel();
	l1.setBounds(50, 25, 100, 30);
	l2=new JLabel();
	l2.setBounds(160, 25, 100, 30);
	area=new JTextArea();
	area.setBounds(20, 75, 250, 200);
	b=new JButton("Count Words");
	b.setBounds(100, 300, 120, 30);
	b.addActionListener(this);
	f.add(l1);f.add(l2);f.add(area);f.add(b);
	f.setSize(450, 450);
	f.setLayout(null);
	f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
	String text=area.getText();
	String words[]=text.split("\\s");
	l1.setText("Words: "+words.length);
	l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
	new TextAreaExample();
}
}

输出:

JAVA Jtextarea 2
赞(0)
未经允许不得转载:srcmini » Java JTextArea用法

评论 抢沙发

评论前必须登录!