SlideShare a Scribd company logo
1 of 21
Download to read offline
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

What's hot

LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 
Funcitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayFuncitonal Swift Conference: The Functional Way
Funcitonal Swift Conference: The Functional WayNatasha Murashev
 
Advanced javascript
Advanced javascriptAdvanced javascript
Advanced javascriptDoeun KOCH
 
The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88The Ring programming language version 1.3 book - Part 7 of 88
The Ring programming language version 1.3 book - Part 7 of 88Mahmoud Samir Fayed
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 
Deep Dive into React Hooks
Deep Dive into React HooksDeep Dive into React Hooks
Deep Dive into React HooksFelix Kühl
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 
Functional Core, Reactive Shell
Functional Core, Reactive ShellFunctional Core, Reactive Shell
Functional Core, Reactive ShellGiovanni Lodi
 
The Ring programming language version 1.5.4 book - Part 14 of 185
The Ring programming language version 1.5.4 book - Part 14 of 185The Ring programming language version 1.5.4 book - Part 14 of 185
The Ring programming language version 1.5.4 book - Part 14 of 185Mahmoud Samir Fayed
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Build Widgets
Build WidgetsBuild Widgets
Build Widgetsscottw
 
Kotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confKotlin Delegates in practice - Kotlin community conf
Kotlin Delegates in practice - Kotlin community confFabio Collini
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
GKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGKAC 2015 Apr. - RxAndroid
GKAC 2015 Apr. - RxAndroidGDG Korea
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose worldFabio Collini
 
Kotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmKotlin delegates in practice - Kotlin Everywhere Stockholm
Kotlin delegates in practice - Kotlin Everywhere StockholmFabio Collini
 

What's hot (20)

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

Viewers also liked

Gastronomia ericka
Gastronomia erickaGastronomia ericka
Gastronomia erickaerickaunita
 
Kilifi county beach tournament 2015
Kilifi county beach tournament 2015Kilifi county beach tournament 2015
Kilifi county beach tournament 2015Peter Ogweyo
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web DesignGoodbytes
 
Drobo Benchmarks to accompany TMUP 159
Drobo Benchmarks to accompany TMUP 159Drobo Benchmarks to accompany TMUP 159
Drobo Benchmarks to accompany TMUP 159typicalmacuser
 
Scdp100421 yasuda
Scdp100421 yasudaScdp100421 yasuda
Scdp100421 yasudavcasi
 
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young AdultsRadiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young AdultsMethodist HealthcareSA
 
Talk to uganda christian university
Talk to uganda christian universityTalk to uganda christian university
Talk to uganda christian universityAlex Taremwa
 
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1Ana Paula Santos
 
Bubble Spotting - Dutch Tulip Mania
Bubble Spotting - Dutch Tulip ManiaBubble Spotting - Dutch Tulip Mania
Bubble Spotting - Dutch Tulip ManiaBenjamin Van As
 

Viewers also liked (14)

Gastronomia ericka
Gastronomia erickaGastronomia ericka
Gastronomia ericka
 
Preguntas
PreguntasPreguntas
Preguntas
 
Kilifi county beach tournament 2015
Kilifi county beach tournament 2015Kilifi county beach tournament 2015
Kilifi county beach tournament 2015
 
Responsive Web Design
Responsive Web DesignResponsive Web Design
Responsive Web Design
 
Goldcard
GoldcardGoldcard
Goldcard
 
Drobo Benchmarks to accompany TMUP 159
Drobo Benchmarks to accompany TMUP 159Drobo Benchmarks to accompany TMUP 159
Drobo Benchmarks to accompany TMUP 159
 
Scdp100421 yasuda
Scdp100421 yasudaScdp100421 yasuda
Scdp100421 yasuda
 
Chena Cultivation
Chena CultivationChena Cultivation
Chena Cultivation
 
Tulip Mania Paper
Tulip Mania PaperTulip Mania Paper
Tulip Mania Paper
 
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young AdultsRadiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
Radiotherapy in the Treatment of Sarcomas in Adolescents and Young Adults
 
Talk to uganda christian university
Talk to uganda christian universityTalk to uganda christian university
Talk to uganda christian university
 
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
Percepção Discriminação- Aprendizagem da Leitura e Escrita 1
 
Bubble Spotting - Dutch Tulip Mania
Bubble Spotting - Dutch Tulip ManiaBubble Spotting - Dutch Tulip Mania
Bubble Spotting - Dutch Tulip Mania
 
Horas cartazes
Horas cartazesHoras cartazes
Horas cartazes
 

Similar to 12advanced Swing

13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swingNataraj Dg
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docxbriancrawford30935
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180Mahmoud Samir Fayed
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2stuq
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsRavi Bhadauria
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 SpringKiyotaka Oku
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsJeff Durta
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbroncymbron
 

Similar to 12advanced Swing (20)

13 advanced-swing
13 advanced-swing13 advanced-swing
13 advanced-swing
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
project2.classpathproject2.project project2 .docx
project2.classpathproject2.project  project2 .docxproject2.classpathproject2.project  project2 .docx
project2.classpathproject2.project project2 .docx
 
The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180The Ring programming language version 1.5.1 book - Part 12 of 180
The Ring programming language version 1.5.1 book - Part 12 of 180
 
Eclipse Tricks
Eclipse TricksEclipse Tricks
Eclipse Tricks
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
droidparts
droidpartsdroidparts
droidparts
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
JJUG CCC 2011 Spring
JJUG CCC 2011 SpringJJUG CCC 2011 Spring
JJUG CCC 2011 Spring
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applicationsAdding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
 
Java
JavaJava
Java
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Developing a new Epsilon EMC driver
Developing a new Epsilon EMC driverDeveloping a new Epsilon EMC driver
Developing a new Epsilon EMC driver
 
Exercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera CymbronExercícios Netbeans - Vera Cymbron
Exercícios Netbeans - Vera Cymbron
 
Ngrx meta reducers
Ngrx meta reducersNgrx meta reducers
Ngrx meta reducers
 
11basic Swing
11basic Swing11basic Swing
11basic Swing
 
jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 

More from Adil Jafri

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5Adil Jafri
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net BibleAdil Jafri
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming ClientsAdil Jafri
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran TochAdil Jafri
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10Adil Jafri
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx TutorialsAdil Jafri
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbAdil Jafri
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12Adil Jafri
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash TutorialAdil Jafri
 

More from Adil Jafri (20)

Csajsp Chapter5
Csajsp Chapter5Csajsp Chapter5
Csajsp Chapter5
 
Php How To
Php How ToPhp How To
Php How To
 
Php How To
Php How ToPhp How To
Php How To
 
Owl Clock
Owl ClockOwl Clock
Owl Clock
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Phpcodebook
PhpcodebookPhpcodebook
Phpcodebook
 
Programming Asp Net Bible
Programming Asp Net BibleProgramming Asp Net Bible
Programming Asp Net Bible
 
Tcpip Intro
Tcpip IntroTcpip Intro
Tcpip Intro
 
Network Programming Clients
Network Programming ClientsNetwork Programming Clients
Network Programming Clients
 
Jsp Tutorial
Jsp TutorialJsp Tutorial
Jsp Tutorial
 
Ta Javaserverside Eran Toch
Ta Javaserverside Eran TochTa Javaserverside Eran Toch
Ta Javaserverside Eran Toch
 
Csajsp Chapter10
Csajsp Chapter10Csajsp Chapter10
Csajsp Chapter10
 
Javascript
JavascriptJavascript
Javascript
 
Flashmx Tutorials
Flashmx TutorialsFlashmx Tutorials
Flashmx Tutorials
 
Java For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand EjbJava For The Web With Servlets%2cjsp%2cand Ejb
Java For The Web With Servlets%2cjsp%2cand Ejb
 
Html Css
Html CssHtml Css
Html Css
 
Digwc
DigwcDigwc
Digwc
 
Csajsp Chapter12
Csajsp Chapter12Csajsp Chapter12
Csajsp Chapter12
 
Html Frames
Html FramesHtml Frames
Html Frames
 
Flash Tutorial
Flash TutorialFlash Tutorial
Flash Tutorial
 

Recently uploaded

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 

Recently uploaded (20)

Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 

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?