使用FlowLayout布局时,JTextField显示为“缝隙”,请解释。

5

请问有人能解释一下,为什么每次我使用FlowLayout布局管理器时,我的文本框都显示为缝隙。

我已经反复研究这个问题很长时间了,但似乎无法确定出错的原因。

我感觉这是一个我一再忽视的简单问题,所以如果有人能向我解释这种现象,我将非常感激。

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class Console
{   
    public Console()
    {
        makeConsole();
    }

    private void makeConsole()
    {
        JFrame console = new JFrame("ArchiveConsole");
        Container base  = console.getContentPane();
        base.setSize(400, 250);
        console.setSize(base.getSize());
        base.setLayout(new FlowLayout(FlowLayout.CENTER, 5,5));

        JTextField tf = new JTextField();
        tf.setSize(base.getWidth(), 25);
        base.add(tf);

        console.setVisible(true);
    }
}
4个回答

10

从Swing布局管理器教程中:

FlowLayout类将组件放置在一行中,大小为它们的首选大小。如果容器中的水平空间不足以将所有组件放在一行中,则FlowLayout类使用多行。如果容器比组件行需要的宽,则默认情况下,该行在容器中水平居中

因此,您需要通过使用setColumns方法来调整文本框的首选大小。

请注意,如果您希望文本字段跨越整个宽度,您可能希望使用另一种布局而不是FlowLayout,原因如上所述

例如,以下代码提供了一个漂亮的JTextField,但我已经硬编码了列数

import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.FlowLayout;

public class TextFieldWithFlowLayout {
  public static void main( String[] args ) {
    EventQueue.invokeLater( new Runnable() {
      @Override
      public void run() {
        JFrame console = new JFrame("ArchiveConsole");
        Container base  = console.getContentPane();
        base.setLayout(new FlowLayout( FlowLayout.CENTER, 5,5));

        JTextField tf = new JTextField();
        tf.setColumns( 20 );
        base.add(tf);
        console.pack();
        console.setVisible(true);
      }
    } );
  }
}

1
使用: JTextField tf = new JTextField(25);
而不是: JTextField tf = new JTextField(); tf.setSize(base.getWidth(), 25);

1
当您使用布局管理器时,请勿尝试手动设置大小和位置。这会与布局管理器的工作冲突。布局管理器根据约束和首选/最小/最大大小调整组件的大小和位置。大多数Swing组件会自动处理,因此通常不应强制其首选大小。
至于您的JTextField,由于它不包含任何文本,因此其首选大小接近于零。使用setColumns指示preferredSize或调用setPreferredSize

谢谢你的指引,我解决了这个问题,现在更接近真正理解布局管理器了。 - TrashCan

0

谢谢!

JTextField函数中使用的参数非常重要!

JPanel panel_buttons = new JPanel(new FlowLayout(FlowLayout.LEFT));
panel_buttons.add(...);
...
panel_buttons.add(...);
JTextField txt_search = new JTextField(20);
panel_buttons.add(txt_search);

如果将20更改为30或更大,可能会找不到它。可能txt_search在下一行。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接