java - 如何让 JTextArea 完全填满 JPanel?

标签 java swing jpanel layout-manager jtextarea

我希望我的 JTextArea 组件完全填满我的 JPanel。正如您在这里看到的,在这张图片中的 JTextArea 周围有一些填充(它是红色的,带有 eclipse 刻的边框):

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

最佳答案

您正在使用 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);
  }
}

关于java - 如何让 JTextArea 完全填满 JPanel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29798739/

相关文章:

java - 如何使用 AffineTransform 的翻译?

java - 在括号之间提取文本的模式

java - 我有一个 JButton 的 2D 数组,但似乎只有一个 JButton 添加到我的面板中

java - 如何使 drawString 居中?

java - 使用RhinoScriptEngine,如何更改javascript关键字 "this"所指的内容?

java - 如何在 JTextPane 中默认将内容滚动到底部?

java - 如何在java中重置面板外观?

java - 盒子里的组件布局很奇怪

java - 在 JPanel 上添加 .GIF 时显示黑色方 block

java - 如何在我刚刚在 Android 中拍摄的图像上放置水印图像?