简体   繁体   English

如何阻止JTextArea和JTextField拉伸?

[英]How can I stop a JTextArea and JTextField from stretching?

This has probably been answered here, but my searches drew up a blank, perhaps I am looking for the wrong thing. 这可能在这里得到了回答,但是我的搜索划出了一个空白,也许我在寻找错误的东西。

How can I stop a JTextArea and a JTextField from stretching? 如何阻止JTextAreaJTextField拉伸? Does swing provide a panel spacer of some sort which I can add that will be stretched before any other elements will? 秋千是否提供某种我可以添加的,可以在其他任何元素之前拉伸的面板垫片?

I have a JPanel which fills a JFrame with a set size. 我有一个JPanel ,它用设定的大小填充JFrame It uses a BoxLayout set to PAGE_AXIS . 它使用BoxLayout设置为PAGE_AXIS If I add a JTextArea with size 3,100 it ignores these row/columns sizes and fills all the available space. 如果添加大小为3,100的JTextArea ,它将忽略这些行/列的大小,并填充所有可用空间。

Similarly I have a JPanel with a GridLayout . 类似地,我有一个带有GridLayoutJPanel If I add a JTextField , rather than be the size in columns that I specify, it fills the entire space in the grid. 如果添加一个JTextField ,而不是我指定的列中的大小,它将填充网格中的整个空间。

Edit: The drawing below shows what I would like (at the top) and what I get. 编辑:下图显示了我想要的(在顶部)和得到的东西。 在此处输入图片说明

Few words directly from documentation on How to Use GridLayout 关于如何使用GridLayout的文档中没有几句话

A GridLayout object places components in a grid of cells. GridLayout对象将组件放置在单元格的网格中。 Each component takes all the available space within its cell, and each cell is exactly the same size. 每个组件占用其单元中的所有可用空间,并且每个单元的大小完全相同。 If the GridLayoutDemo window is resized, the GridLayout object changes the cell size so that the cells are as large as possible, given the space available to the container. 如果调整GridLayoutDemo窗口的大小,则GridLayout对象将更改单元格大小,以便在给定容器可用空间的情况下,单元格尽可能大。

GridLayout doesn't consider the size of the component. GridLayout不考虑组件的大小。 It tries to fit the component in available space in rows and columns. 它尝试将组件放入行和列的可用空间中。


Try to avoid setting size explicitly. 尽量避免显式设置大小。 There is a very good post about Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing? 关于我是否应该避免在Java Swing中使用set(Preferred | Maximum | Minimum)Size方法,有一篇很好的文章 that can help you to design it in a better way. 可以帮助您更好地设计它。


There are lots of layout managers that can fit as per your requirements. 有很多布局管理器可以满足您的要求。 Please have a look at How to Use Various Layout Managers 请看一下如何使用各种布局管理器


You can use GridBagLayout instead of GridLayout to divide the components in rows and columns just like table layout that gives you more control on grid width, height, margin, padding, column, rows etc. 您可以使用GridBagLayout而不是GridLayout将组件划分为行和列,就像表格布局一样,可以对网格的宽度,高度,边距,填充,列,行等进行更多控制。

In My code I just set the number of columns 在我的代码中,我只是设置列数

JTextField data = new JTextField();
data.setColumns(30);

You cannot do serious layouts withe GridLayout or BoxLayout . 您不能使用GridLayoutBoxLayout进行严肃的布局。 Forget about them. 忘了他们。

The first question is: Are you sure you don't want the JTextArea and JTextField to grow? 第一个问题是:您确定不希望JTextAreaJTextField增长吗? It is a standard in UI that these components are growing and shrinking; 这些组件不断增长和缩小是UI的标准。 the first one in both directions and the second one horizontally. 第一个在两个方向上,第二个在水平方向上。

Anyway, I post solutions for GroupLayout and MigLayout , which are the managers I highly recommend. 无论如何,我都会发布我强烈推荐的管理器GroupLayoutMigLayout解决方案。

a) Solution with GroupLayout a) GroupLayout 解决方案

Each component has three sizes: minimum, preferred, and maximum. 每个组件都有三种尺寸:最小值,首选值和最大值。 These are set to some sensible defaults for each component. 对于每个组件,这些设置为一些合理的默认值。 This is why the JTextField tends to grow horizontally; 这就是JTextField倾向于水平增长的原因。 its maximum value is set to a very large number. 其最大值设置为非常大的数字。

package com.zetcode;

import java.awt.Container;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class GroupLayoutStretchingEx extends JFrame {

    public GroupLayoutStretchingEx() {

        initUI();
    }

    private void initUI() {

        JTextArea area = new JTextArea(12, 20);
        area.setBorder(BorderFactory.createEtchedBorder());
        JLabel input = new JLabel("Input");
        JTextField textField = new JTextField(15);

        createLayout(area, input, textField);

        setTitle("Stretching");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {

        Container pane = getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createParallelGroup(GroupLayout.Alignment.TRAILING)
                .addComponent(arg[0], GroupLayout.DEFAULT_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGroup(gl.createSequentialGroup()
                        .addComponent(arg[1])
                        .addComponent(arg[2], GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );

        gl.setVerticalGroup(gl.createSequentialGroup()
                .addComponent(arg[0], GroupLayout.DEFAULT_SIZE,
                        GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
                .addGroup(gl.createParallelGroup()
                        .addComponent(arg[1])
                        .addComponent(arg[2], GroupLayout.DEFAULT_SIZE,
                                GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
        );

        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() -> {
            GroupLayoutStretchingEx ex = new GroupLayoutStretchingEx();
            ex.setVisible(true);
        });
    }
}

In GroupLayout , you need to set the correct values for the maximum component size in the addComponent() method. GroupLayout ,您需要在addComponent()方法中为最大组件大小设置正确的值。

JTextArea area = new JTextArea(12, 20);

By setting the number of rows and columns for the JTextArea , we set a preffered size for this component. 通过设置JTextArea的行数和列数,我们为此组件设置了首选的大小。 This value is later used by the layout manager in its calculations. 此值稍后由布局管理器在其计算中使用。

b) Solution with MigLayout b)使用MigLayout 解决方案

In MigLayout , we control the resizement of the components with various constraints, such as fill , grow , or push . MigLayout ,我们通过各种约束(例如fillgrowpush控制组件的大小调整。 By not using them, the components do not grow. 通过不使用它们,组件不会增长。

package com.zetcode;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;

public class MigLayoutStretchingEx extends JFrame {

    public MigLayoutStretchingEx() {

        initUI();
    }

    private void initUI() {

        JTextArea area = new JTextArea(12, 20);
        area.setBorder(BorderFactory.createEtchedBorder());
        JLabel input = new JLabel("Input");
        JTextField textField = new JTextField(15);

        createLayout(area, input, textField);

        setTitle("MigLayout example");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {

        setLayout(new MigLayout());

        add(arg[0], "wrap");
        add(arg[1], "split 2");
        add(arg[2], "growx");
        pack();
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            MigLayoutStretchingEx ex = new MigLayoutStretchingEx();
            ex.setVisible(true);
        });
    }
}

And here is the screenshot: 这是屏幕截图:

MigLayout示例的屏幕截图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM