如何在Java Swing中控制JTextField的宽度? [英] How can I control the width of JTextFields in Java Swing?

查看:1043
本文介绍了如何在Java Swing中控制JTextField的宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一行上有几个JTextField,但我不希望它们具有相同的宽度。如何控制宽度并使其中一些宽度比其他宽度更宽?我希望他们一起占据总宽度的100%,所以如果我可以使用某种形状的话会很好。

I am trying to have several JTextFields on a single row, but I don't want them to have the same width. How can I control the width and make some of them wider than others? I want that they together take up 100% of the total width, so it would be good if I could use some kind of weigthing.

我试过 .setColumns()但它没有意义。

这是一个例子,我用三行三字符串应显示在列中:

Here is an example, where I am using three rows with three strings that should appear as in columns:

import java.awt.GridLayout;
import javax.swing.BoxLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class RowTest extends JPanel {

    class Row extends JComponent {
        public Row(String str1, String str2, String str3) {
            this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));

            JTextField fld1 = new JTextField(str1);
            JTextField fld2 = new JTextField(str2);
            JTextField fld3 = new JTextField(str3);

            fld1.setColumns(5); // makes no sense

            this.add(fld1);
            this.add(fld2);
            this.add(fld3);
        }
    }

    public RowTest() {
    this.setLayout(new GridLayout(5,0));

    this.add(new Row("Short", "A long text that takes up more space",
        "Short again"));
    this.add(new Row("Longer but short", "Another long string", "Short"));
    this.add(new Row("Hello", "The long field again",
        "Some info"));
    }

    public static void main(String[] args) {
        new JFrame() {{ this.getContentPane().add(new RowTest());
                            this.pack(); this.setVisible(true); }};
    }

}


推荐答案

所有Swing组件都有首选大小。文本组件的首选大小基于组件的文本。因此,通常组件按其首选大小绘制。

All Swing components have a preferred size. The preferred size of a text component is based on the text of the component. So generally the component is painted at its preferred size.

所以我没有看到您的代码片段存在问题。每个文本字段应具有不同的首选大小。此外,随着帧的大小调整,宽度将被调整,因为BoxLayout将尝试将每个组件的大小调整为其最大/最小大小。

So I don't see the problem with your code snippet. Each text field should have a different preferred size. Also, as the frame is resized the width will be adjusted since the BoxLayout will try to resize each component up to its maximum/minimum size.

如果您需要更多帮助帖子您的 SSCCE 实际上展示了您遇到的尺寸问题。

If you need more help post your SSCCE that actually demonstrates the sizing problem you are experiencing.

编辑:

根据最新要求,您可以使用相对布局

Based on the latest requirement you can use the Relative Layout.

这篇关于如何在Java Swing中控制JTextField的宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆