简体   繁体   中英

JTextArea doesn't show up

public class Server extends JFrame{
    private JLabel ipLabel;
    private JTextField ipTextField;
    private JLabel portLabel;
    private JTextField portTextField;

    private JTextArea messagesTextArea;

    public Server(String title){
        super(title);

        setLayout(new GridBagLayout());
        Container container = getContentPane();
        GridBagConstraints gc = new GridBagConstraints();

        ipLabel = new JLabel("IP Address: ");
        gc.gridx = 0;
        gc.gridy = 0;
        container.add(ipLabel, gc);

        ipTextField = new JTextField();
        ipTextField.setColumns(15);
        gc.gridx = 1;
        gc.gridy = 0;
        container.add(ipTextField, gc);

        portLabel = new JLabel("Port: ");
        gc.gridx = 2;
        gc.gridy = 0;
        container.add(portLabel, gc);

        portTextField = new JTextField();
        portTextField.setColumns(4);
        gc.gridx = 3;
        gc.gridy = 0;
        container.add(portTextField, gc);

            // I think this is the problem
        messagesTextArea = new JTextArea();
        gc.gridx = 0;
        gc.gridy = 1;
        container.add(messagesTextArea, gc);
    }
}

JTextArea doesn't show up. I am using GridBagLayout. This is my code. What's the problem?

Here's my main method.

public class MainFrame {

    private static Server server;

    public static void main(String[] args) {    
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {

                server = new Server("Server");
                server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                server.setBounds(dimension.width/4, dimension.height/4, dimension.width/2, dimension.height/2);
                server.setVisible(true);
            }
        });
    }
}

Always add JTextArea to JScrollPane otherwise it will create a problem when the no of rows in text area is greater than frame's height.

    JScrollPane jScrollPane=new JScrollPane(messagesTextArea);
    container.add(jScrollPane, gc);

and try

    gc.fill=GridBagConstraints.BOTH;
    gc.weighty=0.9;
    gc.weightx=0.8;

use weighty and weightx to set the size in percent of the component.

use fill to fill all the available space either horizontally or vertically or both.

For more info have a look at How to Use GridBagLayout

Instead of calling the empty constructor use JTextArea(int, int) to set the row and column size like this:

// JTextArea with 1 row and 50 columns
messagesTextArea = new JTextArea(1,50);

the constructor without arguments creates a JTextArea with 0 rows and 0 columns hence you see nothing.

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