Hot questions for Using JTextField in jtextarea

Question:

In my program, I want a large area for typing in. I have been playing around with JTextPanes and JTextAreas. However if I continuously type, when I reach the end of the area, it does not automatically create a new line it just continues off the box, I know that I can add a horizontal scroll bar, but I would prefer it to just drop to a new line when I reach the end of the box. I saw something called dropMode and tried playing with this to see if it helped, but it just resulted in the following error "Unsupported drop mode for text". My program is GUI based, therefore the user will be typing directly into the area, not appending it.


Answer:

textArea.setLineWrap(true) should work as you want.

Example:

public Etst() {
    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    JTextArea area = new JTextArea();
    area.setLineWrap(true);
    f.add(area);
    f.setSize(100, 100);
    f.setVisible(true);
}

Question:

I want a JTextArea in a certain position. I tried several things like using different LayoutManagers, no LayoutManager at all, setLayout(null) etc. Whatever I do, it seems like setBounds(), setLocation() and setSize() aren't working here, but I read about it and it said it should work. So what am I doing wrong?

The JTextArea is always too high and the position doesn't change if I change the Parameters in setBounds().

public class textarea extends JPanel {

    public static void main(String[] args){
        JFrame frame = new JFrame("text area");
        textarea content = new textarea();
        frame.setContentPane(content);
        frame.setLocation(120,70);
        frame.pack();
        frame.setVisible(true);
        frame.setSize(700,500);     
    }

    JPanel PanelForText;

    public textarea(){
        setBackground(Color.LIGHT_GRAY);
        setLayout(new FlowLayout(FlowLayout.CENTER,50,50));

        txtArea txt = new txtArea();

        PanelForText = new JPanel();
        PanelForText.setPreferredSize(new Dimension(500,300));
        PanelForText.setBorder(BorderFactory.createEtchedBorder());
        PanelForText.add(txt);

        add(PanelForText);
    }
}


public class txtArea extends JPanel {

    boolean textAreaCreated = false;

    public txtArea(){
        setBackground(Color.WHITE);
        setPreferredSize(new Dimension(496, 290));
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.GRAY);
        g.fillRect(50, 25, 400, 245);
        if (!textAreaCreated)
            createTextArea();
    }

    public void createTextArea() {  
        JTextArea Text = new JTextArea();
        Text.setBounds(500,300,300,300);
        Text.setOpaque(false);
        Text.setWrapStyleWord(true);
        Text.setLineWrap(true); 
        Text.setBorder(BorderFactory.createLineBorder(Color.RED));
        add(Text);
        textAreaCreated = true;
    }
}

Here is what I want it to look like:

And here is what it currently looks like:

I did a few tutorials where they used JTextFields that were added to JPanels, but I was wondering if I could just use a JTextField or JTextArea for more text WITHOUT adding it to a Panel first!

Like I said, I was looking up "how to set JTextArea position" and it said to use setBounds(). Apparently that's not correct.. So again, all I want to know is how to do it better. Also: I did read a lot about the LayoutManagers, but for me trying to use it is more helpful than just reading about it...

I tried that with rows and columns, but it didn't change the fact that the JTextArea was not in the right position.

What I did was (in the CreateTextArea method):

public void createTextArea() {  
    JTextArea Text = new JTextArea(5,1);
    Text.setOpaque(false);
    Text.setWrapStyleWord(true);
    Text.setLineWrap(true); 
    Text.setBorder(BorderFactory.createLineBorder(Color.RED));
    add(Text);
    textAreaCreated = true;
}

Answer:

You could achieve your center-nested look by doing just that, using GridBagLayout to center nest your components. You could achieve the width of some of the framing JPanels by using an EmptyBorder. You should never add components from within a paintComponent method.

For example:

import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;

@SuppressWarnings("serial")
public class TestTextArea2 extends JPanel {

   private static final Color BG = Color.LIGHT_GRAY;
   private static final int ROWS = 14;
   private static final int COLS = 34;
   private JTextArea textArea = new JTextArea(ROWS, COLS);

   public TestTextArea2(int heightGap, int sideGap) {
      setBorder(BorderFactory.createEmptyBorder(heightGap, sideGap, heightGap, sideGap));

      textArea.setBackground(Color.LIGHT_GRAY);
      JScrollPane scrollPane = new JScrollPane(textArea);

      JPanel txtAreaPanel = new JPanel(); 
      int ebGap = 40;
      txtAreaPanel.setBackground(Color.white);
      txtAreaPanel.setBorder(BorderFactory.createEmptyBorder(ebGap, ebGap, ebGap, ebGap));
      txtAreaPanel.setLayout(new GridBagLayout());
      txtAreaPanel.add(scrollPane);

      JPanel myPanel2 = new JPanel();
      Border outerBorder = BorderFactory.createEtchedBorder();
      int heightGap2 = 5;
      int sideGap2 = 5;
      Border innerBorder = BorderFactory.createEmptyBorder(heightGap2, sideGap2, heightGap2, sideGap2);
      myPanel2.setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));

      myPanel2.setLayout(new GridBagLayout());
      myPanel2.add(txtAreaPanel);

      setBackground(BG);
      setLayout(new GridBagLayout());
      add(myPanel2);
   }


   private static void createAndShowGui() {
      JFrame frame = new JFrame("TestTextArea2");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new TestTextArea2(100, 100));
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

And note, not one setSize(...) or setPreferredSize(...).

Question:

I have two JTextField which take numbers from users, like this:

nbMuscle = new JTextField();
nbMuscle.setText("2");

and this:

nbFuyard = new JTextField();
nbFuyard.setText("1");

my JTextArea() takes make an addition of both JTextField's values, like this:

nbPersonnages = new JTextArea();
int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));

It works like a charm but I have one problem, if the user edit one of the JTextFields, the JTextArea value don't change. I have found on internet some notions like jTextArea.appened(String str) but it doesn't work.

Any idea of what I could do?


Answer:

You have to add a DocumentListener to the underlying Document of the TextFields to listen to changes made while the program runs. The easiest way to do this is proboably an anonymous class. Here is the Code:

nbMuscle = new JTextField();
nbMuscle.setText("2");
nbFuyard = new JTextField();
nbFuyard.setText("1");

nbPersonnages = new JTextArea();

DocumentListener dl = new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent e) {
        textChanged();
    }

    @Override
    public void insertUpdate(DocumentEvent e) {
        textChanged();
    }

    @Override
    public void changedUpdate(DocumentEvent e) {
        // This method is not called when the text of the Document changed, but if attributes of the Document changed.
    }

    private void textChanged() {
        int nombMusc = Integer.valueOf(nbMuscle.getText());
        int nombFuy = Integer.valueOf(nbFuyard.getText());
        int nbTotal = nombMusc + nombFuy;
        nbPersonnages.setText(String.valueOf(nbTotal));
    }
};

int nombMusc = Integer.valueOf(nbMuscle.getText());
int nombFuy = Integer.valueOf(nbFuyard.getText());
int nbTotal = nombMusc + nombFuy;
nbPersonnages.setText(String.valueOf(nbTotal));

nbMuscle.getDocument().addDocumentListener(dl);
nbFuyard.getDocument().addDocumentListener(dl);

Question:

I'm trying to remove all the even lines in a JTextArea, but I'm having trouble getting that to work. My JTextArea is called "input" and I'm using a for loop to iterate through the lines and then remove all the even ones. My for loop:

for (int i=0; i<lineMax; i++) {
    if (lineNum % 2 == 0) {
        end = input.getLineEndOffset(0);
        input.replaceRange("", 0, end);
    }
    lineNum++;
}

If I put "This is a test" into my JTextArea with each word on a new line the output will be "a test" (with each word on a new line).


Answer:

end = input.getLineEndOffset(0);
input.replaceRange("", 0, end);

That will always get the offset of the first line, so you will always be removing text from offset 0, to the end of the first line.

The algorithm will be more complicated than that when you attempt to loop forward in the text area because every time you remove a line the offsets of the following lines change and the relative lines number change so you don't know which line is odd/even any more.

An easier approach would be to start with the last line in the text area. This way relative line numbers of the previous lines will not change as you delete the text.

You can use the following methods of the JTextArea to help with the logic:

  1. getLineCount() - start here and count back to line zero
  2. getLineEndOffset() and getLineStartOffset() - when you find an even line you get the two offsets and remove the text.

Question:

So I'm trying to make a fill up form when i click on the add menu. So once I click add, it will show me a fill up form and I must I fill it up so that I can view it on the other window or frame with a jtextarea that I made. My problem is that once I input the data on my fill up form, the output will only show one text field in the jtextarea. I must output all the inputs that I placed in my jtextfield and output it as one in another jtextarea. Also, I must put the JLabel on the jtextarea output too. For example, I have the FirstName label, and I will input on the Jtext "my name" then it should output on the other window as First Name: MyName together with the other requirements to be inputted. Hope I can get some little help. Thank you. Here's my work so far:

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

public class Sample extends JFrame implements ActionListener {
    JTextField r = new JTextField();
    JDesktopPane desk = new JDesktopPane();
    JMenuBar bar = new JMenuBar();
    JMenu mAdd = new JMenu("Add");
    JMenu mView = new JMenu("View");
    JMenuItem miNew =new JMenuItem("New");
    JMenuItem miExit = new JMenuItem("Exit");
    JMenuItem miStudInfo = new JMenuItem("Student Info");
    JMenuItem miEducInfo = new JMenuItem("Educational Info");

    JLabel personalInfo = new JLabel("Personal Information");
    JLabel space1 = new JLabel("");
    JLabel space2 = new JLabel("");
    JLabel studnum = new JLabel("Student #: ");
    JLabel space3 = new JLabel("");
    JTextField jtxstudnum = new JTextField();
    JLabel fname = new JLabel("First Name: ");
    JLabel space4 = new JLabel("");
    JTextField jtxfname = new JTextField();
    JLabel midname = new JLabel("Middle Name: ");
    JLabel space5 = new JLabel("");
    JTextField jtxmidname = new JTextField();
    JLabel lname = new JLabel("Last Name: ");
    JLabel space6 = new JLabel("");
    JTextField jtxlname = new JTextField();
    JLabel address = new JLabel("Address: ");
    JLabel space7 = new JLabel("");
    JTextField jtxaddress = new JTextField();

    JLabel educQualify = new JLabel("Educational Qualification");
    JLabel space8 = new JLabel("");
    JLabel space9 = new JLabel("");
    JLabel preschool = new JLabel("Preschool: ");
    JTextField jtxpre= new JTextField();
    JTextField jtxpreyear = new JTextField();
    JLabel elementary = new JLabel("Elementary: ");
    JTextField jtxelem = new JTextField();
    JTextField jtxelemyear = new JTextField();
    JLabel highschool = new JLabel("HighSchool: ");
    JTextField jtxhigh = new JTextField();
    JTextField jtxhighyear = new JTextField();
    JLabel college = new JLabel("College: ");
    JTextField jtxcol = new JTextField();
    JTextField jtxcolyear = new JTextField();
    JLabel postgrad = new JLabel("PostGrad: ");
    JTextField jtxpost = new JTextField();
    JTextField jtxpostyear = new JTextField();

    JLabel space10 = new JLabel("");
    JButton jbtnView = new JButton("View");
    JButton jbtnReset = new JButton("Reset");

JPopupMenu jpExit = new JPopupMenu("Select an option");
JButton yes = new JButton("Yes");
JButton no = new JButton("No");
JButton cancel = new JButton("Cancel");
JLabel message;

JTabbedPane tabbedPane;
//JTabbedPane tabStudInfo = new JTabbePane("Student Info");
//JTabbedPane tabEducInfo = new JTabbePane("Educational Info");
JPanel p1;
JPanel p2;
JPanel p3;

Container con = getContentPane();


public Sample() {
    setTitle("Student Information");
    setSize(900,700);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLocationRelativeTo(null);

    con.add(desk);
    setJMenuBar(bar);

    bar.add(mAdd);
    bar.add(mView);
    mAdd.add(miNew);
    mAdd.add(miExit);
    mView.add(miStudInfo);
    mView.add(miEducInfo);

    miNew.addActionListener(this);
    mAdd.add(miExit);
    miExit.addActionListener(this);
    miStudInfo.addActionListener(this);
    miEducInfo.addActionListener(this);


    setVisible(true);
}

public void actionPerformed(ActionEvent e){
        if(e.getSource()==miNew){
        JInternalFrame nf = new JInternalFrame("Add -> New", true, true, true, true );
        nf.setSize(450,500);
        nf.setDefaultCloseOperation(JInternalFrame.HIDE_ON_CLOSE);

        Container con = nf.getContentPane();
        con.setLayout(new GridLayout(13,2));
        //con.setLayout(new GridLayout(6,2));
        con.add(personalInfo);
        con.add(space1);
        con.add(space2);
        //personalInfo.setBounds(2,2,200,30);
        //x=100, y =50, width=300, height=30
        con.add(studnum);
        con.add(space3);
        con.add(jtxstudnum);
        con.add(fname);
        con.add(space4);
        con.add(jtxfname);
        con.add(midname);
        con.add(space5);
        con.add(jtxmidname);
        con.add(lname);
        con.add(space6);
        con.add(jtxlname);
        con.add(address);
        con.add(space7);
        con.add(jtxaddress);

    //  con.setLayout(new GridLayout(6,3));
        con.add(educQualify);
        con.add(space8);
        con.add(space9);
        con.add(preschool);
        con.add(jtxpre);
        con.add(jtxpreyear);
        con.add(elementary);
        con.add(jtxelem);
        con.add(jtxelemyear);
        con.add(highschool);
        con.add(jtxhigh);
        con.add(jtxhighyear);
        con.add(college);
        con.add(jtxcol);
        con.add(jtxcolyear);
        con.add(postgrad);
        con.add(jtxpost);
        con.add(jtxpostyear);

    //  con.setLayout(new GridLayout(1,2));
        con.add(space10);
        con.add(jbtnView,BorderLayout.SOUTH);
        con.add(jbtnReset,BorderLayout.SOUTH);

        //r.setEditable(false);
        jbtnView.addActionListener(this);       
        jbtnReset.addActionListener(this);

        nf.setVisible(true);

        desk.add(nf);

    }

    else if(e.getSource()==jbtnView){
        r.setText(jtxstudnum.getText());

        JInternalFrame showNF =  new JInternalFrame("Show Result", true, true, true, true);
        showNF.setSize(400,500);
        showNF.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
        showNF.setLocation(300,0);

        Container showNFcon = showNF.getContentPane();
        showNFcon.setLayout(new FlowLayout());
        JTabbedPane pane = new JTabbedPane();

        JPanel p1 = new JPanel();
        p1.setLayout(new FlowLayout());
        JTextArea display = new JTextArea(20,30);
        p1.add(display);
        display.setText(jtxstudnum.getText()); display.setText(jtxfname.getText());


        display.setText(jtxfname.getText());
        display.setText(jtxmidname.getText());
        display.setText(jtxlname.getText());
        display.setText(jtxaddress.getText());

        pane.add("Student Info", p1);


        JPanel p3 = new JPanel();
        p3.setLayout(new FlowLayout());
        JTextArea display2 = new JTextArea(20,30);
        p3.add(display2);
        display2.setText(jtxpre.getText());
        display2.setText(jtxpreyear.getText());
        display2.setText(jtxelem.getText());
        display2.setText(jtxelemyear.getText());
        display2.setText(jtxhigh.getText());
        display2.setText(jtxhighyear.getText());
        display2.setText(jtxcol.getText());
        display2.setText(jtxcolyear.getText());
        display2.setText(jtxpost.getText());
        display2.setText(jtxpostyear.getText());
        pane.add("Educational Info", p3);


        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());

        p2.add(pane);
        showNFcon.add(p2);


        showNF.setVisible(true);
        desk.add(showNF);
    }
        //else if(e.getSource()==b){
    //  r.setText(t.getText());
//  }
 /*
        else if(e.getSource()==miExit)
        //  con.add(jpExit);

        int response = JOptionPane.showConfirmDialog(null,"Exit?","Select an option",JOptionPane.QUESTION_MESSAGE);
        switch(response){
            case JOptionPane.YES_OPTION:
                message.setText("Yes");
                System.exit(0);
                break;
            case JOptionPane.NO_OPTION:
                message.setText("No");
                break;
            case JOptionPane.CANCEL_OPTION:
                message.setText("Cancel");
                break;

        }*/
        //System.exit(0);

}
/*
public void createPage1(){
    panel1 = new JPanel();
//  panel1=setLayout(new BorderLayout());


}

public void createPage2(){
    panel2 = new JPanel();
//  panel2=setLayout(new BorderLayout());


}*/


public static void main(String[] args) {
    Sample frame = new Sample();
}

}


Answer:

You problem is here...

display.setText(jtxstudnum.getText());
display.setText(jtxfname.getText());

display.setText(jtxfname.getText());
display.setText(jtxmidname.getText());
display.setText(jtxlname.getText());
display.setText(jtxaddress.getText());

setText does that, it says, "discard what ever text you current have set the text I'm giving you as your only content"...

Instead, you want to use JTextArea#append instead

display.append(jtxstudnum.getText());
display.append(jtxfname.getText());

display.append(jtxfname.getText());
display.append(jtxmidname.getText());
display.append(jtxlname.getText());
display.append(jtxaddress.getText());

Which does what it says, it appends the supplied text to the existing content

Take a closer look at How to Use Text Areas for more details

Question:

I am trying to implement buttons that search a specific word in JTextArea in my Java Swing application. Can anyone help me to implement buttons to highlight the next and previous match ? Please review my code for searchbutton aswell. For now it works fine.

PS. I want run searchButton in new Thread. Is it okay like that ???

searchButton.addActionListener(e -> new Thread(() -> {
        int pos = 0;
        // Get the text to find...convert it to lower case for eaiser comparision
        String find = searchField.getText().toLowerCase();
        // Focus the text area, otherwise the highlighting won't show up
        textArea.requestFocusInWindow();
        // Make sure we have a valid search term
        if (find != null && find.length() > 0) {
            Document document = textArea.getDocument();
            int findLength = find.length();
            try {
                boolean found = false;
                // Rest the search position if we're at the end of the document
                if (pos + findLength > document.getLength()) {
                    pos = 0;
                }
                // While we haven't reached the end...
                // "<=" Correction
                while (pos + findLength <= document.getLength()) {
                    // Extract the text from the docuemnt
                    String match = document.getText(pos, findLength).toLowerCase();
                    // Check to see if it matches or request
                    if (match.equals(find)) {
                        found = true;
                        break;
                    }
                    pos++;
                }
                // Did we find something...
                if (found) {
                    // Get the rectangle of the where the text would be visible...
                    Rectangle viewRect = textArea.modelToView(pos);
                    // Scroll to make the rectangle visible
                    textArea.scrollRectToVisible(viewRect);
                    // Highlight the text
                    textArea.setCaretPosition(pos + findLength);
                    textArea.select(pos, pos + findLength);
                    textArea.grabFocus();

                }

            } catch (Exception exp) {
                exp.printStackTrace();
            }
        }
    }));

Answer:

There are two ways to search through the text for matches in your JTextArea:

  1. Use String.indexOf(idx) [forward] and String.lastIndexOf(idx) [backward] on the document text, where idx is the current caret location. You may also want to use String.toUppercase / toLowercase on both the search text and the document text if you don't want your searching to be case sensitive.

  2. Use Matcher/Pattern for regular expression searching. This is the more powerful but complicated solution. And just FYI, I am working on rolling out a DHTML solution and for the longest time I wanted to include regex searching. But in the end I didn't - I don't think customers (unless they are internal maybe) care about learn how to write regexes

Question:

I have been wondering if it is possible to update JFrame or JDialogs based on the inputs inside jtextarea without button click. For an example, after i input some text in textarea. it should automatically update jlabel without the need of a button. I have search troughout but all the information i found is only based on button click . For an example ,

JFrame frame = new JFrame();
    frame.setLayout(new GridLayout(0, 1));
    JTextArea input = new JTextArea();
    JLabel output = new JLabel("test");

    // Condition 
    // If user input "abc" inside textfield
    // JLabel will automatically display "abc"

    frame.add(input);
    frame.add(output);
    frame.setSize(300,400);
    frame.setVisible(true);

Do i need to refresh the entire frame ? will it affect all the other textfield that user have already fill back to empty?

Thanks


Answer:

Document object contained by JTextArea receives updates.

JTextArea input = new JTextArea();
input .getDocument().addDocumentListener(new DocumentListener() {

    @Override
    public void removeUpdate(DocumentEvent e) {}

    @Override
    public void insertUpdate(DocumentEvent e) {}

    @Override
    public void changedUpdate(DocumentEvent arg0) {
            //Add logic here to check if particular word is entered.
            //if yes show label, else hide the label object 
    }
});

Question:

I'm trying to enable changing the text of my JTextArea from outside the GUI-class. I think I know how I'm supposed to do it, it just doesn't work.

I declare and initialize the JTextArea like this:

JTextArea typeField = new JTextArea();

And then I have this method inside my GUI-class (but outside of the constructor, of course):

public void setText(String text){
    typeField.append(text);
}

I read in another thread here that this is how you're supposed to do. But the compiler doesn't approve of this, and says "typeField cannot be resolved" on the line where I use the append method. I think what I'm trying to accomplish is quite simple and I really don't get why this doesn't work. Maybe I've done some silly mistake? If so, I can't find it.

Thanks in advance.

Edit: I'm going to post my code here anyway, hoping someone will be able to help me! So what I'm trying to do is implement the client part of a chat program. I have two parts. The chat client part and the GUI part.

The chat part:

package chat;

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

public class ChatClient{
  public static void main(String [] args) throws IOException {

    //ChatWindow chatWindow = new ChatWindow();

    //Default values.
    String host = "127.0.0.1";
    int port = 2000;

    //If the user starts the program with "java ChatClient <host>"
    if (args.length == 1) {
        host = args[0]; //Catches the first parameter.                
    }

    //If the user starts the program with "java ChatClient <host> <port>"
    else if (args.length == 2) {
        host = args[0]; //Catches the first parameter.
        port = Integer.parseInt(args[1]); //Catches the second parameter.
    }

    //If the user sends too many parameters.
    else if (args.length > 2) {
        System.out.println("You have sent too many parameters.");
        System.exit(1);
    }

    //Sets the host and port as the titel of the window.
    //chatWindow.setWindowTitle(host + " " + port);

    try (   
        Socket socket = new Socket(host, port);

        PrintWriter out = 
            new PrintWriter(socket.getOutputStream(), true);
        BufferedReader in = 
            new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
        BufferedReader stdIn =
            new BufferedReader(
                new InputStreamReader(System.in))
    ) {
        String userInput;
        while ((userInput = stdIn.readLine()) != null) {
            out.println(userInput);
            System.out.println("Server: " + in.readLine());
        }
    } catch (UnknownHostException e) {
        System.err.println("Couldn't not find host " + host);
        System.exit(1);
    } catch (IOException e) {
        System.err.println("Couldn't get I/O for the connection to " + host);
        System.exit(1);
    }
}
}

And the GUI part (these two classes are defined in the same file, so I don't need to repeat the imported librarys):

class ChatWindow extends JFrame {
public ChatWindow () {
    setLayout(new BorderLayout());

    //A JPanel containing the "message board";
    JPanel messageBoard = new JPanel(new FlowLayout());

    //A JTextArea showing all the messages.
    JTextArea messageField =  new JTextArea();
    messageField.setPreferredSize(new Dimension(470, 300));
    messageField.setMargin(new Insets(10, 10, 10, 10));
    messageBoard.add(messageField);
    add(messageBoard, BorderLayout.NORTH);

    //A JPanel containing the TextField where the user writes his messages as well as the button to send these messages
    JPanel typeBoard = new JPanel(new FlowLayout());

    //A JTextArea where the user writes his messages.
    JTextArea typeField = new JTextArea();
    typeField.setPreferredSize(new Dimension(350, 100));
    typeField.setMargin(new Insets(10, 10, 10, 10));
    typeBoard.add(typeField);

    //A button used to send a message.
    JButton sendButton = new JButton("Send");
    sendButton.setPreferredSize(new Dimension(100, 100));
    typeBoard.add(sendButton);

    add(typeBoard, BorderLayout.SOUTH);

    setSize(500, 470);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);        
}

public void setText (String text) {
    messageField.append("\n" + text);
}

public void setWindowTitle (String title) {
    setTitle(title);
}
}

class SendButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e){
        //Not implemented yet
    }
}

Answer:

I'm not sure but you can try this :

public synchronized void setText(String text){
    typeField.append(text);
}

synchronized will synchro the two threads. You can read more here : Docs Oracle