JList wordList = new JList(words);
setVisibleRowCount(n);方法可以設置最多顯示多少行(若沒有添加滾動面板,此設置無效,所有內容均會顯示)。
另外兩個參數是JList.VERTICAL_WRAP和JList.HORIZONTAL_WRAP,其含義分別是“在保證行數不超過setVisibleRowCount(n)的情況下,縱向或橫向排列元素”。此時滾動面板無效,因爲行數永遠不可能超標,因此滾動面板也永遠不會出現。比如最大顯示行數爲4,總共有5個元素,顯示結果如下:
1.按下鼠標不鬆手,在各個元素間拖動;
2.鬆開鼠標。
也就是說,當你按下鼠標後,會觸發一個事件,拖動到另一個控件,又觸發一個事件,繼續拖動則繼續觸發事件,最後鬆手,觸發一個事件。那麼,你如何區分這2種情況呢?ListSelectionEvent提供了一個方法getValueIsAdjusting(),如果該方法返回true,則代表情況1;反之代表情況2。同時請注意,JList控件不提供鼠標雙擊元素的處理事件,若要處理鼠標雙擊的情況,則應該添加鼠標監聽器,代碼如下:
...{
if (evt.getClickCount() == 2)
...{
JList source = (JList) evt.getSource();
Object[] selection = source.getSelectedValues();
doAction(selection);
}
}
...{
public WordListModel(int n) ...{ length = n; }
public int getSize()
...{
return (int) Math.pow(LAST - FIRST + 1, length);
}
public Object getElementAt(int n)
...{
StringBuilder r = new StringBuilder();;
for (int i = 0; i < length; i++)
...{
char c = (char)(FIRST + n % (LAST - FIRST + 1));
r.insert(0, c);
n = n / (LAST - FIRST + 1);
}
return r;
}
private int length;
public static final char FIRST = 'a';
public static final char LAST = 'z';
}
...{
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
...{
text = (String)value;
background = isSelected ? list.getSelectionBackground() : list.getBackground();
foreground = isSelected ? list.getSelectionForeground() : list.getForeground();
return this;
}
public void paintComponent(Graphics g)
...{
g.setColor(background);
g.fillRect(0, 0, getWidth(), getHeight()); //設置背景色
g.setColor(foreground);
g.drawString(text, 5, 15); //在制定位置繪製文本
}
public Dimension getPreferredSize()
...{
return new Dimension(30, 20); //Cell的尺寸
}
private String text;
private Color background;
private Color foreground;
}