Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a JTextArea fill up a JPanel completely?

I'd like my JTextArea component to completely fill up my JPanel. As you can see here, there is some padding around the JTextArea (which is colored red with an etched border) in this picture:

Image of program below.

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

public class Example
{
    public static void main(String[] args)
    {
    // Create JComponents and add them to containers.
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();
    JTextArea jta = new JTextArea("Hello world!");
    panel.add(jta);
    frame.setLayout(new FlowLayout());
    frame.add(panel);

    // Modify some properties.
    jta.setRows(10);
    jta.setColumns(10);
    jta.setBackground(Color.RED);
    panel.setBorder(new EtchedBorder());

    // Display the Swing application.
    frame.setSize(200, 200);
    frame.setVisible(true);
    }
}
like image 299
zxgear Avatar asked Dec 08 '25 09:12

zxgear


1 Answers

You're using FlowLayout, which will only give your JTextArea the size that it needs. You can either try fiddling with the min, max, and preferred size of the JTextArea, or you can use a layout that will give your JTextArea as much room as possible. BorderLayout is one option.

The default layout of a JFrame is BorderLayout, so to use that you would need to not set it specifically. The default layout of a JPanel is FlowLayout, so you do need to set that one specifically. It might look something like this:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EtchedBorder;

public class Main{
  public static void main(String[] args){
    // Create JComponents and add them to containers.
    JFrame frame = new JFrame();
    JPanel panel = new JPanel();

    panel.setLayout(new BorderLayout());

    JTextArea jta = new JTextArea("Hello world!");
    panel.add(jta);
    frame.add(panel);

    // Modify some properties.
    jta.setRows(10);
    jta.setColumns(10);
    jta.setBackground(Color.RED);
    panel.setBorder(new EtchedBorder());

    // Display the Swing application.
    frame.setSize(200, 200);
    frame.setVisible(true);
  }
}
like image 108
Kevin Workman Avatar answered Dec 09 '25 21:12

Kevin Workman