gpt4 book ai didi

java - 调整组件大小以适应行

转载 作者:行者123 更新时间:2023-11-29 05:04:01 26 4
gpt4 key购买 nike

我在我的代码中使用了 MigLayout

import javax.swing.*;
import java.awt.*;
import net.miginfocom.swing.MigLayout;

public class MCVE
{
JFrame myMainWindow = new JFrame("MCVE");

JPanel mcvePanel = new JPanel();

JTextField tf1 = new JTextField();
JTextField tf2 = new JTextField();
JTextField tf3 = new JTextField();
JTextField tf4 = new JTextField();
JTextField tf5 = new JTextField();

public void runGUI()
{
myMainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

myMainWindow.setLayout(new GridLayout(1,1));

createMCVEPanel();

myMainWindow.getContentPane().add(mcvePanel);

myMainWindow.setVisible(true);
myMainWindow.pack();
}

public void createMCVEPanel()
{
MigLayout layout = new MigLayout("" , "[grow]");
mcvePanel.setLayout(layout);

mcvePanel.add(tf1,"growx, width 100:100:");
mcvePanel.add(tf2,"growx, width 100:100:");
mcvePanel.add(tf3,"growx, width 100:100:,wrap");
mcvePanel.add(tf4,"growx, width 100:100:");
mcvePanel.add(tf5,"growx, width 100:100:");
}

public static void main(String[] args)
{
MCVE mcve = new MCVE();
mcve.runGUI();
}
}

创建布局

3x2

有没有办法自动调整组件的大小,使其产生这样的布局

3xSpread2

不使用类似的代码

mcvePanel.add(tf1,"growx, width 100:100:, span 2");
mcvePanel.add(tf2,"growx, width 100:100:, span 2");
mcvePanel.add(tf3,"growx, width 100:100:, span 2, wrap");
mcvePanel.add(tf4,"growx, width 100:100:, span 3");
mcvePanel.add(tf5,"growx, width 100:100:, span 3");

我希望能够做到这一点,因为它对于 5 个 JTextFields 来说并不太复杂,但是对于大量的 JTextFields,例如 128 个 JTextFields,这不是最有效的方法(不是我会使用这么多的 JTextField)。

最佳答案

不要使用 span,而是使用 split:

mcvePanel.add(tf1,"growx, width 100:100:, split 3");
mcvePanel.add(tf2,"growx, width 100:100:");
mcvePanel.add(tf3,"growx, width 100:100:,wrap");
mcvePanel.add(tf4,"growx, width 100:100:, split 2");
mcvePanel.add(tf5,"growx, width 100:100:");

此外,为了避免显式包装,您可以将其设置为布局约束并改为这样做:

MigLayout layout = new MigLayout("wrap 1", "[grow]");
mcvePanel.setLayout(layout);

mcvePanel.add(tf1, "growx, width 100:100:, split 3");
mcvePanel.add(tf2, "growx, width 100:100:");
mcvePanel.add(tf3, "growx, width 100:100:");
mcvePanel.add(tf4, "growx, width 100:100:, split 2");
mcvePanel.add(tf5, "growx, width 100:100:");

关于java - 调整组件大小以适应行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013869/

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