Reputation: 2042
I have a JPanel that I create like so
JPanel statsKeysPanel = new JPanel(new MigLayout("insets 0", "[]", ""));
and populate with a dynamic number of JLabels stacked on top of each other. For the sake of an example:
for(int i = 0; i < 30; i++) {
statsKeysPanel.add(new JLabel("" + i + " key value"), "wrap");
}
I then create and add the scroller like so
JPanel panel = new JPanel(new MigLayout("insets 0", "[center][][center][]", "[][]"));
final JScrollPane keysScroller = new JScrollPane(this.statsKeysPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
keysScroller.setMaximumSize(new Dimension(100, 300));
panel.add(keysScroller, "cell 0 1");
The max of 300 is applied but the 15 out of 30 JLabels that don't fit in 300px are hidden, and scrolling doesn't work. What am I doing wrong? (image below)
Upvotes: 0
Views: 2155
Reputation: 11627
You are using unnecessarily two panels; one will suffice. I think that you have omitted the code that caused your error.
Here is a working example:
package com.zetcode;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;
public class StatsKeyEx extends JFrame {
public StatsKeyEx() {
initUI();
}
private void initUI() {
JPanel pnl = new JPanel(new MigLayout());
for (int i = 0; i < 60; i++) {
pnl.add(new JLabel("" + i + " key value"), "wrap");
}
JScrollPane spane = new JScrollPane(pnl);
spane.setPreferredSize(new Dimension(150, 200));
add(spane);
pack();
setTitle("Scrolling");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
StatsKeyEx ex = new StatsKeyEx();
ex.setVisible(true);
}
});
}
}
The scrollbars are shown as needed.
Upvotes: 0
Reputation: 324078
final JScrollPane keysScroller = new JScrollPane(this.statsKeysPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
Why are you using NEVER
for both the horizontal and vertical scrollbar? I would think this would prevent a scrollbar from appearing.
I generally don't set either property and just let the scrollpane determine when to display the scrollbar. Sometimes I use ALWAYS
to reserve space for the scrollbar.
Upvotes: 2