Custom Data Models and Cell Renderers

Similar documents
The Google Web Toolkit (GWT):

Basics of programming 3. Java GUI and SWING

Simplifying GWT RPC with

jquery Ajax Support: Sending Data to the Server

JavaScript: Functions

The Prototype Framework Part III: Better OOP

Using Applets as Front Ends to

Generating the Server Response:

I VE GOT A LITTLE LIST

The Google Web Toolkit (GWT):

JavaScript: Getting Started

Android Programming: Overview

Setup and Getting Startedt Customized Java EE Training:

File I/O in Java 7: A Very Quick Summary

Lambda-Related Methods Directly in Lists and Maps

Java with Eclipse: Setup & Getting Started

Course Material Usage Rules

Jakarta Struts: An MVC Framework

The Spring Framework: Overview and Setup

For live Java EE training, please see training courses at

Charlie Garrod Bogdan Vasilescu

Java Swing. Lists Trees Tables Styled Text Components Progress Indicators Component Organizers

Developed and taught by well-known Contact author and developer. At public for details venues or onsite at your location.

Course Material Usage Rules

Invoking Native Applications from Java

Administrivia. CSSS Movie Night: Zombieland & Iron Man Date: Thurs., Mar 11 Time: 6 10 pm Location: DMP 310 Free pop & popcorn for every attendee!

For live Java EE training, please see training courses at

Uppsala University. Assignment 3. Separation into Model-View TableModel ListModel ( multiple inheritance or adapter) Renderer (delegation)

JAVA NOTES GRAPHICAL USER INTERFACES

CS111: PROGRAMMING LANGUAGE II

Core Capabilities Part 3

Tutorial: Implementing a Graphical User Interface

Goals. Lecture 7 More GUI programming. The application. The application D&D 12. CompSci 230: Semester JFrame subclass: ListOWords

CS410G: GUI Programming. The Model/View/Controller Pattern. Model. Controller. View. MVC is a popular architecture for building GUIs

Ajax with PrimeFaces

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

The Google Web Toolkit (GWT): Extended GUI Widgets

Part 2. can be held on-site at your organization.

JList. Displays a series of items The user can select one or more items Class JList extends directly class Jcomponent Class Jlist supports

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Better GUI Controls Originals of Slides and Source Code for Examples:

Intents, Intent Filters, and Invoking Activities: Part I: Using Class Name

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

JSF: The "h" Library Originals of Slides and Source Code for Examples:

Idea Requirements Steps for sending data Steps for receiving data Example: saving GUI in file Example: sending GUI across network.

HBase Java Client API

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Swing from A to Z Some Simple Components. Preface

Introduction to the JAVA UI classes Advanced HCI IAT351

Multithreaded Programming Part I: General Techniques

Unit Testing with JUnit: A Very Brief Introduction

JSF: Introduction, Installation, and Setup

Design Case Study: GUI with Swing

Swing Programming Example Number 2

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Course Material Usage Rules

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Course Material Usage Rules

Advanced Web Technology - Java Server Faces

Design Case Study: GUI with Swing (2)

Object-Oriented Programming in Java: More Capabilities

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Object-Oriented Programming in Java:

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Rich Interfaces with jquery UI: Part 1 Setup and Basic Widgets

Advanced Features. venues, or customized versions can be held on-site at your organization.

CSS Basics. Slides 2016 Marty Hall,

Handling Cookies. For live Java EE training, please see training courses at

Java Programming Lecture 6

Basic Object-Oriented Programming in Java

CS 349 / SE 382 Design Patterns. Professor Michael Terry January 21, 2009

MIT AITI Swing Event Model Lecture 17

Chapter 14. More Swing

Library Part II: Visual Effects

Network Programming: Servers

Swing. Component overview. Java UI, summer semester 2017/2018 1

Graphical User Interface (GUI)

CoSc Lab # 6 (The Model) Due Date: Part I, Experiment classtime, Tuesday, Nov 6 th, 2018.

Webservices In Java Tutorial For Beginners Using Netbeans Pdf

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

The Google Web Toolkit (GWT): Extended GUI Widgets

Computer Science 210: Data Structures. Intro to Java Graphics

Graphical User Interfaces. Comp 152

Class 16: The Swing Event Model

Clean up and remove examples that show panels! Make slide summarizing all the HTML ones and equivalent GWT names

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Outline. Composite Pattern. Model-View-Controller Pattern Callback Pattern

GUI Event Handlers (Part II)

Managed Beans III Advanced Capabilities

Chapter 6 Introduction to Defining Classes

Object-Oriented Programming Design. Topic : User Interface Components with Swing GUI Part III

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Chapter 17 Creating User Interfaces

Is image everything?

12/22/11. Copyright by Pearson Education, Inc. All Rights Reserved.

Overview. Topics in This Section

Graphical User Interface (GUI)

Lecture 18 Java Graphics and GUIs

Transcription:

2010 Marty Hall Advanced Swing & MVC Custom Data Models and Cell Renderers Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/course-materials/java5.html 2 Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jquery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring, Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, Customized or customized Java EE Training: versions http://courses.coreservlets.com/ can be held on-site at your organization. Contact hall@coreservlets.com for details. Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

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 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 iti data. dt Custom cell renderers Changing gthe 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 ec 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 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. */ 8 public void valuechanged(listselectionevent event) { if (!event.getvalueisadjusting()) { Object value = samplejlist.getselectedvalue(); if (value!= null) { valuefield.settext(value.tostring()); 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 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 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. */ 12 public void actionperformed(actionevent event) { int index = samplemodel.getsize(); samplemodel.addelement("entry " + (index+1)); ((JComponent)getContentPane()).revalidate(); samplejlist.setselectedindex(index); samplejlist.ensureindexisvisible(index); 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 { 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) { 15 public void removelistdatalistener(listdatalistener l) {

Actual Data 16 public class JavaLocationCollection { private static JavaLocation[] defaultlocations = { new JavaLocation("Belgium", "near Liege", "flags/belgium.gif"), gif") new JavaLocation("Brazil", "near Salvador", "flags/brazil.gif"), if") new JavaLocation("Colombia", "near Bogota", "flags/colombia.gif"),... ;... JavaLocation has tostring plus 3 fields Country, comment, flag file 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); tf t(di l F t) content.add(samplejlist); 17

JList with Custom Model: Example Output 18 JList with Custom Cell Renderer 19 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?

Custom Renderer: Example Code 20 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); Custom Renderer: Example Output 21

Summary 22 Simple static JList Pass array of strings to JList constructor Simple changeable JList Pass Df DefaultListModel lli Mdlto 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 2010 Marty Hall Questions? 23 Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.