Tyler B
Tyler B

Reputation: 27

How do I set the size of a JTextArea?

I'm fairly new to working with graphics in Java, and have been trying to make a simple console to display text based games in a window. I have a test class, where I'm working on the console, but when I add a JTextArea to my console window, it either takes up the entire window or doesn't display at all.

Here is my code:

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.Event;
public class GUI {
    public static void main(String[] args) {
        JFrame frame = new JFrame("AoA");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(1020,760);
        frame.setBackground(Color.LIGHT_GRAY);
        frame.setResizable(false);
        JTextArea jta = new JTextArea(100,100);
        jta.setEditable(false);
        jta.setBackground(Color.WHITE);
        frame.add(jta);

    }
}

I know that some of my imports aren't used in this file, but they will used in the final game. I am also aware that the JTextArea is set to size 100,100, which I am unsure whether it is too large or small. I could really use some help on this, though.

Upvotes: 1

Views: 1078

Answers (1)

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

Your problem is the installed by default BorderLayout in your frame. The easiest way to solve your problem is to set another layout manager.

public static void main(String[] args) {
    SwingUtilities.invokeLater(GUI::startUp); 
}

private static void startUp() {
    JFrame frame = new JFrame("AoA");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(1020,760);
    frame.setBackground(Color.LIGHT_GRAY);
    frame.setResizable(false);
    frame.setLayout(new FlowLayout()); // FlowLayout is required
    JTextArea jta = new JTextArea(40,40);
    jta.setEditable(false);
    jta.setBackground(Color.WHITE);
    // JScrollPane to get the scroll bars when required
    frame.add(new JScrollPane(jta));
    // setVisible should be last operation to get a correct painting
    frame.setVisible(true);
}

Please take a look for layout managers in Swing

Upvotes: 5

Related Questions