我正在尝试在一个JList中使用一个DefaultListModel来处理一个通用的JScrollPane。然而,我看不到JList。
这是一堂课:
FieldScrollList:
public class FieldScrollList<T> extends JScrollPane {
private DefaultListModel<T> listModel;
public int length () {
return listModel.size();
}
public FieldScrollList () {
setBorder(new TitledBorder(this.getClass().getSimpleName()));
setBackground(Color.PINK);
listModel = new DefaultListModel<>();
JList<T> jList = new JList<>(listModel);
add(jList);
jList.setBorder(new TitledBorder(jList.getClass().getSimpleName()));
}
public void clear () {
listModel.clear();
}
public void push(T t) {
listModel.add(length(),t);
}
public <C extends Collection<T>> void pushAll(C coll) {
coll.forEach(this::push);
}
public void pushAll(T[] coll) {
for (T t : coll) {
push(t);
}
}
}这是使用它的类。在本例中,我是一个FieldScrollList,它应该显示列表项: hi和hello。
public class test {
public static void main(String[] args) {
new Thread(() -> {
//---------------------------------- Content initialization ------------------
JFrame frame = new JFrame("Test");
JPanel panel = new JPanel();
FieldScrollList<String> list = new FieldScrollList<String>();
//---------------------------------- Strings initialization ------------------
ArrayList<String> strings = new ArrayList<>();
strings.add("Hello");
strings.add("Hi");
strings.forEach(list::push);
//---------------------------------- JPanel configuration --------------------
panel.setLayout(new GridLayout(1,1));
panel.add(list);
//---------------------------------- JFrame configuration --------------------
frame.add(panel);
frame.setPreferredSize(new Dimension(550,600));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}).start();
}
}其结果是:

边框和设置背景的目标是显示内容的位置和区域(视觉)。
我不明白为什么不显示这些字段
发布于 2016-05-04 15:08:13
不要扩展JScrollPane。您不会向滚动窗格添加任何功能。所有这些方法都与ListModel相关,与JScrollPane无关。
add(jList);不要向滚动窗格添加组件。JScrollPane是一个包含JScrollBars和JViewport的复合组件。需要将JList添加到视图端口。
不要将JList添加到面板中。您需要将JScrollPane添加到面板中
这通常是用基本代码完成的,如下所示:
JScrollPane scrollPane = new JScrollPane( list );
panel.add( scrollPane );发布于 2016-05-04 15:10:11
您是在EDT上创建和操作Swing对象的。您的Runnable应该由SwingUtilities.invokeLater在静态void中调用。
https://stackoverflow.com/questions/37031376
复制相似问题