如何使用 BorderLayout (Java) 使 JTextField 展开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/594994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:00:31  来源:igfitidea点击:

How to make JTextField expand with a BorderLayout (Java)

javaswing

提问by Xunil

I have a Java program, in which, I'm using a JTextField, but if i don't specify a default size, it'll have the width 0. I'm inserting it in a BorderLayout, so how do I make it expand to fill the whole container?

我有一个 Java 程序,其中我使用的是 JTextField,但是如果我没有指定默认大小,它的宽度将为 0。我将它插入到 BorderLayout 中,那么我该如何制作呢?展开以填满整个容器?

回答by Ascalonian

In the above example, the text field will work fine. However, if you insert into EAST or WEST, it will not work.

在上面的示例中,文本字段将正常工作。但是,如果插入到 EAST 或 WEST 中,它将不起作用。

import java.awt.BorderLayout;

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


public class TextFieldTest {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        JTextField tf = new JTextField();
        f.getContentPane().add(BorderLayout.EAST, tf);
        f.pack();
        f.setVisible(true);
    }
}

My question back to you is: Does this need to be a BorderLayout or can you use other Layout Managers? If you can, you should check out GridBagLayout that you can have an element auto expand (using a weight) to fit the entire container.

我的问题是:这需要是一个 BorderLayout 还是你可以使用其他布局管理器?如果可以,您应该查看 GridBagLayout,您可以让元素自动展开(使用权重)以适应整个容器。

回答by banjollity

Fill the whole container? With BorderLayout?

填满整个容器?带边框布局?

container.add( jTextField, BorderLayout.CENTER );

Simple as that.

就那么简单。

回答by 01es

When programming with Swing the key thing is to use a good layout manager. For me the perfect layout manager is MigLayout. This is simply the best one-stop solution to all layout needs. Their site provides excellent documentation and examples.

使用 Swing 编程时,关键是使用好的布局管理器。对我来说,完美的布局管理器是MigLayout。这简直是​​满足所有布局需求的最佳一站式解决方案。他们的网站提供了优秀的文档和示例。

回答by tddmonkey

It will automatically fill to the width of the container, example shown:

它将自动填充到容器的宽度,示例如下:

    import java.awt.BorderLayout;

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


public class TextFieldTest {
    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setLayout(new BorderLayout());
        JTextField tf = new JTextField();
        f.add(tf, BorderLayout.SOUTH);
        f.pack();
        f.setVisible(true);
    }
}