简体   繁体   中英

How to append text to JTextArea from main function int java?

I want to append some text to JTextArea from main function, but it doesn't work.

I am appending text from init() and from main() , but only text from init() appears on JTextArea .

public class Test extends JApplet{

    private static JPanel panel = new JPanel();
    private static JTextArea textArea = new JTextArea();

    public void init() {   

        panel.setLayout(null); 
        panel.setPreferredSize(new Dimension(400,300)); 
        this.add(panel);

        textArea.setBounds(20, 150, 350, 100);
        panel.add(textArea);

        setTextArea("BBBB");
    }

    public static void setTextArea(String text){
        textArea.append(text);
    }
    public static void main(String args[]) {        
        setTextArea("AAAAA");
    }   

}

I'm getting textarea just with "BBBB".

UPDATE

I have one more function. I am calling it from init() , text is appending and everything is fine. But if I put a line setTextArea("some text"); after line clientSocket = new Socket(address, port); , text won't append.

 private static void connetToServer() throws IOException, InterruptedException {
        try {
            //address = args.length > 0 ? args[0] : "localhost";
            //port = args.length > 1 ? Integer.parseInt(args[1]) : 4444;
            //System.out.println(address + ' ' + port);
            setTextArea("some text");
            clientSocket = new Socket(address, port);
            output = new PrintStream(clientSocket.getOutputStream());
            input = new DataInputStream(clientSocket.getInputStream());
            inputLine = new DataInputStream(new BufferedInputStream(System.in));
        } 
        catch( IOException e){
            setTextArea("Can't connet to server");
            System.exit(0);
        }
     }

You're getting "BBBB" appended to your text area because the init method is used as an entry point for applets and servlets .

Your class extends JApplet which is a subclass of java.applet.Applet meaning it will use init and not main (which is instead used as an entry point for applications).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM