GroupLayout - 组件对齐

时间:2017-03-12 16:33:43

标签: java swing alignment layout-manager grouplayout

我在groupLayout中对齐组件时遇到了一些问题。 我想制作一个计算器类型的布局,顶部有6个文本字段,右下6个按钮,排列成2列3行,结果是文本字段,但标签没有与文本字段对齐,但是相同按钮按钮。如果你能提出一些建议,我将不胜感激。谢谢! 这是代码:

Result

public class View extends JFrame{

    JFrame frame = new JFrame("Example");
    JPanel p1 = new JPanel();
    JPanel p2 = new JPanel();
    JPanel p3 = new JPanel();
    JPanel p4 = new JPanel();
    JTextField tf = new JTextField(15);
    JTextField tf1 = new JTextField(15);
    JButton b = new JButton(" + ");
    JButton b1 = new JButton(" - ");
    JTextField tf3 = new JTextField(15);

    public View(){
        frame.setLayout(new FlowLayout());
        GroupLayout layout = new GroupLayout(p1);
         p1.setLayout(layout);
         layout.setAutoCreateGaps(true);
         layout.setAutoCreateContainerGaps(true);

         JLabel label = new JLabel("Polinom 1: ");
            JLabel label1 = new JLabel("Polinom 2: ");

        b.setSize(20,20);
        b1.setSize(20,20);

        b.setFont(new Font("Arial", Font.PLAIN, 50));
        b1.setFont(new Font("Arial", Font.PLAIN, 50));

         layout.setHorizontalGroup(
                   layout.createSequentialGroup()
                      .addComponent(label)
                      .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                               .addComponent(tf)
                               .addComponent(b))
                      .addComponent(label1)
                      .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                              .addComponent(tf1)
                              .addComponent(b1)

                ));
                layout.setVerticalGroup(
                   layout.createSequentialGroup()
                      .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                           .addComponent(label)
                           .addComponent(tf)
                           .addComponent(label1))
                           .addComponent(tf1)

                      .addComponent(b)
                      .addComponent(b1)
                );

        frame.add(p1);

        JLabel l = new JLabel("Rezultat: ");

        p3.add(b);
        frame.pack();
        frame.setSize(500,400);
        // frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
    }
}

0 个答案:

没有答案