Click here to close now.


Java IoT Authors: Elizabeth White, Pat Romanski, Liz McMillan, Chris Fleck, Gary Kaiser

Related Topics: Java IoT

Java IoT: Article

ArrayListModel with Swing's JList and JComboBox

A convenient way to use a simple collection

This article presents a data model based on a Collection implementation that can be used with Swing components JList and JComboBox. It also discusses a method to use these same concepts in constructing the user interface of an application.

Java Collections are indispensable for building any application, whether GUI or non-GUI. And the ArrayList class is a heavyweight in the java.util package. In a GUI application, the user often must choose items from a list, which can be presented in a variety of forms (drop down combo, list box, etc.). For example, the Java Swing components JList and JComboBox each have list data models - ListModel and ComboBoxListModel, respectively. Both components will react to changes in these models in keeping with the Model-View-Controller paradigm. However, neither of these models are based on a Collection, and therefore lack many of the convenient methods that the Collection interface provides. In addition, lists shown in an application are often populated from external sources (like a database) that return a Collection. Unfortunately, none of the Collection classes in Java broadcast changes to their contents, which is necessary for a user interface component to react to a true MVC data model.

The solution presented in this article to this dichotomy is simple - a subclass of the ArrayList Collection class that implements the ListModel Swing interface, the ArrayListModel class. A subclass, ArrayListComboBoxModel, which extends ArrayListModel implementing the ComboBoxModel model (which is itself a subclass of ListModel), is also presented.

The ArrayListModel class implementation is very straightforward. You can probably already imagine what the methods look like. All ArrayList methods that modify the underlying collection are augmented. The superclass ArrayList method is invoked, and then the ArrayListModel publishes the underlying collection changes to all ListDataListeners that have been added (as part of satisfying the ListModel interface contract). Listing 1 shows the implementation of the add(), remove() and set() ArrayListModel methods.

Each method calls a corresponding fire method, which notifies any ListDataListeners what exactly in the collection has changed (see Listing 2).

Other methods in ArrayListModel work very similarly. For example, the clear() method calls the superclass method, and then fires a ListDataEvent signaling that all items from the collection (model) were removed. The ListDataEvent that is sent to each ListDataListener completely describes the collection elements (actually the indices) that have been added, removed, or modified. Because ArrayListModel implements the ListModel interface, the collection can be directly assigned as the data model of a JList. The ArrayListComboBoxModel class extends ArrayListModel implementing the two additional methods in the ComboBoxModel interface: getSelectedItem() and setSelectedItem().

To see these two classes in action, download the provided code and run the ArrayListModelTest class (see Figure 1). This is a Swing application consisting of a JToolBar, a JComboBox, and a JList. There are two data models used. One is an ArrayListModel that holds all of the data items, and the other is an empty ArrayListComboBoxModel used by both the JComboBox and JList components as their data models.

Figure 1 shows the contents of the combo and list boxes after the red, blue, magenta, and orange toolbar toggle buttons, respectively, have been pressed. Pressing a toggle button on the toolbar adds an item to the data model, while un-pressing it removes the corresponding data item from the model. The data model items are each an instance of a ColorItem, an internally defined class that consists of a name and an icon property (see Listing 3).

Listing 4 shows the method in the test program that constructs the JToolBar. The method has two arguments - an Iterator of ColorItem objects and the list to manipulate on toggle button press/un-press. The list parameter is actually the ArrayListComboBoxModel, but this method simply knows it as a generic List. Note that the ActionListener that is added to each toggle button is very trivial: it simply adds or removes the data item from the list as appropriate. The visual components (JList and JComboBox) attached to the single ArrayListComboBoxModel are automatically updated. A ListCellRenderer is used to render the ColorItem icon in the JList.

You can probably think of other uses for a Collection that announces changes to itself, and not necessarily in a GUI scenario. In that case, you might object to the fact that ArrayListModel and ArrayListComboBoxModel are connected to Java Swing, both in the interfaces they implement and the ListDataEvent/ListDataListener classes they consume. One possible solution to this would be to extend ArrayList as I have done but define your own event model and listener interface that would be more generic and not Swing biased. You could then use this class in a GUI application as I've shown by writing the necessary adapters to implement the ListModel and ComboBoxModel interfaces.

ListModels in Your UI
Have you ever considered all of the list-like elements in a GUI application? Many of the user interface constructs in your application can be thought of as lists of user interface elements that potentially have to be manipulated (items are added, ordered, and removed). Examples are menus, toolbars (their buttons), tabbed panes, internal frames of an MDI application, and potentially other custom components. And quite often you need to associate an icon, a tool tip, and some other visual component with each element.

Listing 5 shows an interface, UIElement, which defines these properties. Run the UIElementTest application that is provided as part of the code for this article. The application looks similar to ArrayListModelTest and has many of the same concepts (see Figures 2 and 3). The data model consists of UIElement objects that are obtained from a UIElementFactory. (The factory returns instances of an inner class, our ColorItem object from before that now implements the UIElement interface.) The application knows nothing about the underlying visuals, just that they implement the UIElement interface. The JList knows it can show icons from the elements and a tool tip for each element. The JList is populated by selecting toggle buttons on the toolbar as above (see Figure 2).

The toolbar is constructed in a method that is nearly identical to the one shown in Listing 4, except the ColorItem parameterized type is replaced by UIElement. When an element in the list is selected, the associated visual component is obtained from the UIElement in the list and shown in the line-bordered JPanel on the right (see Figure 3).

Note the use of tool tips in both the list and panel, which are provided by the getDescription() method of the UIElement data items. The ListCellRenderer for the JList reacts to the state of the Use large icons check box, calling the appropriate UIElement get*Icon() method. A simple change to my UIElementFactory could be coded to return a completely different implementation, but the rest of the application code would not have to be touched.

As you can see, we've implemented a simple list selection method that populates another part of the application upon selection. I would bet that most Swing developers have done something very similar in one or more applications they've worked on. And we've implemented a fairly rich user interface, with icons and tool tips using a single data model, with minimal code.

In my next article, I will present more of this list-based/UIElement framework for constructing an application's user interface. We'll start with an AbstractUIElement that will serve as the base class for our user interface data model. I'll also introduce the UIElementListModel class and its view counterpart, the UIElementListView interface (with an AbstractListView base class implementation).

In this article I have described a convenient way to use a simple collection (List) as the data model for JList and JComboBox Swing components. These components react to changes in the underlying collection, remaining synchronized with the data in the model. I have also introduced the beginning of a small framework that can assist in constructing a Swing application.

More Stories By Phil Herold

Phil Herold is VP and CTO of PocketScience LLC in Research Triangle Park, NC. He has over 24 years of experience in software engineering, and has been working with Java client technologies since 1996.

Comments (4) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.

Most Recent Comments
Knut Vidar Siem 05/04/06 02:47:52 AM EDT

I noticed that ArrayListComboBoxModel is not generic although ArrayListModel is. I tried changing setSelectedItem(Object item) in ArrayListComboBoxModel to setSelectedItem(E item) (after having made the rest of the class generic with type E), but got the following error: "Name clash: The method setSelectedItem(E) of type ArrayListComboBoxModel has the same erasure as setSelectedItem(Object) of type ComboBoxModel but does not override it". Is there any way around this besides cocky casting from Object to E?

JDJ News Desk 11/07/05 11:14:43 AM EST

Java Developer's Journal - ArrayListModel with Swing's JList and JComboBox. This article presents a data model based on a Collection implementation that can be used with Swing components JList and JComboBox. It also discusses a method to use these same concepts in constructing the user interface of an application.

Java Developer's Journal News Desk 11/07/05 10:53:58 AM EST

This article presents a data model based on a Collection implementation that can be used with Swing components JList and JComboBox. It also discusses a method to use these same concepts in constructing the user interface of an application.

JDJ News Desk 11/07/05 10:13:56 AM EST

ArrayListModel with Swing's JList and JComboBox
This article presents a data model based on a Collection implementation that can be used with Swing components JList and JComboBox. It also discusses a method to use these same concepts in constructing the user interface of an application.

@ThingsExpo Stories
"Matrix is an ambitious open standard and implementation that's set up to break down the fragmentation problems that exist in IP messaging and VoIP communication," explained John Woolf, Technical Evangelist at Matrix, in this interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
As more intelligent IoT applications shift into gear, they’re merging into the ever-increasing traffic flow of the Internet. It won’t be long before we experience bottlenecks, as IoT traffic peaks during rush hours. Organizations that are unprepared will find themselves by the side of the road unable to cross back into the fast lane. As billions of new devices begin to communicate and exchange data – will your infrastructure be scalable enough to handle this new interconnected world?
SYS-CON Events announced today that Super Micro Computer, Inc., a global leader in high-performance, high-efficiency server, storage technology and green computing, will exhibit at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA. Supermicro (NASDAQ: SMCI), the leading innovator in high-performance, high-efficiency server technology is a premier provider of advanced server Building Block Solutions® for Data Center, Cloud Computing, Enterprise IT, Hadoop/Big Data, HPC and Embedded Systems worldwide. Supermi...
Nowadays, a large number of sensors and devices are connected to the network. Leading-edge IoT technologies integrate various types of sensor data to create a new value for several business decision scenarios. The transparent cloud is a model of a new IoT emergence service platform. Many service providers store and access various types of sensor data in order to create and find out new business values by integrating such data.
Too often with compelling new technologies market participants become overly enamored with that attractiveness of the technology and neglect underlying business drivers. This tendency, what some call the “newest shiny object syndrome,” is understandable given that virtually all of us are heavily engaged in technology. But it is also mistaken. Without concrete business cases driving its deployment, IoT, like many other technologies before it, will fade into obscurity.
There are so many tools and techniques for data analytics that even for a data scientist the choices, possible systems, and even the types of data can be daunting. In his session at @ThingsExpo, Chris Harrold, Global CTO for Big Data Solutions for EMC Corporation, will show how to perform a simple, but meaningful analysis of social sentiment data using freely available tools that take only minutes to download and install. Participants will get the download information, scripts, and complete end-to-end walkthrough of the analysis from start to finish. Participants will also be given the pract...
WebRTC services have already permeated corporate communications in the form of videoconferencing solutions. However, WebRTC has the potential of going beyond and catalyzing a new class of services providing more than calls with capabilities such as mass-scale real-time media broadcasting, enriched and augmented video, person-to-machine and machine-to-machine communications. In his session at @ThingsExpo, Luis Lopez, CEO of Kurento, will introduce the technologies required for implementing these ideas and some early experiments performed in the Kurento open source software community in areas ...
Electric power utilities face relentless pressure on their financial performance, and reducing distribution grid losses is one of the last untapped opportunities to meet their business goals. Combining IoT-enabled sensors and cloud-based data analytics, utilities now are able to find, quantify and reduce losses faster – and with a smaller IT footprint. Solutions exist using Internet-enabled sensors deployed temporarily at strategic locations within the distribution grid to measure actual line loads.
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Everything is re-shaping technology trends–moving away from “request/response” architecture to an “always-on” Streaming Web where data is in constant motion and secure, reliable communication is an absolute necessity. As more and more THINGS go online, the challenges that developers will need to address will only increase exponentially. In his session at @ThingsExpo, Todd Greene, Founder & CEO of PubNub, will explore the current state of IoT connectivity and review key trends and technology requirements that will drive the Internet of Things from hype to reality.
There will be 20 billion IoT devices connected to the Internet soon. What if we could control these devices with our voice, mind, or gestures? What if we could teach these devices how to talk to each other? What if these devices could learn how to interact with us (and each other) to make our lives better? What if Jarvis was real? How can I gain these super powers? In his session at 17th Cloud Expo, Chris Matthieu, co-founder and CTO of Octoblu, will show you!
Today’s connected world is moving from devices towards things, what this means is that by using increasingly low cost sensors embedded in devices we can create many new use cases. These span across use cases in cities, vehicles, home, offices, factories, retail environments, worksites, health, logistics, and health. These use cases rely on ubiquitous connectivity and generate massive amounts of data at scale. These technologies enable new business opportunities, ways to optimize and automate, along with new ways to engage with users.
Through WebRTC, audio and video communications are being embedded more easily than ever into applications, helping carriers, enterprises and independent software vendors deliver greater functionality to their end users. With today’s business world increasingly focused on outcomes, users’ growing calls for ease of use, and businesses craving smarter, tighter integration, what’s the next step in delivering a richer, more immersive experience? That richer, more fully integrated experience comes about through a Communications Platform as a Service which allows for messaging, screen sharing, video...
With major technology companies and startups seriously embracing IoT strategies, now is the perfect time to attend @ThingsExpo in Silicon Valley. Learn what is going on, contribute to the discussions, and ensure that your enterprise is as "IoT-Ready" as it can be! Internet of @ThingsExpo, taking place Nov 3-5, 2015, at the Santa Clara Convention Center in Santa Clara, CA, is co-located with 17th Cloud Expo and will feature technical sessions from a rock star conference faculty and the leading industry players in the world. The Internet of Things (IoT) is the most profound change in personal an...
WebRTC converts the entire network into a ubiquitous communications cloud thereby connecting anytime, anywhere through any point. In his session at WebRTC Summit,, Mark Castleman, EIR at Bell Labs and Head of Future X Labs, will discuss how the transformational nature of communications is achieved through the democratizing force of WebRTC. WebRTC is doing for voice what HTML did for web content.
SYS-CON Events announced today that Sandy Carter, IBM General Manager Cloud Ecosystem and Developers, and a Social Business Evangelist, will keynote at the 17th International Cloud Expo®, which will take place on November 3–5, 2015, at the Santa Clara Convention Center in Santa Clara, CA.
The Internet of Things (IoT) is growing rapidly by extending current technologies, products and networks. By 2020, Cisco estimates there will be 50 billion connected devices. Gartner has forecast revenues of over $300 billion, just to IoT suppliers. Now is the time to figure out how you’ll make money – not just create innovative products. With hundreds of new products and companies jumping into the IoT fray every month, there’s no shortage of innovation. Despite this, McKinsey/VisionMobile data shows "less than 10 percent of IoT developers are making enough to support a reasonably sized team....
As a company adopts a DevOps approach to software development, what are key things that both the Dev and Ops side of the business must keep in mind to ensure effective continuous delivery? In his session at DevOps Summit, Mark Hydar, Head of DevOps, Ericsson TV Platforms, will share best practices and provide helpful tips for Ops teams to adopt an open line of communication with the development side of the house to ensure success between the two sides.
The IoT market is on track to hit $7.1 trillion in 2020. The reality is that only a handful of companies are ready for this massive demand. There are a lot of barriers, paint points, traps, and hidden roadblocks. How can we deal with these issues and challenges? The paradigm has changed. Old-style ad-hoc trial-and-error ways will certainly lead you to the dead end. What is mandatory is an overarching and adaptive approach to effectively handle the rapid changes and exponential growth.
Today air travel is a minefield of delays, hassles and customer disappointment. Airlines struggle to revitalize the experience. GE and M2Mi will demonstrate practical examples of how IoT solutions are helping airlines bring back personalization, reduce trip time and improve reliability. In their session at @ThingsExpo, Shyam Varan Nath, Principal Architect with GE, and Dr. Sarah Cooper, M2Mi's VP Business Development and Engineering, will explore the IoT cloud-based platform technologies driving this change including privacy controls, data transparency and integration of real time context w...