I have a GUI that consists of multiple JList components on a panel, which is on a JScrollPane. The scroll pane makes it possible to scroll all of the lists at once. However, when I use MigLayout on the panel containing the lists I am unable to scroll past the first 1819 list elements. The limitation appears to be related to the height of the list, not the number of elements. If I use larger element sizes I can scroll less elements. I'm currently using MigLayout 4.2.
Here is a simplified example that exhibits this behavior.
import net.miginfocom.swing.MigLayout;
import javax.swing.*;
import java.awt.*;
public final class MigLayoutListTest {
public static void main(final String... args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
final String[] listData = new String[5000];
for (int i = 0; i < 5000; i++) {
listData[i] = "Index " + i;
}
final JPanel panel = new JPanel(new MigLayout());
panel.add(new JList(listData));
final JFrame frame = new JFrame();
frame.setContentPane(new JScrollPane(panel));
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(600, 400));
frame.pack();
frame.setVisible(true);
}
});
}
}
If I eliminate the JPanel and put the JList directly on the JScrollPane then scrolling works correctly, but I cannot use this workaround since I need multiple lists on the same JScrollPane. If I use any layout other than MigLayout for the JPanel then scrolling works correctly.
Is this a bug or limitation of MigLayout? Is there some configuration option that needs to be applied to MigLayout in order to get it working correctly?
I think your approach is kludgy. Rather, use JLists in their own JScrollPane and synch up the scrolling:
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ScrollingDemo implements Runnable
{
public static void main(String args[])
{
SwingUtilities.invokeLater(new ScrollingDemo());
}
public void run()
{
JScrollPane sp1 = new JScrollPane(getJList(1));
sp1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollPane sp2 = new JScrollPane(getJList(3));
sp2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
JScrollBar sBar1 = sp1.getVerticalScrollBar();
JScrollBar sBar2 = sp2.getVerticalScrollBar();
// synchronize:
sBar2.setModel(sBar1.getModel());
JPanel p = new JPanel(new GridLayout(1,2));
p.add(sp1);
p.add(sp2);
JFrame frame = new JFrame("Synch Scrolling");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(p, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public JList getJList(int factor)
{
Vector<String> items = new Vector<String>();
for(int i = 0; i < 5000; i++)
{
items.add(Integer.toString((i+1)*factor));
}
JList list = new JList(items);
list.setPrototypeCellValue("XXXXXXXXXX");
list.setVisibleRowCount(10);
return list;
}
}
If only want to see 1 vertical scrollbar, just set the scrollbar policy to JScrollPane.VERTICAL_SCROLLBAR_NEVER on the ones you want to hide.
NOTE: This assumes that each JList has the same number of elements. If you had multiple lists of varying length, you'd probably (instead) need to add an AdjustmentListener to the vertical scrollbars.
EDIT: Example:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class ScrollingDemo2 implements Runnable
{
public static void main(String args[])
{
SwingUtilities.invokeLater(new ScrollingDemo2());
}
public void run()
{
JScrollPane sp1 = new JScrollPane(getJList(100));
sp1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
JScrollPane sp2 = new JScrollPane(getJList(200));
sp2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
// synchronize:
sp2.getVerticalScrollBar().addAdjustmentListener(new Synchronizer(sp1, sp2));
JPanel p = new JPanel(new GridLayout(1,0));
p.add(sp1);
p.add(sp2);
JFrame frame = new JFrame("Synch Scrolling 2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(p, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public JList getJList(int count)
{
Vector<String> items = new Vector<String>();
for(int i = 0; i < count; i++)
{
items.add(Integer.toString(i+1));
}
JList list = new JList(items);
list.setPrototypeCellValue("XXXXXXXXXX");
list.setVisibleRowCount(10);
return list;
}
class Synchronizer implements AdjustmentListener
{
JScrollPane sp1, sp2;
public Synchronizer(JScrollPane sp1, JScrollPane sp2)
{
this.sp1 = sp1;
this.sp2 = sp2;
}
public void adjustmentValueChanged(AdjustmentEvent e)
{
if (! e.getValueIsAdjusting())
{
return;
}
JScrollBar vert1 = sp1.getVerticalScrollBar();
JScrollBar vert2 = sp2.getVerticalScrollBar();
int range1 = vert1.getMaximum() - vert1.getMinimum() -
vert1.getModel().getExtent();
int range2 = vert2.getMaximum() - vert2.getMinimum() -
vert2.getModel().getExtent();
float percent2 = (float) (vert2.getValue()) / range2;
int newVal1 = (int) (percent2 * range1);
vert1.setValue(newVal1);
}
}
}
Related
i have a problem with adding a specific number of buttons from my for-loop to my JPanel, i know how to add all oof them, but i want to add only 1-10 (i havent decided yet, lets go with 10).'
this is my class where i just declare what objects i want to have.
private static int cID;
private static Deck[] card;
static ArrayList<JButton> buttonList = new ArrayList<JButton>();
private JFrame f;
private JPanel p1;
private JButton button;
public boolean isEmpty() {
return cID == 0;
}
public static void main(String[] args) {
CustomDecks c = new CustomDecks();
c.deckCreator();
}```
this is my for-loop where i create 420 buttons and give them names "card" + i where i is 0 - 419, yet when i try to add card0 to my panel, it fails, why?
private void deckCreator() {
card = new Deck[25];
new ArrayList<Cards> (cSet.cards);
for(int i = 0; i < 420; i++) {
button = new JButton();
buttonList.add(button);
button.setName("card" + i);
f.add(button);
p1.add(card0);
}
f.add(p1);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setVisible(true);
f.setExtendedState(Frame.MAXIMIZED_BOTH);
f.setUndecorated(true);
}
}
}
I'm not sure you can create a JPanel large enough to hold 420 JButtons.
Here's an example of a JButton GUI.
[
Generally, you create an application model and view separately. The model is made up of one or more plain Java classes. The view reads from the application model but doesn't update the model.
Your controller classes (ActionListener classes) update the application model and update / repaint the view.
This pattern is called the model / view / controller (MVC) pattern.
You can see in the example code below that the model is created in the view class constructor. Generally, you create the application model first, then you create the application view.
And here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
public class JButtonScrollGUI {
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new JButtonScrollGUI();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private String[] greekAlphabet;
public JButtonScrollGUI() {
this.greekAlphabet = new String[] { "alpha", "beta", "gamma", "epsilon", "zeta" };
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setTitle("Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createScrollPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createScrollPanel() {
JPanel panel = new JPanel(new BorderLayout());
JPanel innerPanel = createButtonPanel();
Dimension d = innerPanel.getPreferredSize();
d.width += 50;
d.height /= 2;
panel.setPreferredSize(d);
JScrollPane scrollPane = new JScrollPane(innerPanel);
panel.add(scrollPane, BorderLayout.CENTER);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(0, 3, 10, 10));
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
for (int i = 0; i < 20; i++) {
JButton button1 = new JButton("Previous " + i);
panel.add(button1);
JComboBox<String> selectorBox = new JComboBox<>(greekAlphabet);
panel.add(selectorBox);
JButton button2 = new JButton("Next " + i);
button2.setPreferredSize(button1.getPreferredSize());
panel.add(button2);
}
return panel;
}
}
How I can create a JPanel with a lot of buttons aligned float left and with vertical scrollbars only?
The buttons should be sorted like below.
1 2 3 4
5 6 7 8
9 10 11 12
If you use GridLayout, then you will not be able to add a scrollpane since it will resize automatically to fit all the components inside of it. An easier approach is to use a FlowLayout and setPreferredSize(...) to set the size of your panel. Though it is not advised to set the size of panels, you still need to have the scrollbar put into use somehow. Here is a MCVE:
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class Example extends JFrame {
private final int BUTTON_WIDTH = 100;
private final int BUTTON_HEIGHT = 50;
private final int BUTTON_ROWS = 3;
private final int BUTTON_COLUMNS = 4;
private final int OFFSET = 20;// the width of the actual scroll bar in pixels (approximately).
private final int PANEL_WIDTH = BUTTON_WIDTH * BUTTON_COLUMNS + OFFSET;
private final int PANEL_HEIGHT = BUTTON_HEIGHT * BUTTON_ROWS + OFFSET;
private final int SCROLL_HEIGHT = 100;//or whatever you would like...
private final JButton[] buttons = new JButton[BUTTON_ROWS * BUTTON_COLUMNS];
public Example() {
JPanel panel = new JPanel(new FlowLayout());
JScrollPane scroll = new JScrollPane(panel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
panel.setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
scroll.setPreferredSize(new Dimension(PANEL_WIDTH + OFFSET, SCROLL_HEIGHT));
for (int i = 0; i < buttons.length; i++) {
JButton button = new JButton((i + 1) + "");
buttons[i] = button;
button.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
panel.add(button);
}
//if you want the panel to resize when window is stretched.
//setLayout(new FlowLayout(FlowLayout.CENTER));
add(scroll);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Example();
}
}
Add the buttons to a (panel with a) grid layout to arrange them in rows and columns. Add that panel to a scroll pane, then add the scroll pane to the line start constraint of a border layout, and they will appear on the left.
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class LeftAlignedButtonGrid {
private JComponent ui = null;
LeftAlignedButtonGrid() {
initUI();
}
public void initUI() {
if (ui!=null) return;
/* BorderLayout offers a LINE_START constraint that will put a
single child component on the left hand side of the GUI (in any
locale that uses left-to-right text orientation) */
ui = new JPanel(new BorderLayout(4,4));
JPanel buttonPanel = new JPanel(new GridLayout(0,4,2,2));
for (int ii=1; ii<13; ii++) {
buttonPanel.add(new JButton("" + ii));
}
ui.add(new JScrollPane(buttonPanel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER),
BorderLayout.LINE_START);
ui.setBorder(new EmptyBorder(4,4,4,4));
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
LeftAlignedButtonGrid o = new LeftAlignedButtonGrid();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
// comment this out to allow the height of the GUI to be reduced,
// thus making the vertical scroll bar to have a purpose!
//f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
I have created a setup of buttons using Box.
The problem is there are gaps between all the buttons.
Below is an MCVE version of my code. What I want to achieve is that the buttons "ONE" and "TWO" are touching side by side, with no gap, and buttons "ONE and "ONE" are touching top to bottom with no gap, and for this to continue throughout the setup.
I have read about glue and have tried to use it, but I have not been able to work it out. I am not able to use another layout other than Box as it will not fit in with the rest of my project.
public class Customers {
public static JFrame frame = new JFrame();
public static void frameGui(JPanel panel, String name){
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.setSize(1200,500);
frame.setVisible(true);
}
public static void ScrollCustomersGui(){
Box box = Box.createVerticalBox();
box.add(customersTableHeadings(box));
box.add(customersTableHeadings(box));
box.add(customersTableHeadings(box));
box.add(customersTableHeadings(box));
JScrollPane scroll = new JScrollPane(box);
JPanel All = new JPanel(new BorderLayout());
All.add(scroll);
frameGui(All, "Customers");
}
public static JPanel customersTableHeadings(Box panel){
Font font = new Font("Courier", Font.BOLD,12);
JPanel customersTable = new JPanel();
JButton custid = new JButton("ONE");
JButton surname = new JButton("TWO");
customersTable.add(custid);
customersTable.add(surname);
return customersTable;
}
}
BoxLayout is designed to distribute unused space among components; struts, glue and filler won't change this. You can use the approach suggested here and here to alter the preferred size of the enclosing scroll pane. More generally, you can implement the scrollable interface. In addition, Swing GUI objects should be constructed and manipulated only on the event dispatch thread.
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/** #se https://stackoverflow.com/a/26829171/230513 */
public class Customers {
private static final int N = 16;
private void display() {
Box box = Box.createVerticalBox();
for (int i = 0; i < N; i++) {
box.add(customersTableHeadings());
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JScrollPane(box) {
int w = box.getPreferredSize().width;
int h = box.getPreferredSize().height;
#Override
public Dimension getPreferredSize() {
return new Dimension(9 * w / 8, h / 3);
}
});
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private JPanel customersTableHeadings() {
JPanel customersTable = new JPanel();
JButton custid = new JButton("ONE");
JButton surname = new JButton("TWO");
customersTable.add(custid);
customersTable.add(surname);
return customersTable;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new Customers().display();
});
}
}
I found the answer myself. By adding the horizontal and vertical inside the same loop, and by enclosing this in a JApplet it closes the gap.
Below is a full working version of the code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Box1 extends JApplet {
public void init() {
Box bv = Box.createVerticalBox();
box(bv);
JScrollPane scroll = new JScrollPane(bv);
JPanel All = new JPanel(new BorderLayout());
All.add(scroll);
Container cp = getContentPane();
cp.add(All);
}
public static void main(String[] args) {
frameGui(new Box1(), "Customers");
}
public static void frameGui (JApplet applet, String name) {
JFrame frame = new JFrame();
frame.getContentPane().removeAll();
frame.setTitle(name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(applet);
frame.setSize(1200, 500);
applet.init();
applet.start();
frame.setVisible(true);
}
public static Box box(Box boxvert){
for (int i = 0; i < 50; i++){
JTextField one = new JTextField("ONE");
one.setMaximumSize(new Dimension (150,20));
JTextField two = new JTextField("TWO");
two.setMaximumSize(new Dimension (150,20));
Box horizontalBox = Box.createHorizontalBox();
horizontalBox.add(one);
horizontalBox.add(two);
boxvert.add(horizontalBox);
}
return boxvert;
}
}
I have a JTabbedPane with 2 JPanels set to GridLayout(13, 11). The first JPanel has enough of the cells filled out that it leaves the empty cells.
The second JPanel has significantly fewer cells filled and this results in each button getting stretched to fill an entire row.
Is there any way to get GridLayout to honor the empty cells, so the buttons in both JPanels are the same size?
Is there any way to get GridLayout to honor the empty cells, so the buttons in both JPanels are the same size?
It is certainly doable with GridLayout, simply 'fill' the blank squares with a JLabel that has no text.
E.G. Here are two grid layouts, both padded to 3 rows.
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.border.LineBorder;
class FillGridLayout {
public static final JComponent getPaddedGrid(
ArrayList<BufferedImage> images, int width, int height) {
JPanel p = new JPanel(new GridLayout(height, width, 2, 2));
p.setBorder(new LineBorder(Color.RED));
int count = 0;
for (BufferedImage bi : images) {
p.add(new JButton(new ImageIcon(bi)));
count++;
}
for (int ii=count; ii<width*height; ii++ ) {
// add invisible component
p.add(new JLabel());
}
return p;
}
public static void main(String[] args) {
final ArrayList<BufferedImage> images = new ArrayList<BufferedImage>();
int s = 16;
for (int ii = s/4; ii < s; ii+=s/4) {
images.add(new BufferedImage(ii, s, BufferedImage.TYPE_INT_RGB));
images.add(new BufferedImage(s, ii, BufferedImage.TYPE_INT_RGB));
}
Runnable r = new Runnable() {
#Override
public void run() {
JPanel gui = new JPanel(new BorderLayout(3,3));
gui.add(getPaddedGrid(images, 3, 3), BorderLayout.LINE_START);
gui.add(getPaddedGrid(images, 4, 3), BorderLayout.LINE_END);
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency
SwingUtilities.invokeLater(r);
}
}
Use nested layouts to get your desired result. Some layouts respect the preferred size of components and some don't. GridLayout is one of the ones that don't. Have a look at this answer to see which one's do and which one's don't.
For example, you could nest the 13 buttons in a GridLayout nested in another JPanel with a FlowLayout
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel p2 = new JPanel(new GridLayout(13, 1));
for (int i = 0; i < 13; i++) {
p2.add(new JButton("Button " + i));
}
p1.add(p2);
import java.awt.FlowLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Test6 {
public Test6() {
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel p2 = new JPanel(new GridLayout(13, 1));
for (int i = 0; i < 13; i++) {
p2.add(new JButton("Button " + i));
}
p1.add(p2);
JFrame frame = new JFrame("Test Card");
frame.add(p1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Test6 test = new Test6();
}
});
}
}
add empty JLabel to the empty cell
content.add(new JLabel(""));
I want to add multiple jpanels to jpanel.So i added a root panel to jscrollpane.and then added all individual jpanels to this root panel.I made jscrollpane's scrolling policy as needed.i.e HORIZONTAL_SCROLLBAR_AS_NEEDED,VERTICAL_SCROLLBAR_AS_NEEDED.
But the problem is all individual panels are not shown inside root panel.
Code:
JScrollPane scPanel=new JScrollPane();
JPanel rootPanel=new JPanel();
rootPanel.setLayout(new FlowLayout());
JPanel indPanel = new JPanel();
rootPanel.add(indPanel);
JPanel indPanel2 = new JPanel();
rootPanel.add(indPanel2);
//.....like this added indPanals to rootPanel.
scPanel.setViewPortView(rootPanel);
//scPanel.setHorizontalScrollPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED);
And one more thing is, as i scroll the scrollbar the panels are going out of jscrollpane area.
I am not able to see all individual panels,
Please suggest me.
Edit: code snippet from double post:
MosaicFilesStatusBean mosaicFilesStatusBean = new MosaicFilesStatusBean();
DefaultTableModel tableModel = null;
tableModel = mosaicFilesStatusBean.getFilesStatusBetweenDates(startDate, endDate);
if (tableModel != null) {
rootPanel.removeAll();
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
for (int tempRow = 0; tempRow < tableModel.getRowCount(); tempRow++) {
int fileIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 0).toString());
String dateFromTemp = tableModel.getValueAt(tempRow, 3).toString();
String dateToTemp = tableModel.getValueAt(tempRow, 4).toString();
int processIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 5).toString());
int statusIdTemp = Integer.parseInt(tableModel.getValueAt(tempRow, 6).toString());
String operatingDateTemp = tableModel.getValueAt(tempRow, 7).toString();
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, dateFromTemp, dateToTemp, processIdTemp, statusIdTemp, operatingDateTemp);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
}
The main reason, why you couldn't see your JPanel is that you are using FlowLayout as the LayoutManager for the rootPanel. And since your JPanel added to this rootPanel has nothing inside it, hence it will take it's size as 0, 0, for width and height respectively. Though using GridLayout such situation shouldn't come. Have a look at this code example attached :
import java.awt.*;
import javax.swing.*;
public class PanelAddition
{
private void createAndDisplayGUI()
{
JFrame frame = new JFrame("Panel Addition Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridLayout(0, 1));
JScrollPane scroller = new JScrollPane();
CustomPanel panel = new CustomPanel(1);
contentPane.add(panel);
scroller.setViewportView(contentPane);
frame.getContentPane().add(scroller, BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
for (int i = 2; i < 20; i++)
{
CustomPanel pane = new CustomPanel(i);
contentPane.add(pane);
contentPane.revalidate();
contentPane.repaint();
}
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new PanelAddition().createAndDisplayGUI();
}
});
}
}
class CustomPanel extends JPanel
{
public CustomPanel(int num)
{
JLabel label = new JLabel("" + num);
add(label);
}
#Override
public Dimension getPreferredSize()
{
return (new Dimension(200, 50));
}
}
Don't use FlowLayout for the rootPanel. Instead consider using BoxLayout:
JPanel rootPanel=new JPanel();
// if you want to stack JPanels vertically:
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
Edit 1
Here's an SSCCE that's loosely based on your latest code posted:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.util.Random;
import javax.swing.*;
#SuppressWarnings("serial")
public class PanelsEg extends JPanel {
private static final int MAX_ROW_COUNT = 100;
private Random random = new Random();
private JPanel rootPanel = new JPanel();
public PanelsEg() {
rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS));
JScrollPane scrollPane = new JScrollPane(rootPanel);
scrollPane.setPreferredSize(new Dimension(400, 400)); // sorry kleopatra
add(scrollPane);
add(new JButton(new AbstractAction("Foo") {
#Override
public void actionPerformed(ActionEvent arg0) {
foo();
}
}));
}
public void foo() {
rootPanel.removeAll();
// rootPanel.setLayout(new BoxLayout(rootPanel, BoxLayout.PAGE_AXIS)); // only need to set layout once
int rowCount = random.nextInt(MAX_ROW_COUNT);
for (int tempRow = 0; tempRow < rowCount ; tempRow++) {
int fileIdTemp = tempRow;
String data = "Data " + (tempRow + 1);
MosaicPanel tempPanel =
new MosaicPanel(fileIdTemp, data);
rootPanel.add(tempPanel);
}
rootPanel.revalidate();
rootPanel.repaint(); // don't forget to repaint if removing
}
private class MosaicPanel extends JPanel {
public MosaicPanel(int fileIdTemp, String data) {
add(new JLabel(data));
}
}
private static void createAndShowGui() {
PanelsEg mainPanel = new PanelsEg();
JFrame frame = new JFrame("PanelsEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
This SSCCE works, in that it easily shows removing and adding JPanels to another JPanel that is held by a JScrollPane. If you're still having a problem, you should modify this SSCCE so that it shows your problem.