gpt4 book ai didi

java - 如何使用 GroupLayout 构建表单?

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

使用 GroupLayout 在 Java 中构建表单的最简单方法是什么?对于表单,我指的是前面带有标签的文本字段。像这样:

Form screenshot

最佳答案

使用 Group Layout ,您可以执行以下操作:

package foo;

import javax.swing.*;
import java.awt.*;

public class ChangeIpSettingsDialog extends JDialog
{
public ChangeIpSettingsDialog( Frame owner )
{
super( owner, true );
setContentPane( createContent() );
}

private Container createContent()
{
JPanel result = new JPanel();
result.setBorder( BorderFactory.createEmptyBorder( 10, 10, 10, 10 ) );

// Create the layout
GroupLayout layout = new GroupLayout( result );
result.setLayout( layout );
layout.setAutoCreateGaps( true );

// Create the components we will put in the form
JLabel ipAddressLabel = new JLabel( "IP Address:" );
JTextField ipAddressTextField = new JTextField( 20 );
JLabel subnetLabel = new JLabel( "Subnet:" );
JTextField subnetTextField = new JTextField( 20 );
JLabel gatewayLabel = new JLabel( "Gateway:" );
JTextField gatewayTextField = new JTextField( 20 );

// Horizontally, we want to align the labels and the text fields
// along the left (LEADING) edge
layout.setHorizontalGroup( layout.createSequentialGroup()
.addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING )
.addComponent( ipAddressLabel )
.addComponent( subnetLabel )
.addComponent( gatewayLabel ) )
.addGroup( layout.createParallelGroup( GroupLayout.Alignment.LEADING )
.addComponent( ipAddressTextField )
.addComponent( subnetTextField )
.addComponent( gatewayTextField ) )
);

// Vertically, we want to align each label with his textfield
// on the baseline of the components
layout.setVerticalGroup( layout.createSequentialGroup()
.addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE )
.addComponent( ipAddressLabel )
.addComponent( ipAddressTextField ) )
.addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE )
.addComponent( subnetLabel )
.addComponent( subnetTextField ) )
.addGroup( layout.createParallelGroup( GroupLayout.Alignment.BASELINE )
.addComponent( gatewayLabel )
.addComponent( gatewayTextField ) )
);

return result;
}

public static void main( String[] args )
{
ChangeIpSettingsDialog dialog = new ChangeIpSettingsDialog( null );
dialog.pack();
dialog.setVisible( true );
}
}

关于java - 如何使用 GroupLayout 构建表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11434347/

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