添加Spring布局时,GUI不会显示标签和文本字段

时间:2019-01-27 20:00:35

标签: java swing jframe layout-manager border-layout

我首先使用了网格布局,然后我意识到我想改用弹簧布局。当我添加Spring布局面板时,什么都不想显示

public class ComplexWindow extends JFrame {

    public ComplexWindow() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(10, 10, 300, 420);
        JPanel mainPanel = (JPanel) getContentPane();
        mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        mainPanel.setLayout(new BorderLayout());
        SpringLayout layout = new SpringLayout();
        JPanel textPanel = new JPanel(layout);
        JLabel lblName = new JLabel("Ime:");
        textPanel.add(lblName);
        JTextField txtName = new JTextField();
        txtName.setColumns(10);
        textPanel.add(txtName);
        JLabel lblSurname = new JLabel("Prezime:");
        textPanel.add(lblSurname);
        JTextField txtSurname = new JTextField();
        txtSurname.setColumns(10);
        textPanel.add(txtSurname);
        layout.putConstraint(SpringLayout.EAST, lblName, 5, 
            SpringLayout.WEST, txtName);
        layout.putConstraint(SpringLayout.SOUTH, lblName, 5, 
            SpringLayout.NORTH, lblSurname);
        layout.putConstraint(SpringLayout.SOUTH, txtName, 5, 
            SpringLayout.NORTH, txtSurname);
        layout.putConstraint(SpringLayout.EAST, lblSurname, 5, 
            SpringLayout.WEST, txtSurname);
        mainPanel.add(textPanel, BorderLayout.NORTH);
    }

    public static void main(String [] args) {
        SwingUtilities.invokeLater(() -> {
            ComplexWindow window = new ComplexWindow();
            window.pack();
            window.setVisible(true);
        });
    }
}

1 个答案:

答案 0 :(得分:0)

如本文档所述,SpringLayout不适用于手动布置组件:
https://docs.oracle.com/javase/tutorial/uiswing/layout/spring.html

  

SpringLayout是非常低级的,因此您确实应该   仅将其与GUI构建器一起使用,而不是尝试对   手工进行弹簧布局管理。

而且,以上教程layout.SpringUtilities中使用的实用程序类也不包含在JDK中。

因此,我建议您为此使用GridBagLayout