SlideShare a Scribd company logo
1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Advanced Swing
Custom Data Models and Cell Renderers
Advanced Swing2 www.corewebprogramming.com
Agenda
• Building a simple static JList
• Adding and removing entries from
a JList at runtime
• Making a custom data model
– Telling JList how to extract data from
existing objects
• Making a custom cell renderer
– Telling JList what GUI component to use for
each of the data cells
Advanced Swing3 www.corewebprogramming.com
MVC Architecture
• Custom data models
– Changing the way the GUI control obtains the data.
Instead of copying data from an existing object into a
GUI control, simply tell the GUI control how to get at the
existing data.
• Custom cell renderers
– Changing the way the GUI control displays data values.
Instead of changing the data values, simply tell the GUI
control how to build a Swing component that represents
each data value.
• Main applicable components
– JList
– JTable
– JTree
Advanced Swing4 www.corewebprogramming.com
JList with Fixed Set of Choices
• Build JList: pass strings to constructor
– The simplest way to use a JList is to supply an array of
strings to the JList constructor. Cannot add or remove
elements once the JList is created.
String options =
{ "Option 1", ... , "Option N"};
JList optionList = new JList(options);
• Set visible rows
– Call setVisibleRowCount and drop JList into JScrollPane
optionList.setVisibleRowCount(4);
JScrollPane optionPane =
new JScrollPane(optionList);
someContainer.add(optionPane);
• Handle events
– Attach ListSelectionListener and use valueChanged
Advanced Swing5 www.corewebprogramming.com
Simple JList: Example Code
public class JListSimpleExample extends JFrame {
...
public JListSimpleExample() {
super("Creating a Simple JList");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
Container content = getContentPane();
String[] entries = { "Entry 1", "Entry 2", "Entry 3",
"Entry 4", "Entry 5", "Entry 6"};
sampleJList = new JList(entries);
sampleJList.setVisibleRowCount(4);
sampleJList.addListSelectionListener
(new ValueReporter());
JScrollPane listPane = new JScrollPane(sampleJList);
...
}
Advanced Swing6 www.corewebprogramming.com
Simple JList: Example Code
(Continued)
private class ValueReporter implements ListSelectionListener {
/** You get three events in many cases -- one for the
* deselection of the originally selected entry, one
* indicating the selection is moving, and one for the
* selection of the new entry. In the first two cases,
* getValueIsAdjusting returns true; thus, the test
* below since only the third case is of interest.
*/
public void valueChanged(ListSelectionEvent event) {
if (!event.getValueIsAdjusting()) {
Object value = sampleJList.getSelectedValue();
if (value != null) {
valueField.setText(value.toString());
}
}
}
}
}
Advanced Swing7 www.corewebprogramming.com
Simple JList: Example Output
Advanced Swing8 www.corewebprogramming.com
JList with Changeable Choices
• Build JList:
– Create a DefaultListModel, add data, pass to constructor
String choices = { "Choice 1", ... , "Choice N"};
DefaultListModel sampleModel = new DefaultListModel();
for(int i=0; i<choices.length; i++) {
sampleModel.addElement(choices[i]);
}
JList optionList = new JList(sampleModel);
• Set visible rows
– Same: Use setVisibleRowCount and a JScrollPane
• Handle events
– Same: attach ListSelectionListener and use valueChanged
• Add/remove elements
– Use the model, not the JList directly
Advanced Swing9 www.corewebprogramming.com
Changeable JList:
Example Code
String[] entries = { "Entry 1", "Entry 2", "Entry 3",
"Entry 4", "Entry 5", "Entry 6"};
sampleModel = new DefaultListModel();
for(int i=0; i<entries.length; i++) {
sampleModel.addElement(entries[i]);
}
sampleJList = new JList(sampleModel);
sampleJList.setVisibleRowCount(4);
Font displayFont = new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
JScrollPane listPane = new JScrollPane(sampleJList);
Advanced Swing10 www.corewebprogramming.com
Changeable JList:
Example Code (Continued)
private class ItemAdder implements ActionListener {
/** Add an entry to the ListModel whenever the user
* presses the button. Note that since the new entries
* may be wider than the old ones (e.g., "Entry 10" vs.
* "Entry 9"), you need to rerun the layout manager.
* You need to do this <I>before</I> trying to scroll
* to make the index visible.
*/
public void actionPerformed(ActionEvent event) {
int index = sampleModel.getSize();
sampleModel.addElement("Entry " + (index+1));
((JComponent)getContentPane()).revalidate();
sampleJList.setSelectedIndex(index);
sampleJList.ensureIndexIsVisible(index);
}
}
}
Advanced Swing11 www.corewebprogramming.com
Changeable JList:
Example Output
Advanced Swing12 www.corewebprogramming.com
JList with Custom Data Model
• Build JList
– Have existing data implement ListModel interface
• getElementAt
– Given an index, returns data element
• getSize
– Tells JList how many entries are in list
• addListDataListener
– Lets user add listeners that should be notified
when an item is selected or deselected.
• removeListDataListener
– Pass model to JList constructor
• Set visible rows & handle events: as before
• Add/remove items: use the model
Advanced Swing13 www.corewebprogramming.com
Custom Model: Example Code
public class JavaLocationListModel implements ListModel {
private JavaLocationCollection collection;
public JavaLocationListModel
(JavaLocationCollection collection) {
this.collection = collection;
}
public Object getElementAt(int index) {
return(collection.getLocations()[index]);
}
public int getSize() {
return(collection.getLocations().length);
}
public void addListDataListener(ListDataListener l) {}
public void removeListDataListener(ListDataListener l) {}
}
Advanced Swing14 www.corewebprogramming.com
Actual Data
public class JavaLocationCollection {
private static JavaLocation[] defaultLocations =
{ new JavaLocation("Belgium",
"near Liege",
"flags/belgium.gif"),
new JavaLocation("Brazil",
"near Salvador",
"flags/brazil.gif"),
new JavaLocation("Colombia",
"near Bogota",
"flags/colombia.gif"),
... }; ...
}
• JavaLocation has toString plus 3 fields
– Country, comment, flag file
Advanced Swing15 www.corewebprogramming.com
JList with Custom Model:
Example Code
JavaLocationCollection collection =
new JavaLocationCollection();
JavaLocationListModel listModel =
new JavaLocationListModel(collection);
JList sampleJList = new JList(listModel);
Font displayFont =
new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
content.add(sampleJList);
Advanced Swing16 www.corewebprogramming.com
JList with Custom Model:
Example Output
Advanced Swing17 www.corewebprogramming.com
JList with Custom Cell
Renderer
• Idea
– Instead of predetermining how the JList will draw the list
elements, Swing lets you specify what graphical
component to use for the various entries.
Attach a ListCellRenderer that has a
getListCellRendererComponent method that determines
the GUI component used for each cell.
• Arguments to
getListCellRendererComponent
– JList: the list itself
– Object: the value of the current cell
– int: the index of the current cell
– boolean: is the current cell selected?
– boolean: does the current cell have focus?
Advanced Swing18 www.corewebprogramming.com
Custom Renderer:
Example Code
public class JavaLocationRenderer extends
DefaultListCellRenderer {
private Hashtable iconTable = new Hashtable();
public Component getListCellRendererComponent
(JList list, Object value, int index,
boolean isSelected, boolean hasFocus) {
JLabel label = (JLabel)super.getListCellRendererComponent
(list,value,index,isSelected,hasFocus);
if (value instanceof JavaLocation) {
JavaLocation location = (JavaLocation)value;
ImageIcon icon = (ImageIcon)iconTable.get(value);
if (icon == null) {
icon = new ImageIcon(location.getFlagFile());
iconTable.put(value, icon);
}
label.setIcon(icon);
...
return(label);
}}
Advanced Swing19 www.corewebprogramming.com
Custom Renderer:
Example Output
Advanced Swing20 www.corewebprogramming.com
Summary
• Simple static JList
– Pass array of strings to JList constructor
• Simple changeable JList
– Pass DefaultListModel to JList constructor. Add/remove
data to/from the model, not the JList.
• Custom data model
– Have real data implement ListModel interface.
– Pass real data to JList constructor.
• Custom cell renderer
– Assign a ListCellRenderer
– ListCellRenderer has a method that determines the
Component to be used for each cell
21 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com
core
programming
Questions?

More Related Content

PDF
Selectors and normalizing state shape
PPT
jQuery for beginners
PDF
Taming Core Data by Arek Holko, Macoscope
PPTX
Javascript talk
PPTX
Functional Reactive Programming (FRP): Working with RxJS
PDF
Anonymous functions in JavaScript
PPT
Swing basics
PDF
The Ring programming language version 1.2 book - Part 5 of 84
Selectors and normalizing state shape
jQuery for beginners
Taming Core Data by Arek Holko, Macoscope
Javascript talk
Functional Reactive Programming (FRP): Working with RxJS
Anonymous functions in JavaScript
Swing basics
The Ring programming language version 1.2 book - Part 5 of 84

What's hot (20)

PDF
LetSwift RxSwift 시작하기
PPT
data Structure Lecture 1
PPT
Iterator Design Pattern
PDF
Funcitonal Swift Conference: The Functional Way
PDF
Advanced javascript
PDF
The Ring programming language version 1.3 book - Part 7 of 88
PDF
RxSwift 활용하기 - Let'Swift 2017
PDF
Deep Dive into React Hooks
PDF
Intro to JavaScript
DOC
Selenium Webdriver with data driven framework
PDF
Functional Core, Reactive Shell
PDF
The Ring programming language version 1.5.4 book - Part 14 of 185
PPTX
Use of Apache Commons and Utilities
PDF
Build Widgets
PDF
Kotlin Delegates in practice - Kotlin community conf
PPTX
Test and profile your Windows Phone 8 App
PDF
GKAC 2015 Apr. - RxAndroid
PPTX
Intro to Javascript
PDF
Architectures in the compose world
PDF
Kotlin delegates in practice - Kotlin Everywhere Stockholm
LetSwift RxSwift 시작하기
data Structure Lecture 1
Iterator Design Pattern
Funcitonal Swift Conference: The Functional Way
Advanced javascript
The Ring programming language version 1.3 book - Part 7 of 88
RxSwift 활용하기 - Let'Swift 2017
Deep Dive into React Hooks
Intro to JavaScript
Selenium Webdriver with data driven framework
Functional Core, Reactive Shell
The Ring programming language version 1.5.4 book - Part 14 of 185
Use of Apache Commons and Utilities
Build Widgets
Kotlin Delegates in practice - Kotlin community conf
Test and profile your Windows Phone 8 App
GKAC 2015 Apr. - RxAndroid
Intro to Javascript
Architectures in the compose world
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Ad

Viewers also liked (14)

PPT
Gastronomia ericka
PPTX
Preguntas
DOCX
Kilifi county beach tournament 2015
PDF
Responsive Web Design
PPT
Goldcard
PDF
Drobo Benchmarks to accompany TMUP 159
PDF
Scdp100421 yasuda
PDF
Tulip Mania Paper
PPT
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
PPT
Talk to uganda christian university
PDF
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
PDF
Bubble Spotting - Dutch Tulip Mania
DOC
Horas cartazes
Gastronomia ericka
Preguntas
Kilifi county beach tournament 2015
Responsive Web Design
Goldcard
Drobo Benchmarks to accompany TMUP 159
Scdp100421 yasuda
Tulip Mania Paper
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
Talk to uganda christian university
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
Bubble Spotting - Dutch Tulip Mania
Horas cartazes
Ad

Similar to 12advanced Swing (20)

PDF
13 advanced-swing
PDF
Module 4
PPTX
Advanced java programming
PPTX
PPT
Lists and scrollbars
PPT
Chapter 5 GUI for introduction of java and gui .ppt
PPTX
OOP Lecture 9-JComboBox,JList,JPanel.pptx
PPTX
DOCX
Advance Java Programs skeleton
PPT
Java awt
PPT
Java swing
PDF
Java Foundation Classes - Building Portable GUIs
PPT
Cso gaddis java_chapter13
PPTX
java-Unit4 chap2- awt controls and layout managers of applet
PPT
Eo gaddis java_chapter_12_5e
PPT
Eo gaddis java_chapter_12_5e
PPTX
swing_compo.pptxsfdsfffdfdfdfdgwrwrwwtry
PPTX
OOP Lecture 10-JTable,JTabbedPane,LayoutManagers.pptx
PPTX
Event handling
13 advanced-swing
Module 4
Advanced java programming
Lists and scrollbars
Chapter 5 GUI for introduction of java and gui .ppt
OOP Lecture 9-JComboBox,JList,JPanel.pptx
Advance Java Programs skeleton
Java awt
Java swing
Java Foundation Classes - Building Portable GUIs
Cso gaddis java_chapter13
java-Unit4 chap2- awt controls and layout managers of applet
Eo gaddis java_chapter_12_5e
Eo gaddis java_chapter_12_5e
swing_compo.pptxsfdsfffdfdfdfdgwrwrwwtry
OOP Lecture 10-JTable,JTabbedPane,LayoutManagers.pptx
Event handling

More from Adil Jafri (20)

PDF
Csajsp Chapter5
PDF
Php How To
PDF
Php How To
PDF
Owl Clock
PDF
Phpcodebook
PDF
Phpcodebook
PDF
Programming Asp Net Bible
PDF
Tcpip Intro
PDF
Network Programming Clients
PDF
Jsp Tutorial
PPT
Ta Javaserverside Eran Toch
PDF
Csajsp Chapter10
PDF
Javascript
PDF
Flashmx Tutorials
PDF
Java For The Web With Servlets%2cjsp%2cand Ejb
PDF
Html Css
PDF
Digwc
PDF
Csajsp Chapter12
PDF
Html Frames
PDF
Flash Tutorial
Csajsp Chapter5
Php How To
Php How To
Owl Clock
Phpcodebook
Phpcodebook
Programming Asp Net Bible
Tcpip Intro
Network Programming Clients
Jsp Tutorial
Ta Javaserverside Eran Toch
Csajsp Chapter10
Javascript
Flashmx Tutorials
Java For The Web With Servlets%2cjsp%2cand Ejb
Html Css
Digwc
Csajsp Chapter12
Html Frames
Flash Tutorial

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Insiders guide to clinical Medicine.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
PPTX
GDM (1) (1).pptx small presentation for students
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Cell Types and Its function , kingdom of life
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Pharma ospi slides which help in ospi learning
PPTX
PPH.pptx obstetrics and gynecology in nursing
human mycosis Human fungal infections are called human mycosis..pptx
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Insiders guide to clinical Medicine.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
Black Hat USA 2025 - Micro ICS Summit - ICS/OT Threat Landscape
GDM (1) (1).pptx small presentation for students
O7-L3 Supply Chain Operations - ICLT Program
Cell Types and Its function , kingdom of life
Module 4: Burden of Disease Tutorial Slides S2 2025
Supply Chain Operations Speaking Notes -ICLT Program
102 student loan defaulters named and shamed – Is someone you know on the list?
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Abdominal Access Techniques with Prof. Dr. R K Mishra
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Microbial diseases, their pathogenesis and prophylaxis
Basic Mud Logging Guide for educational purpose
Pharma ospi slides which help in ospi learning
PPH.pptx obstetrics and gynecology in nursing

12advanced Swing

  • 1. 1 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Advanced Swing Custom Data Models and Cell Renderers
  • 2. Advanced Swing2 www.corewebprogramming.com Agenda • Building a simple static JList • Adding and removing entries from a JList at runtime • Making a custom data model – Telling JList how to extract data from existing objects • Making a custom cell renderer – Telling JList what GUI component to use for each of the data cells
  • 3. Advanced Swing3 www.corewebprogramming.com MVC Architecture • Custom data models – Changing the way the GUI control obtains the data. Instead of copying data from an existing object into a GUI control, simply tell the GUI control how to get at the existing data. • Custom cell renderers – Changing the way the GUI control displays data values. Instead of changing the data values, simply tell the GUI control how to build a Swing component that represents each data value. • Main applicable components – JList – JTable – JTree
  • 4. Advanced Swing4 www.corewebprogramming.com JList with Fixed Set of Choices • Build JList: pass strings to constructor – The simplest way to use a JList is to supply an array of strings to the JList constructor. Cannot add or remove elements once the JList is created. String options = { "Option 1", ... , "Option N"}; JList optionList = new JList(options); • Set visible rows – Call setVisibleRowCount and drop JList into JScrollPane optionList.setVisibleRowCount(4); JScrollPane optionPane = new JScrollPane(optionList); someContainer.add(optionPane); • Handle events – Attach ListSelectionListener and use valueChanged
  • 5. Advanced Swing5 www.corewebprogramming.com Simple JList: Example Code public class JListSimpleExample extends JFrame { ... public JListSimpleExample() { super("Creating a Simple JList"); WindowUtilities.setNativeLookAndFeel(); addWindowListener(new ExitListener()); Container content = getContentPane(); String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6"}; sampleJList = new JList(entries); sampleJList.setVisibleRowCount(4); sampleJList.addListSelectionListener (new ValueReporter()); JScrollPane listPane = new JScrollPane(sampleJList); ... }
  • 6. Advanced Swing6 www.corewebprogramming.com Simple JList: Example Code (Continued) private class ValueReporter implements ListSelectionListener { /** You get three events in many cases -- one for the * deselection of the originally selected entry, one * indicating the selection is moving, and one for the * selection of the new entry. In the first two cases, * getValueIsAdjusting returns true; thus, the test * below since only the third case is of interest. */ public void valueChanged(ListSelectionEvent event) { if (!event.getValueIsAdjusting()) { Object value = sampleJList.getSelectedValue(); if (value != null) { valueField.setText(value.toString()); } } } } }
  • 8. Advanced Swing8 www.corewebprogramming.com JList with Changeable Choices • Build JList: – Create a DefaultListModel, add data, pass to constructor String choices = { "Choice 1", ... , "Choice N"}; DefaultListModel sampleModel = new DefaultListModel(); for(int i=0; i<choices.length; i++) { sampleModel.addElement(choices[i]); } JList optionList = new JList(sampleModel); • Set visible rows – Same: Use setVisibleRowCount and a JScrollPane • Handle events – Same: attach ListSelectionListener and use valueChanged • Add/remove elements – Use the model, not the JList directly
  • 9. Advanced Swing9 www.corewebprogramming.com Changeable JList: Example Code String[] entries = { "Entry 1", "Entry 2", "Entry 3", "Entry 4", "Entry 5", "Entry 6"}; sampleModel = new DefaultListModel(); for(int i=0; i<entries.length; i++) { sampleModel.addElement(entries[i]); } sampleJList = new JList(sampleModel); sampleJList.setVisibleRowCount(4); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); JScrollPane listPane = new JScrollPane(sampleJList);
  • 10. Advanced Swing10 www.corewebprogramming.com Changeable JList: Example Code (Continued) private class ItemAdder implements ActionListener { /** Add an entry to the ListModel whenever the user * presses the button. Note that since the new entries * may be wider than the old ones (e.g., "Entry 10" vs. * "Entry 9"), you need to rerun the layout manager. * You need to do this <I>before</I> trying to scroll * to make the index visible. */ public void actionPerformed(ActionEvent event) { int index = sampleModel.getSize(); sampleModel.addElement("Entry " + (index+1)); ((JComponent)getContentPane()).revalidate(); sampleJList.setSelectedIndex(index); sampleJList.ensureIndexIsVisible(index); } } }
  • 12. Advanced Swing12 www.corewebprogramming.com JList with Custom Data Model • Build JList – Have existing data implement ListModel interface • getElementAt – Given an index, returns data element • getSize – Tells JList how many entries are in list • addListDataListener – Lets user add listeners that should be notified when an item is selected or deselected. • removeListDataListener – Pass model to JList constructor • Set visible rows & handle events: as before • Add/remove items: use the model
  • 13. Advanced Swing13 www.corewebprogramming.com Custom Model: Example Code public class JavaLocationListModel implements ListModel { private JavaLocationCollection collection; public JavaLocationListModel (JavaLocationCollection collection) { this.collection = collection; } public Object getElementAt(int index) { return(collection.getLocations()[index]); } public int getSize() { return(collection.getLocations().length); } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} }
  • 14. Advanced Swing14 www.corewebprogramming.com Actual Data public class JavaLocationCollection { private static JavaLocation[] defaultLocations = { new JavaLocation("Belgium", "near Liege", "flags/belgium.gif"), new JavaLocation("Brazil", "near Salvador", "flags/brazil.gif"), new JavaLocation("Colombia", "near Bogota", "flags/colombia.gif"), ... }; ... } • JavaLocation has toString plus 3 fields – Country, comment, flag file
  • 15. Advanced Swing15 www.corewebprogramming.com JList with Custom Model: Example Code JavaLocationCollection collection = new JavaLocationCollection(); JavaLocationListModel listModel = new JavaLocationListModel(collection); JList sampleJList = new JList(listModel); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); content.add(sampleJList);
  • 16. Advanced Swing16 www.corewebprogramming.com JList with Custom Model: Example Output
  • 17. Advanced Swing17 www.corewebprogramming.com JList with Custom Cell Renderer • Idea – Instead of predetermining how the JList will draw the list elements, Swing lets you specify what graphical component to use for the various entries. Attach a ListCellRenderer that has a getListCellRendererComponent method that determines the GUI component used for each cell. • Arguments to getListCellRendererComponent – JList: the list itself – Object: the value of the current cell – int: the index of the current cell – boolean: is the current cell selected? – boolean: does the current cell have focus?
  • 18. Advanced Swing18 www.corewebprogramming.com Custom Renderer: Example Code public class JavaLocationRenderer extends DefaultListCellRenderer { private Hashtable iconTable = new Hashtable(); public Component getListCellRendererComponent (JList list, Object value, int index, boolean isSelected, boolean hasFocus) { JLabel label = (JLabel)super.getListCellRendererComponent (list,value,index,isSelected,hasFocus); if (value instanceof JavaLocation) { JavaLocation location = (JavaLocation)value; ImageIcon icon = (ImageIcon)iconTable.get(value); if (icon == null) { icon = new ImageIcon(location.getFlagFile()); iconTable.put(value, icon); } label.setIcon(icon); ... return(label); }}
  • 20. Advanced Swing20 www.corewebprogramming.com Summary • Simple static JList – Pass array of strings to JList constructor • Simple changeable JList – Pass DefaultListModel to JList constructor. Add/remove data to/from the model, not the JList. • Custom data model – Have real data implement ListModel interface. – Pass real data to JList constructor. • Custom cell renderer – Assign a ListCellRenderer – ListCellRenderer has a method that determines the Component to be used for each cell
  • 21. 21 © 2001-2003 Marty Hall, Larry Brown http://www.corewebprogramming.com core programming Questions?