Hello,

I'm having a requirement to develop a GUI based JFrame which should have capabilities to add Multiple JPanel on an event occurrence[Ex. button click] and the JFrame should be scrollable.

I tried a lot, but I failed. I also tried to add multiple Jpanel in JScrollpane that also failed. Can somebody help me please?

Thanks in advance,

regards,

Gokul Rangarajan

Dani AI

Generated

Nice call from . Building on that approach, stack your dynamic panels in a single content panel so they stay in order and can stretch to the full width. BoxLayout on Y_AXIS is a good fit for this. After adding a new panel, call revalidate() on the content panel and then repaint(); that tells the scroll pane to recalc its viewport. If you want to auto-scroll to the newly added panel, call scrollRectToVisible on that child.

import java.awt.*;
import javax.swing.*;

public class DynamicPanelsDemo {
  public static void main(String[] args) {
    SwingUtilities.invokeLater(DynamicPanelsDemo::createAndShow);
  }

  private static void createAndShow() {
    JFrame f = new JFrame("Dynamic panels");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JPanel content = new JPanel();
    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));

    JScrollPane scroll = new JScrollPane(content);
    scroll.getVerticalScrollBar().setUnitIncrement(16);

    JButton add = new JButton("Add panel");
    add.addActionListener(e -> {
      JPanel row = new JPanel(new BorderLayout(5, 5));
      row.add(new JLabel("Panel " + (content.getComponentCount() + 1)), BorderLayout.WEST);
      row.add(new JTextField(15), BorderLayout.CENTER);
      // let each row fill available width
      row.setMaximumSize(new Dimension(Integer.MAX_VALUE, row.getPreferredSize().height));

      content.add(row);
      content.revalidate();
      content.repaint();

      SwingUtilities.invokeLater(() -> row.scrollRectToVisible(row.getBounds()));
    });

    f.add(scroll, BorderLayout.CENTER);
    f.add(add, BorderLayout.SOUTH);
    f.setSize(420, 300);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

Tips: keep all Swing changes on the EDT (the example does). For very large numbers of items, a JList/JTable with a custom renderer will scroll more smoothly and use less memory than hundreds of nested JPanels.

Add a single JPanel to the JScrollPane. Use FlowLayout with vertical (or horizontal, depending on which way you want to "scroll") alignment in that JPanel, and add the JPanels that are to be added "dynamically" to that JPanel. Then, don't forget to call validate() and/or repaint() on the JScrollPane.

Thank you masijade its working. Superb.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.