如何在Java中将文本从JTextarea转换为OutputStream或将文本从JTextarea打印至控制台?

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

class Clients implements ActionListener
{
    JFrame fr;
    JPanel p1,p2;
    JTextArea asend,achat;
    JButton b1,b2;
    String s1;
    String f;

    Clients()
    {
        fr=new JFrame();
        fr.setLayout(new GridLayout(2,1));
        p1=new JPanel(new GridLayout(1,1));
        p2=new JPanel(new GridLayout(1,2));
        achat=new JTextArea(80,80);
        asend=new JTextArea(30,30);
        b1=new JButton("send");
        b2=new JButton("close");

        p1.add(new JScrollPane(achat));
        p2.add(asend);
        p2.add(b1);
        p1.setVisible(true);
        p2.setVisible(true);
        p1.setSize(400,300);
        p2.setSize(400,100);

        fr.add(p1);
        fr.add(p2);
        fr.setVisible(true);
        fr.setSize(400,400);
        b1.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource()==b1)
        {
            s1 = asend.getText();
            appendData(s1);
            send();
            asend.setText( " ");
            set(s1);
        }
    }

    public void set(String a)
    {
        f=a;
    }

    public void appendData(String a)
    {
        String b=a;
        //get data from 'asned' textarea into 'achat' textarea
        achat.append( "\n SENT:      "+b);
    }

    public String send()
    {
        String h=f;
        //(return the value of string caught from textbox)
        return(h);
    }

    public void setRec(String g)
    {
        String s2=g;
        achat.append("\n RECIEVED:       "+s2);
    }

    public static void main(String s[])
    {
        Clients d=new Clients();
        /*
         * object calls da method send 2 acesss non static
         * data from static block of main method
         */
        String sendn=d.send();
        try
        {
            Socket so=new Socket("169.254.121.33 ",255);
            DataInputStream inp=new DataInputStream(so.getInputStream());
            PrintStream outp=new PrintStream(so.getOutputStream());
            System.out.println(sendn);
            Boolean b=true;
            while(b)
            {
                String incomng=inp.readLine();
                d.setRec(incomng);    //incoming data is transferrd
                System.out.println(incomng);
                outp.println(sendn);
                if(incomng==null)
                {
                    b=false;
                }
            }
        }
        catch(IOException ee)
        {
        }
    }
}


代码首先通过set()方法从JTextArea achat中获取数据。.dis方法中的dn数据被传输到main或console的静态块中。主要问题是我无法从在main method()中。

最佳答案

Component.getText()按下按钮或执行某些操作后,此功能将返回该区域中的String

JTextArea textArea = new JTextArea();
String s = textArea.getText();

10-06 16:15