如何让JTextArea完全填满JPanel?

zxg*_*ear 3 java swing jpanel jtextarea layout-manager

我希望我的JTextArea组件能够完全填满我的JPanel.正如你在这里看到的那样,在这张照片中,JTextArea周围有一些填充物(带有蚀刻边框的红色):

下面的程序图像.

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*man 9

您正在使用FlowLayout,它只会为您的JTextArea提供所需的大小.您可以尝试摆弄JTextArea的最小,最大和首选大小,也可以使用一个布局,为您的JTextArea提供尽可能多的空间.BorderLayout是一种选择.

JFrame的默认布局是BorderLayout,所以你真正需要做的就是不要专门设置它.JPanel的默认布局是FlowLayout,因此您需要专门设置该布局.它可能看起来像这样:

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);
  }
}
Run Code Online (Sandbox Code Playgroud)