jdk6中新增的grouplayout,可以简单地处理对齐问题

昨天帮人搞程序的时候发现的

比如说登陆的swing界面,

如何处理用户密码输入label textfield的对齐呢?

自己写定位也行

就是太麻烦

jdk6提供了一个grouplayout

可以简单地实现对齐

不多废话了

直接上测试程序

import javax.swing.*; import javax.swing.GroupLayout.Alignment; public class Test8 { public Test8() { JFrame f = new JFrame(); JPanel panel = new JPanel(); JLabel label1 = new JLabel("用户名:"); JLabel label2 = new JLabel("密码:"); JTextField tf1 = new JTextField(); JTextField tf2 = new JTextField(); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); // Turn on automatically adding gaps between components layout.setAutoCreateGaps(true); // Turn on automatically creating gaps between components that touch // the edge of the container and the container. layout.setAutoCreateContainerGaps(true); // Create a sequential group for the horizontal axis. GroupLayout.SequentialGroup hGroup = layout.createSequentialGroup(); // The sequential group in turn contains two parallel groups. // One parallel group contains the labels, the other the text fields. // Putting the labels in a parallel group along the horizontal axis // positions them at the same x location. // // Variable indentation is used to reinforce the level of grouping. hGroup.addGroup(layout.createParallelGroup().addComponent(label1) .addComponent(label2)); hGroup.addGroup(layout.createParallelGroup().addComponent(tf1) .addComponent(tf2)); layout.setHorizontalGroup(hGroup); // Create a sequential group for the vertical axis. GroupLayout.SequentialGroup vGroup = layout.createSequentialGroup(); // The sequential group contains two parallel groups that align // the contents along the baseline. The first parallel group contains // the first label and text field, and the second parallel group // contains // the second label and text field. By using a sequential group // the labels and text fields are positioned vertically after one // another. vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(label1).addComponent(tf1)); vGroup.addGroup(layout.createParallelGroup(Alignment.BASELINE) .addComponent(label2).addComponent(tf2)); layout.setVerticalGroup(vGroup); f.add(panel); f.setBounds(200, 200, 300, 300); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); } public static void main(String[] args) { new Test8(); } }

你可能感兴趣的:(jdk,swing,layout,import,parallel,Components)