gpt4 book ai didi

java - JTextField 在使用 FlowLayout 时显示为狭缝...请解释

转载 作者:搜寻专家 更新时间:2023-11-01 01:36:47 25 4
gpt4 key购买 nike

谁能给我解释一下,为什么我每次都使用 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);
}
}

最佳答案

来自 Swing 布局管理器教程

The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centered horizontally within the container

因此您需要调整文本字段的首选大小,最好使用 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);
}
} );
}
}

关于java - JTextField 在使用 FlowLayout 时显示为狭缝...请解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10549627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com