Java 如何使JTextArea完全填满JPanel?

Java 如何使JTextArea完全填满JPanel?,java,swing,jpanel,layout-manager,jtextarea,Java,Swing,Jpanel,Layout Manager,Jtextarea,我希望我的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 a

我希望我的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);
    }
}


您使用的是
FlowLayout
,它只会为您的
JTextArea
提供所需的大小。您可以尝试调整
JTextArea
的最小、最大和首选大小,也可以使用一种布局,使
JTextArea
拥有尽可能多的空间<代码>边框布局是一个选项

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);
  }
}

@穆库尔·戈尔:我认为这是不可能的。@JohnH有很多布局。GridLayout也出现在脑海中。从这里开始:加上一个,但是请(你到处都是优秀的海报)1。为什么帧。设置大小(200200);如果存在jta.setRows(10)/setColumns(10);:-),2.或者缺少一个JScrollPane(为什么不指导OP:-)@mKorbel我只是学习了OP代码的基本知识,我认为这只是示例代码。必须直接或通过调用pack()设置JFrame的大小。添加一个JScrollPane超出了这个问题的范围,会让人困惑,所以我把这些东西都说出来了。