添加滚动条到JList,JList被添加到JPanel
问题描述:
我有一个我想要动态填充的列表,因此需要滚动条。我已经添加了一个滚动条列表。问题是,当我尝试将列表添加到面板。滚动条在列表中变得可见,但即使列表的元素变得更大,它们也不工作。添加滚动条到JList,JList被添加到JPanel
JPanel p4=new JPanel();
Container c=getContentPane();
myList=new JList(model);
myList.setVisibleRowCount(5);
myList.setFixedCellWidth(200);
p4.add(new JScrollPane(myList,ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS));
c.add(p4);
答
这里工作得很好。我用SplitPaneDemo.java文件中查找该SSCCE和
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import java.awt.BorderLayout;
public class SplitPaneDemo extends JPanel {
private JList<String> list;
private String[] imageNames = { "Bird", "Cat", "Dog", "Rabbit", "Pig", "dukeWaveRed",
"kathyCosmo", "lainesTongue", "left", "middle", "right", "stickerface"};
public SplitPaneDemo() {
setLayout(new BorderLayout());
list = new JList<>(imageNames);
list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
list.setSelectedIndex(0);
add(new JScrollPane(list));
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("SplitPaneDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SplitPaneDemo splitPaneDemo = new SplitPaneDemo();
frame.getContentPane().add(splitPaneDemo);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
}
应该按预期工作(请参阅@ Robin的SSCCE) - 您没有显示的代码出现错误... – kleopatra 2012-04-07 08:48:52