Adding JPanel to JScrollPane

前端 未结 3 1211
后悔当初
后悔当初 2021-01-24 12:36

I have a gui which has a Panel that contains a sequence of labels and TextFields and uses a spring layout(this is the mainPanel) and another Panel that just contains a button(bu

3条回答
  •  说谎
    说谎 (楼主)
    2021-01-24 13:03

    This is how I would do it:

    public static void main(String args[]) {
        JFrame frame = new JFrame("SpringLayout");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();
    
        JButton next = new JButton("Next");
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(next);
        GridBagLayout layout = new GridBagLayout();
        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(layout);
        contentPane.setLayout(new BorderLayout());
    
        GridBagConstraints gbc = new GridBagConstraints();
    
        int j = 25;
        for (int i = 0; i < 50; i++) {
            JLabel label = new JLabel("Enter Name (" + i + ")");
            JTextField text = new JTextField(15);
    
            gbc.gridx = 0;
            gbc.gridy = i;
    
            mainPanel.add(label, gbc);
    
            gbc.gridx = 1;
            mainPanel.add(text, gbc);
        }
        contentPane.add(new JScrollPane(mainPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED), BorderLayout.CENTER);
        contentPane.add(buttonPanel, BorderLayout.SOUTH);
        frame.setSize(500, 800);
        frame.setVisible(true);
    }
    

    Few modifications: * use GridBagLayout instead of SpringLayout (just because I don't know SpringLayout) * wrap your mainPanel inside a JScrollPane

    Does not look and feel exactly like your example. GridBagConstraints can be tuned.

提交回复
热议问题