Reputation: 2047
I want to make a scrollbar appear on a JList whenever the frame is resized to be too small for the List itself. So far, this is the code I have. Run it, resize the frame, and notice how no scrollbar ever appears on the JList.
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JListScroll extends JPanel{
JScrollPane listScrollPane;
public JListScroll() {
String[] stringArray = {"Testing","This","Stuff"};
JList<String> rowList = new JList<String>(stringArray);
listScrollPane = new JScrollPane();
listScrollPane.getViewport().setView(rowList);
this.setSize(new Dimension(75,200));
this.add(listScrollPane);
this.doLayout();
}
public static void main(String[] args){
JFrame frame = new JFrame();
JListScroll scrollPanel = new JListScroll();
frame.add(scrollPanel);
frame.setVisible(true);
frame.setSize(new Dimension(75,300));
}
}
Notice how there is a JScrollPane added, but no scroll bar appears on the list when the window gets really small. This is what I want to fix.
Thanks in advance!
Upvotes: 3
Views: 16467
Reputation: 109813
JPanel has implemented FlowLayout
FlowLayout accepting only PreferredSize (in your case hardcoded by setSize)
FlowLayout isn't designated, not implemented any resize JComponents (layed by FlowLayout) together with container, JComponent isn't resizable, stays as it is
don't want to commenting something about your code posted here, see differencies, quite good low level
import java.awt.BorderLayout;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class JListScroll {
private JFrame frame = new JFrame();
private JPanel panel = new JPanel();
private JScrollPane listScrollPane = new JScrollPane();
private String[] stringArray = {"Testing", "This", "Stuff"};
private JList rowList = new JList(stringArray);
public JListScroll() {
rowList.setVisibleRowCount(2);
listScrollPane.setViewportView(rowList);
panel.setLayout(new BorderLayout());
panel.add(listScrollPane);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // EDIT
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JListScroll jListScroll = new JListScroll();
}
});
}
}
Upvotes: 6
Reputation: 4380
You can force the visibility of the (vertical) scroll bar with the method listScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS)
Upvotes: 2