的JList#setVisibleRowCount(...)
工作正常,我在Windows 10使用JDK 1.8.0_141。
寬度
也許JList#setPrototypeCellValue(...)
方法將起作用。
import java.awt.*;
import java.util.*;
import javax.swing.*;
public class ListScrollPaneTest {
public JComponent makeUI() {
int visibleRowCount = 8;
String prototypeCellValue = "mmmmmmmmmmmmmmmmmmmm";
String[] model1 = Collections.nCopies(20, "aaa").toArray(new String[0]);
JList<String> list1 = makeJList(visibleRowCount, prototypeCellValue, model1);
JScrollPane scroll1 = makeTitledScrollPane("Included Groups", list1);
String[] model2 = {"loooooooooooooooooooooooooooooooooooooooooooooong"};
JList<String> list2 = makeJList(visibleRowCount, prototypeCellValue, model2);
JScrollPane scroll2 = makeTitledScrollPane("Excluded Groups", list2);
JPanel p = new JPanel(new GridBagLayout());
p.setOpaque(true);
p.setBackground(Color.GRAY);
GridBagConstraints gb = new GridBagConstraints();
gb.insets = new Insets(15, 15, 15, 15);
gb.gridx = 1;
gb.gridy = 0;
gb.fill = GridBagConstraints.NONE;
p.add(scroll1, gb);
gb.gridx ++;
gb.anchor = GridBagConstraints.CENTER;
gb.fill = GridBagConstraints.NONE;
p.add(scroll2, gb);
return p;
}
private static <E> JList<E> makeJList(int rowCount, E prototypeCellValue, E[] m) {
JList<E> list = new JList<>(m);
list.setVisibleRowCount(rowCount);
list.setPrototypeCellValue(prototypeCellValue);
return list;
}
private static JScrollPane makeTitledScrollPane(String title, JComponent c) {
JScrollPane scroll = new JScrollPane(c);
scroll.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEmptyBorder(), title));
return scroll;
}
public static void main(String... args) {
EventQueue.invokeLater(() -> {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new ListScrollPaneTest().makeUI());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
});
}
}
爲了更好地提供幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –
您可以使用[JList#getPreferredScrollableViewportSize()](https://docs.oracle.com/javase/7/docs/api/javax/swing/JList.html#getPreferredScrollableViewportSize()) – mKorbel