March 2, 2021
Hot Topics:

Creating Interactive GUIs with Swing's MVC Architecture Part 2: Dynamic View for a Static Model

  • By Vlad Kofman
  • Send Email »
  • More Articles »


The technique presented in this article relies on the separable architecture of Swing. The source code has a full listing of the custom model and filtering models as well as main the GUI code. It undoubtedly can be applied to any Swing object and imbedded into any graphical application that requires real-time manipulation of a presentation. Custom filters can do any number of tasks and be easily added later on in the development cycles, preserving existing functionality and introducing new features.

Download Source Code

Listing 1

class Moon
   public String name;
   public String planet;
   public int population;
   public String atmosphere;

   Moon(String name, String planet, String atmosphere, int population)
      this.name = name;
      this.planet = planet;
      this.population = population;
      this.atmosphere = atmosphere;

   public String toString()
      return this.name;

Listing 2

public void setModelData(Moon[] data) {
   for (int i = 0; i < data.length; i++) {
      Moon moon = data[i];
      Object row[] = new Object[] {moon.name, moon.planet,
Note: The fireTableDataChanged() method is one of methods that indicate to the visual components to sync with the model and therefore refresh the presentation.

Listing 3

public synchronized void reallocateIndexes() {

   int rowCount = model.getRowCount();


   // Iterate through the model

   for (int z = 0; z < rowCount; z++) {
      String planet = (String) model.getValueAt(z, 0);
      if (filter.equals("All")) {
         indexList.add(new Integer(z));
      } else if (filter.equals(planet))
         indexList.add(new Integer(z));

Listing 4