[英]DefaultListModel in JList in JScrollPane, can't see the JList
我正在嘗試使用JScrollPane內部的DefaultListModel處理通用JList。 但是,我看不到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();
}
}
結果是這樣的:
邊框和setbackground的目標是顯示內容的位置和區域(可視化)
我不明白為什么不顯示字段
不要擴展JScrollPane
。 您沒有在滾動窗格中添加任何功能。 所有這些方法都與ListModel
有關,與JScrollPane
無關。
add(jList);
不要將組件添加到滾動窗格中。 JScrollPane
是包含JScrollBars
和JViewport
的復合組件。 JList
需要添加到視口中。
不要將JList
添加到面板中。 您需要將JScrollPane
添加到面板中
通常,這是通過基本代碼完成的,例如:
JScrollPane scrollPane = new JScrollPane( list );
panel.add( scrollPane );
您已創建並處理不在EDT上的Swing對象。 您的Runnable應該由static void main內部的SwingUtilities.invokeLater調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.