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:
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);
}
}
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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.