SlideShare uma empresa Scribd logo
1 de 11
Baixar para ler offline
© 2013 Marty Hall
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Advanced Swing & MVC
2
Custom Data Models and Cell Renderers
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/java.html
© 2013 Marty Hall
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
For live Java-related training,
see http://courses.coreservlets.com/
or email hall@coreservlets.com.
Taught by the author of Core Servlets and JSP, More Servlets
and JSP, and this tutorial. Available at public venues, or
customized versions can be held on-site at your organization.
• Courses developed and taught by Marty Hall
– JSF 2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 7 or 8 programming, custom mix of topics
– Courses available in any state or country. Maryland/DC area companies can also choose afternoon/evening courses.
• Courses developed and taught by coreservlets.com experts (edited by Marty)
– Spring, Hibernate/JPA, GWT, Hadoop, HTML5, RESTful Web Services
Contact hall@coreservlets.com for details
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
– Using toString to display a String but return a complex
object upon selection
• Making a custom cell renderer
– Telling JList what GUI component to use for
each of the data cells
4
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
5
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<String> 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
6
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);
...
}
7
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()) {
String value = sampleJList.getSelectedValue();
if (value != null) {
valueField.setText(value.toString());
}
}
}
}
}8
Simple JList: Example Output
9
JList with Changeable Choices
• Build JList:
– Create a DefaultListModel, add data, pass to constructor
String choices = { "Choice 1", ... , "Choice N"};
DefaultListModel<String> sampleModel =
new DefaultListModel<>();
for(int i=0; i<choices.length; i++) {
sampleModel.addElement(choices[i]);
}
JList<String> 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
10
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);
11
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
Changeable JList:
Example Output
13
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
14
Custom Model: Example Code
public class JavaLocationListModel
implements ListModel<JavaLocation> {
private JavaLocationCollection collection;
public JavaLocationListModel(JavaLocationCollection collection) {
this.collection = collection;
}
public JavaLocation getElementAt(int index) {
return(collection.getLocations()[index]);
}
public int getSize() {
return(collection.getLocations().length);
}
public void addListDataListener(ListDataListener l) {}
public void removeListDataListener(ListDataListener l) {}
}
15
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
16
JList with Custom Model:
Example Code
JavaLocationCollection collection =
new JavaLocationCollection();
JavaLocationListModel listModel =
new JavaLocationListModel(collection);
JList<JavaLocation> sampleJList =
new JList<>(listModel);
Font displayFont =
new Font("Serif", Font.BOLD, 18);
sampleJList.setFont(displayFont);
content.add(sampleJList);
17
JList with Custom Model:
Example Output
18
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.
• getListCellRendererComponent arguments
– 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?19
Custom Renderer:
Example Code
public class JavaLocationRenderer extends
DefaultListCellRenderer {
private Map<Object,ImageIcon> iconTable =
new HashMap<Object,ImageIcon>();
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 = iconTable.get(value);
if (icon == null) {
icon = new ImageIcon(location.getFlagFile());
iconTable.put(value, icon);
}
label.setIcon(icon);
...
return(label);
}}20
Custom Renderer:
Example Output
21
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
22
© 2013 Marty Hall
Customized Java EE Training: http://courses.coreservlets.com/
Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Questions?
23
JSF 2, PrimeFaces, Java 7 or 8, HTML5, Ajax, jQuery, Hadoop, RESTful Web Services, Android, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training.

Mais conteúdo relacionado

Mais procurados

Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Google app engine cheat sheet
Google app engine cheat sheetGoogle app engine cheat sheet
Google app engine cheat sheetPiyush Mittal
 
saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...
saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...
saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...butest
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and JavaSasha Goldshtein
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesAndrey Karpov
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2stuq
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtimeDneprCiklumEvents
 
jQuery 1.7 visual cheat sheet
jQuery 1.7 visual cheat sheetjQuery 1.7 visual cheat sheet
jQuery 1.7 visual cheat sheetJiby John
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vectornurkhaledah
 
Jquery 17-visual-cheat-sheet1
Jquery 17-visual-cheat-sheet1Jquery 17-visual-cheat-sheet1
Jquery 17-visual-cheat-sheet1Michael Andersen
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector classNontawat Wongnuk
 
Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose worldFabio Collini
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design PatternVarun Arora
 

Mais procurados (19)

Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Google app engine cheat sheet
Google app engine cheat sheetGoogle app engine cheat sheet
Google app engine cheat sheet
 
saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...
saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...
saihw1_weka_tutorial.pptx - Machine Discovery and Social Network ...
 
JQuery
JQueryJQuery
JQuery
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Generics in .NET, C++ and Java
Generics in .NET, C++ and JavaGenerics in .NET, C++ and Java
Generics in .NET, C++ and Java
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Static analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutesStatic analysis: Around Java in 60 minutes
Static analysis: Around Java in 60 minutes
 
Wicket KT part 2
Wicket KT part 2Wicket KT part 2
Wicket KT part 2
 
Pavel kravchenko obj c runtime
Pavel kravchenko obj c runtimePavel kravchenko obj c runtime
Pavel kravchenko obj c runtime
 
jQuery 1.7 visual cheat sheet
jQuery 1.7 visual cheat sheetjQuery 1.7 visual cheat sheet
jQuery 1.7 visual cheat sheet
 
Lecture20 vector
Lecture20 vectorLecture20 vector
Lecture20 vector
 
Jquery 17-visual-cheat-sheet1
Jquery 17-visual-cheat-sheet1Jquery 17-visual-cheat-sheet1
Jquery 17-visual-cheat-sheet1
 
Function Java Vector class
Function Java Vector classFunction Java Vector class
Function Java Vector class
 
Architectures in the compose world
Architectures in the compose worldArchitectures in the compose world
Architectures in the compose world
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Kotlin-Java Interop - Matej VidakovićJavantura v6 - Kotlin-Java Interop - Matej Vidaković
Javantura v6 - Kotlin-Java Interop - Matej Vidaković
 
Iterator Design Pattern
Iterator Design PatternIterator Design Pattern
Iterator Design Pattern
 
Easy mockppt
Easy mockpptEasy mockppt
Easy mockppt
 

Destaque

Why is swing named swing
Why is swing named swingWhy is swing named swing
Why is swing named swingNataraj Dg
 
Tutorial java swing
Tutorial java swingTutorial java swing
Tutorial java swingNataraj Dg
 
Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.hitaxidave19
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your BusinessBarry Feldman
 

Destaque (7)

Why is swing named swing
Why is swing named swingWhy is swing named swing
Why is swing named swing
 
Tutorial java swing
Tutorial java swingTutorial java swing
Tutorial java swing
 
Swing
SwingSwing
Swing
 
Java lecture
Java lectureJava lecture
Java lecture
 
Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.Comparison between Sense & Sensibility and Pride & Prejudice.
Comparison between Sense & Sensibility and Pride & Prejudice.
 
Java swing
Java swingJava swing
Java swing
 
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business32 Ways a Digital Marketing Consultant Can Help Grow Your Business
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
 

Semelhante a 13 advanced-swing

12advanced Swing
12advanced Swing12advanced Swing
12advanced SwingAdil Jafri
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr TolstykhCodeFest
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryjanet736113
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeMacoscope
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App DevelopmentKetan Raval
 
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
 

Semelhante a 13 advanced-swing (20)

12advanced Swing
12advanced Swing12advanced Swing
12advanced Swing
 
Json generation
Json generationJson generation
Json generation
 
Prototype Framework
Prototype FrameworkPrototype Framework
Prototype Framework
 
droidparts
droidpartsdroidparts
droidparts
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Oleksandr Tolstykh
Oleksandr TolstykhOleksandr Tolstykh
Oleksandr Tolstykh
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 
react-slides.pdf gives information about react library
react-slides.pdf gives information about react libraryreact-slides.pdf gives information about react library
react-slides.pdf gives information about react library
 
Taming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, MacoscopeTaming Core Data by Arek Holko, Macoscope
Taming Core Data by Arek Holko, Macoscope
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Swift Tableview iOS App Development
Swift Tableview iOS App DevelopmentSwift Tableview iOS App Development
Swift Tableview iOS App Development
 
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
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 

13 advanced-swing

  • 1. © 2013 Marty Hall Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Advanced Swing & MVC 2 Custom Data Models and Cell Renderers Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/java.html © 2013 Marty Hall Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. For live Java-related training, see http://courses.coreservlets.com/ or email hall@coreservlets.com. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. • Courses developed and taught by Marty Hall – JSF 2, PrimeFaces, servlets/JSP, Ajax, jQuery, Android development, Java 7 or 8 programming, custom mix of topics – Courses available in any state or country. Maryland/DC area companies can also choose afternoon/evening courses. • Courses developed and taught by coreservlets.com experts (edited by Marty) – Spring, Hibernate/JPA, GWT, Hadoop, HTML5, RESTful Web Services Contact hall@coreservlets.com for details
  • 2. 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 – Using toString to display a String but return a complex object upon selection • Making a custom cell renderer – Telling JList what GUI component to use for each of the data cells 4 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 5
  • 3. 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<String> 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 6 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); ... } 7
  • 4. 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()) { String value = sampleJList.getSelectedValue(); if (value != null) { valueField.setText(value.toString()); } } } } }8 Simple JList: Example Output 9
  • 5. JList with Changeable Choices • Build JList: – Create a DefaultListModel, add data, pass to constructor String choices = { "Choice 1", ... , "Choice N"}; DefaultListModel<String> sampleModel = new DefaultListModel<>(); for(int i=0; i<choices.length; i++) { sampleModel.addElement(choices[i]); } JList<String> 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 10 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); 11
  • 6. 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 Changeable JList: Example Output 13
  • 7. 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 14 Custom Model: Example Code public class JavaLocationListModel implements ListModel<JavaLocation> { private JavaLocationCollection collection; public JavaLocationListModel(JavaLocationCollection collection) { this.collection = collection; } public JavaLocation getElementAt(int index) { return(collection.getLocations()[index]); } public int getSize() { return(collection.getLocations().length); } public void addListDataListener(ListDataListener l) {} public void removeListDataListener(ListDataListener l) {} } 15
  • 8. 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 16 JList with Custom Model: Example Code JavaLocationCollection collection = new JavaLocationCollection(); JavaLocationListModel listModel = new JavaLocationListModel(collection); JList<JavaLocation> sampleJList = new JList<>(listModel); Font displayFont = new Font("Serif", Font.BOLD, 18); sampleJList.setFont(displayFont); content.add(sampleJList); 17
  • 9. JList with Custom Model: Example Output 18 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. • getListCellRendererComponent arguments – 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?19
  • 10. Custom Renderer: Example Code public class JavaLocationRenderer extends DefaultListCellRenderer { private Map<Object,ImageIcon> iconTable = new HashMap<Object,ImageIcon>(); 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 = iconTable.get(value); if (icon == null) { icon = new ImageIcon(location.getFlagFile()); iconTable.put(value, icon); } label.setIcon(icon); ... return(label); }}20 Custom Renderer: Example Output 21
  • 11. 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 22 © 2013 Marty Hall Customized Java EE Training: http://courses.coreservlets.com/ Java, JSF 2, PrimeFaces, HTML5, JSP, Ajax, jQuery, Spring, Hibernate, RESTful Web Services, Hadoop, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location. Questions? 23 JSF 2, PrimeFaces, Java 7 or 8, HTML5, Ajax, jQuery, Hadoop, RESTful Web Services, Android, Spring, Hibernate, Servlets, JSP, GWT, and other Java EE training.