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