Вопрос

Im trying to surround a JPanel with JScrollPane but it just wont show, why is that? My JPanel is composed of components that are dynamically created. Whenever the user will click a button, a new component will be created thus making the JPanel bigger (by setting the PrefferedSize) . But the JScrollPane wont show. Please help. thank you.

scrpOfPanel = new JScrollPane();
    scrpOfPanel .setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
    scrpOfPanel .setBounds(54, 180, 565, 400);
    panel.add(scrpOfPanel);

    panel = new JPanel();

    panel.setBackground(Color.WHITE);
    panel.setPreferredSize(new Dimension (450, 50));
    panel.setLayout(null);

    scrpOfPanel .setViewportView(panel);
    lblAdd = new JLabel();
    lblAdd.setBounds(420, 6, 38, 25);
    lblAdd.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            count++;
            txtItem= new JTextField();
            txtItemNumber = new JTextField();
            lblRemove = new JLabel();
            l
            panel.add(txtItem);
            panel.add(txtItemNumber);
            panel.add(lblRemove);
            if(count>0){
                x+=30;
                y+=30;
                lblRemove.setBounds(420,6+y, 125, 25);
                txtItem.setBounds(225,6+y, 182, 27);
                txtItemNumber.setBounds(35, 6+y, 182, 27);

                if(panel.getComponentCount() >9){

                panel.setPreferredSize(new Dimension(100+y,50+y));
                panel.add(txtItem);
                panel.add(txtItemNumber);
                panel.add(lblRemove);

                }
            }

        }

    });

    panel.add(lblAdd);
Это было полезно?

Решение

Don't use a null layout. Swing was designed to be used with layout managers.

From what I can tell in you code you are adding a row of 3 components to a panel every time you click a button.

This can easily be down by using layout managers. Maybe start with a main panel that uses a vertical BoxLayout. Then when you click a button you create a panel that uses a horizontal BoxLayout and add your 3 components to this panel. Then add this panel to the main panel.

Then you need to use:

mainPanel.revalidate();
mainPanel.repaint();

To make sure the layout manager is invoked and the components are repainted. Then the layout manager will manage the preferred size for you.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top