JList Dynamic List Model problem
Hello All,
I have a simple custom JList with a simple custom DefaultListModel and its own cell renderer. This JList is set as the view port of a scroll pane and the scroll pane is added to a panel. Standard Stuff.
JList's model changes dynamically and when this happens I call the updateModel method. As you can see I remove all elements and add new set of items. Now I want JScrollPane to automatically resize such that even the longest item is visible. What is the best way to do this?
1) Compute the longest string in the array and use the setPrototypeCellValue() ?
- Problem is that some times the longest string is just two characters wide and the display looks retarted.
2) Should I experiment with setPreferredSize stuff to see what is logical size for various combinations of the data that could occur in the JList?
3) Should the JScrollPane listens to change in the JList 's model and then resize itself ?
- Seems very complex for such a trivial job.
publicclass SearchableListextends JList{
MyListModel _model;
public SearchableList(){
super();
init();
}
privatevoid init(){
this.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
this.setCellRenderer(new Renderer() );
_model =new MyListModel(new String[]{});
super.setModel(_model);
}
class Rendererextends JTextFieldimplements ListCellRenderer{
protected Border noFocusBorder;
private DefaultHighlighter.DefaultHighlightPainter painter;
public Renderer(){
super();
if( noFocusBorder ==null )
noFocusBorder =new EmptyBorder(1, 1, 1, 1);
this.painter =new DefaultHighlighter.DefaultHighlightPainter(Color.GREEN);
}
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus ){
setComponentOrientation( list.getComponentOrientation() );
if( isSelected ){
setBackground( list.getSelectionBackground() );
setForeground( list.getSelectionForeground() );
}else{
setBackground( list.getBackground() );
setForeground( list.getForeground() );
}
String text = value.toString();
setText( text );
// For now highlight the second character of all items
// We must change the Highlighter AFTER calling setText()
Highlighter highlighter = this.getHighlighter();
highlighter.removeAllHighlights();
if( text.length() > 2 ){
//ADD code here that highlightes the user entered substring match
// try {
//highlighter.addHighlight( 1, 2, this.painter );
// } catch( BadLocationException e ) {
// e.printStackTrace();
//}
}
setEnabled( list.isEnabled() );
setFont( list.getFont() );
returnthis;
}
}
publicvoid updateModel(String[] carValues){
_model.init(carValues);
}
}
class MyListModelextends DefaultListModel{
public MyListModel(String[] args){
init(args);
}
publicvoid contentsChanged (){
super.fireContentsChanged(this, -1, -1);
}
publicvoid init(String[] args){
removeAllElements();
if (args ==null)return;
for (int i=0; i < args.length; i++){
addElement(args[i]);
}
contentsChanged();
}
}
Thanks in advance.

