java如何在jtextarea中写入文字,并获得文字个数

java如何在jtextarea中写入文字,并获得文字个数,第1张

JTextArea text =

textsetText("要写入的文字");

String str = textgetText();//得到里面的文字

int i = strlength();//个数

package zhidao;

import javaawt;

import javaawtevent;

import javaioFile;

import javatext;

import javautil;

import javautilconcurrentConcurrentHashMap;

import javaxswing;

import javaxswingtable;

public class TokenCategorizer extends JFrame

{

private static final long serialVersionUID = 1L;

private static final String FILE_NAME = "testtxt";

private static final String[] NAMES = { "Integer numbers", "Real numbers", "Other tokens" };

private static String[][] data = null;

private static JList jList = null;

private static JTable tableView = null;

private static LinkedList<String[]> list = new LinkedList<String[]> ();

private static String[] strs = new String[NAMESlength];

private static Vector<SupportedLaF> lafVector = new Vector<SupportedLaF> ();

private static Map<Integer, Vector<String>> tabelDataMap = new ConcurrentHashMap<Integer, Vector<String>> ();

private static final String PLASTIC3D = "comjgoodieslooksplasticPlastic3DLookAndFeel";

private static final String PLASTIC = "comjgoodieslooksplasticPlasticLookAndFeel";

private static final String PLASTXP = "comjgoodieslooksplasticPlasticXPLookAndFeel";

public TokenCategorizer ( String title )

{

UIManagerinstallLookAndFeel ("Plastic3D", PLASTIC3D);

UIManagerinstallLookAndFeel ("Plastic", PLASTIC);

UIManagerinstallLookAndFeel ("PlasticXP", PLASTXP);

UIManagerLookAndFeelInfo[] installedLafs = UIManagergetInstalledLookAndFeels ();

for ( UIManagerLookAndFeelInfo lafInfo : installedLafs )

{

try

{

Class<> lnfClass = ClassforName (lafInfogetClassName ());

LookAndFeel laf = (LookAndFeel) ( lnfClassnewInstance () );

if (lafisSupportedLookAndFeel ())

{

String name = lafInfogetName ();

lafVectoradd (new SupportedLaF (name, laf));

}

}

catch (Exception e)

{

continue;

}

}

thissetTitle (title);

}

private static class SupportedLaF

{

String name;

LookAndFeel laf;

SupportedLaF ( String name, LookAndFeel laf )

{

thisname = name;

thislaf = laf;

}

public String toString ()

{

return name;

}

}

private static void createTable ( TokenCategorizer tc )

{

TableModel dataModel = new AbstractTableModel ()

{

private static final long serialVersionUID = 1L;

public int getColumnCount ()

{

return NAMESlength;

}

public int getRowCount ()

{

return data[0]length;

}

public Object getValueAt ( int row, int col )

{

return data[col][row];

}

public String getColumnName ( int column )

{

return NAMES[column];

}

};

tableView = new JTable (dataModel);

tableViewsetSelectionMode (ListSelectionModelSINGLE_SELECTION);

tableViewsetRowSelectionInterval (0, 0);

initTableData (tableView, list, strs);

tableViewaddMouseListener (new MouseAdapter ()

{

@Override

public void mouseClicked ( MouseEvent e )

{

initTableData (tableView, list, strs);

}

});

JScrollPane scrollpane = new JScrollPane (tableView);

scrollpanesetPreferredSize (new Dimension (500, 400));

tcadd (scrollpane);

}

private static void initTableData ( final JTable tableView, final LinkedList<String[]> list, final String[] strs )

{

try

{

listclear ();

int row = tableViewgetSelectedRow ();

Vector<String> v = null;

if (null != ( v = tabelDataMapget (row) ))

{

jListsetListData (v);

}

else

{

for ( int j = 0; j < NAMESlength; j++ )

{

strs[j] = data[j][row];

}

permutations (list, NAMESlength, strs, 0, -1);

v = new Vector<String> ();

for ( String[] strings : list )

{

vadd (ArraystoString (strings)replaceAll ("[\\[\\]]", ""));

}

jListsetListData (v);

tabelDataMapput (row, v);

}

}

catch (Exception e)

{}

}

private static void createList ( TokenCategorizer tc )

{

ListModel dataModel = new AbstractListModel ()

{

private static final long serialVersionUID = 1L;

@Override

public int getSize ()

{

return NAMESlength;

}

@Override

public Object getElementAt ( int index )

{

return NAMES[index];

}

};

jList = new JList (dataModel);

}

private static void initFrame ( TokenCategorizer tc )

{

tcsetLayout (new FlowLayout (FlowLayoutLEFT));

tcsetSize (800, 400);

tcsetLocationRelativeTo (null);

tcpack ();

tcsetResizable (false);

tcsetDefaultCloseOperation (JFrameEXIT_ON_CLOSE);

tcsetVisible (true);

}

private static LinkedList<String[]> permutations ( LinkedList<String[]> list, int count, String[] array, int ind,

int start, int indexs )

{

start++;

if (start > count - 1)

{

return null;

}

if (start == 0)

{

indexs = new int[arraylength];

}

for ( indexs[start] = 0; indexs[start] < arraylength; indexs[start]++ )

{

permutations (list, count, array, 0, start, indexs);

if (start == count - 1)

{

String[] temp = new String[count];

for ( int i = count - 1; i >= 0; i-- )

{

temp[start - i] = array[indexs[start - i]];

}

boolean flag = true;

L: for ( int i = 0; i < templength; i++ )

{

for ( int j = i + 1; j < templength; j++ )

{

if (temp[i]equals (temp[j]))

{

flag = false;

break L;

}

}

}

if (flag)

{

listadd (temp);

}

}

}

return list;

}

private static void initOthers ( final TokenCategorizer tc )

{

JPanel jPanel = new JPanel ();

BoxLayout boxLayout = new BoxLayout (jPanel, BoxLayoutY_AXIS);

jPanelsetLayout (boxLayout);

jPanelsetPreferredSize (new Dimension (300, 400));

JScrollPane scrollpane = new JScrollPane (jList);

scrollpanesetPreferredSize (new Dimension (300, 400));

jPaneladd (scrollpane);

final JFileChooser chooser = new JFileChooser ();

JPanel bottomPanel = new JPanel ();

JButton jButton = new JButton ("Import File Data");

jButtonaddActionListener (new ActionListener ()

{

@Override

public void actionPerformed ( ActionEvent e )

{

int returnVal = choosershowOpenDialog (tc);

if (returnVal == JFileChooserAPPROVE_OPTION)

{

File file = choosergetSelectedFile ();

loadFileData (filegetPath ());

SwingUtilitiesupdateComponentTreeUI (tc);

tabelDataMapclear ();

tableViewsetRowSelectionInterval (0, 0);

initTableData (tableView, list, strs);

}

}

});

bottomPanelsetLayout (new FlowLayout (FlowLayoutLEFT));

final JComboBox jcb = new JComboBox (lafVector);

jcbaddActionListener (new ActionListener ()

{

@Override

public void actionPerformed ( ActionEvent e )

{

SupportedLaF supportedLaF = ( (SupportedLaF) jcbgetSelectedItem () );

LookAndFeel laf = supportedLaFlaf;

try

{

UIManagersetLookAndFeel (laf);

SwingUtilitiesupdateComponentTreeUI (tc);

if (null != chooser)

{

SwingUtilitiesupdateComponentTreeUI (chooser);

}

}

catch (UnsupportedLookAndFeelException exc)

{

( (DefaultComboBoxModel) jcbgetModel () )removeElement (supportedLaF);

}

}

});

bottomPaneladd (jcb);

bottomPaneladd (jButton);

jPaneladd (bottomPanel);

tcadd (jPanel);

}

private static void loadFileData ( String fileName )

{

Locale locale = new Locale ("en", "US");

Scanner scanner = null;

String result = "";

String line = null;

LinkedList<String> listInt = new LinkedList<String> ();

LinkedList<String> listDouble = new LinkedList<String> ();

LinkedList<String> listOthers = new LinkedList<String> ();

try

{

scanner = new Scanner (new File (fileName))useDelimiter ("[\\s\r\n\t\f]+");

while (scannerhasNext ())

{

line = scannernext ();

result += line + " ";

if (linematches ("^(\\+|\\-)[\\d,]+$"))

{

NumberFormat nf = NumberFormatgetInstance (locale);

listIntadd (nfparse (line)toString ());

}

else if (linematches ("^[\\dE\\\\+\\-]+$"))

{

NumberFormat f = NumberFormatgetInstance (locale);

if (f instanceof DecimalFormat)

{

( (DecimalFormat) f )setDecimalSeparatorAlwaysShown (true);

}

listDoubleadd (fparse (line)toString ());

}

else

{

listOthersadd (line);

}

}

}

catch (Exception e)

{}

scannerclose ();

int max =

listIntsize () > listDoublesize ()  listIntsize () > listOtherssize ()  listIntsize ()

: listOtherssize () : listDoublesize () > listOtherssize ()  listDoublesize ()

: listOtherssize ();

int size1 = listIntsize ();

for ( int i = size1; i < max; i++ )

{

listIntadd (" ");

}

int size2 = listDoublesize ();

for ( int i = size2; i < max; i++ )

{

listDoubleadd ("  ");

}

int size3 = listOtherssize ();

for ( int i = size3; i < max; i++ )

{

listOthersadd ("   ");

}

String reg = "[\\[\\]]";

String intdata = listInttoString ()replaceAll (reg, "");

String realdata = listDoubletoString ()replaceAll (reg, "");

String otherdata = listOtherstoString ()replaceAll (reg, "");

Systemoutprintln ("Text file: ");

Systemoutprintln (result);

Systemoutprintln ("sumDouble: ");

Systemoutprintln (realdatareplaceAll ("[,\\s]+$", ""));

Systemoutprintln ("sumInt: ");

Systemoutprintln (intdatareplaceAll ("[,\\s]+$", ""));

Systemoutprintln ("sumOther: ");

Systemoutprintln (otherdatareplaceAll ("[,\\s]+$", ""));

String[] ints = intdatasplit (",\\s");

String[] reals = realdatasplit (",\\s");

String[] others = otherdatasplit (",\\s");

data = new String[][] { ints, reals, others };

}

public static void main ( String[] args )

{

loadFileData (FILE_NAME);

TokenCategorizer tc = new TokenCategorizer ("Categories/columns containing tokens");

createList (tc);

createTable (tc);

initOthers (tc);

initFrame (tc);

}

}

可以使用 JLabel、JTextField 组件显示文字。下面是一个示例可以参考一下:

import javaawtFlowLayout;

import javaxswingJFrame;

import javaxswingJLabel;

import javaxswingJTextField;

class MainFrame extends JFrame {

public MainFrame() {

thissetSize(400, 300);

thissetLocationRelativeTo(null);

thissetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

thissetLayout(new FlowLayout());

// 使用 JLabel 文字

JLabel label = new JLabel();

labelsetText("这是一个Label"); // 设置显示文字

thisadd(label);

// 使用 JTextField 显示文字

JTextField field = new JTextField();

fieldsetText("这是一个 JTextField"); // 设置显示文字

thisadd(field);

}

}

public class App {

public static void main(String[] args) {

new MainFrame()setVisible(true);

}

}

运行结果:

import javaxswing;

import javaxswingfilechooserFileNameExtensionFilter;

import javaawtevent;

import javaawt;

import javaio;

class test extends JFrame{

JButton jb=new JButton("打开txt文件");

JTextArea jt=new JTextArea();

test(){

setSize(400,300);

setVisible(true);

setLayout(new BorderLayout());

add(jb,BorderLayoutSOUTH);

add(jt,BorderLayoutNORTH);

jbaddActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){

JFileChooser chooser = new JFileChooser();

FileNameExtensionFilter filter = new FileNameExtensionFilter("文本文件(txt)", "txt");

choosersetFileFilter(filter);

int returnVal = choosershowOpenDialog(null);

if(returnVal == JFileChooserAPPROVE_OPTION) {

try{ FileInputStream fd=new FileInputStream(choosergetSelectedFile());

byte[] b=new byte[4096];

fdread(b);

jtsetText(new String(b));

fdclose();

}catch( IOException ex){}

}

}

});

}

public static void main(String args[]){

new test();

}

}

import javaxswing;

import javaawt;

import javaawtevent;

@SuppressWarnings("serial")

public class ButtonActionTest extends JFrame{

//创建三个文本按钮

private JButton jb1=new JButton("Java"),

jb2=new JButton("Linux"),

jb3=new JButton("Windows");

private JToggleButton jb4=new JToggleButton("JToggleButton");

//创建一个文本区域

private TextField tf=new TextField(15);

public ButtonActionTest()

{

//创建一个监听器类,当单击按钮时获得按钮上的文字

class ButtonAction implements ActionListener

{

public void actionPerformed(ActionEvent e)

{

String name=((JButton)egetSource())getText();

tfsetText(name);

}

}

ButtonAction ba=new ButtonAction();//创建按钮监听器

//为按钮注册监听器

jb1addActionListener(ba);

jb2addActionListener(ba);

jb3addActionListener(ba);

JFrame jf=new JFrame("测试按钮事件");//创建Frame容器,并设置标题

//设置按钮的分布方式

jfsetLayout(new FlowLayout());

//将各组件添加进容器

jfadd(jb1);

jfadd(jb2);

jfadd(jb3);

jfadd(jb4);

jfadd(tf);

jb1setToolTipText("这一个java");

jfsetSize(350,200);//设置容器大小

jfsetVisible(true);//将容器设为可视

jfsetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);

}

public static void main(String args[])

{

new ButtonActionTest();

}

import javaawt;

import javaawtevent;

public class MyFrame implements ActionListener{

public Button a ;//a按钮

public Button b ;//b按钮

public Button c ;//c按钮

public TextArea t;//t文本域

public MyFrame() {

Frame f = new Frame("显示三个按钮的文本");

fsetSize(300,500);

fsetLayout(new FlowLayout());

a = new Button("a按钮");

b = new Button("b按钮");

c = new Button("c按钮");

t = new TextArea(8,8);

fadd(t); fadd(a); fadd(b); fadd(c);//具体的布局就由你自己来布局了

fsetVisible(true);//显示窗体

aaddActionListener(this); baddActionListener(this); caddActionListener(this);

//添加监听器

}

public void actionPerformed(ActionEvent e) {//事件

if(egetSource()==a) {

tappend(agetLabel()+"\n");

}

if(egetSource()==b) {

tappend(bgetLabel()+"\n");

}

if(egetSource()==c) {

tappend(cgetLabel()+"\n");//具体的输出格式也可以自己来设定

}

}

public static void main(String args[]) {

new MyFrame();

}

}

你先通过io字符流读取出来,然后在通过java Swing窗体 中的JPanel 中的模板显示啊

读取txt 的io流代码:

BufferedReader br = new BufferedReader(new FileReader(new File(‘atxt’)));

String s;

while ((s = brreadLine()) != null) {

Systemoutprintln(s);

}

网页可以用Java的网络编程来模仿传统的CGI编程,去解析一个>

以上就是关于java如何在jtextarea中写入文字,并获得文字个数全部的内容,包括:java如何在jtextarea中写入文字,并获得文字个数、初学JAVA现在编写一个记事本窗体,关于如何实现打开读取文件功能提问、java 输出文字到新建窗口等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/9657032.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-30
下一篇 2023-04-30

发表评论

登录后才能评论

评论列表(0条)

保存