Example: Building a Java GUI

Steven Zeil

Last modified: Mar 21, 2014

Contents:
1. Develop the Model
2. Develop the layout of those elements
3. Add listeners to the elements
4. Implement custom drawing

The StringArt Program



The Process

  1. Develop the model
  2. Select the GUI elements to portray the model
  3. Develop the layout of those elements
  4. Add listeners to the elements
  5. Implement custom drawing

1. Develop the Model

The model is the underlying data that is being manipulated and portrayed by the program.

// The Model
  private Color[] colors;
  private int stepSize = 5;


Select the GUI elements to portray the model

2. Develop the layout of those elements

There are two common approaches to laying out GUIs


Programmed Approach in Java

Uses a combination of


GUI Container Elements


GUI Elements in StringArt


Structural Summary


Where Did the Control Panel Come From?


Programming the Containment

GUI container elements are handled much like utility containers

containment.java


Laying out the components

Java has several layout managers.


Using Border Layout

  public void createAndShowGUI() {
      window = new JFrame();
      // set up the components
      window.getContentPane().setLayout (
            new BorderLayout());
    
      canvas = new JPanel () {
          ⋮
          }
      };
      ⋮
    window.getContentPane().add (canvas, 
             BorderLayout.CENTER);
    
    JPanel controls = new JPanel();
      ⋮
    window.getContentPane().add (controls, 
              BorderLayout.SOUTH);
      ⋮


Miscellaneous Appearance Code

appearance.java

Most of the highlighted code is self-explanatory

3. Add listeners to the elements

We need to implement some behaviors


Closing the Window

Here we use a shorthand technqiue rather than create a full-fledged functor to listen:

public void createAndShowGUI() {
    window = new JFrame();
       ⋮
  window.setDefaultCloseOperation(
    (startedInAnApplet)
        ? JFrame.DISPOSE_ON_CLOSE 
        : JFrame.EXIT_ON_CLOSE);
       ⋮
}


Entering the Step Size

This is handled by an ActionListener, which is triggered when we hit Enter/Return with the cursor positioned in the text box.

 stepSizeIn = new JTextField (""+stepSize, 5);
 controls.add (stepSizeIn);
 stepSizeIn.addActionListener (new ActionListener()
   {
     public void actionPerformed(ActionEvent e) {
       try {
         Integer newSize = new Integer(
                       stepSizeIn.getText());
         stepSize = newSize.intValue();
            ⋮
       } catch (Exception ex) {};
     }
   });


Color Selection

Buttons notify an ActionListener when a button is clicked

    colorChooser1 = new JButton("Color 1");
    controls.add (colorChooser1);
    setColor(colorChooser1, colors[0]);
    colorChooser1.addActionListener (
        new ColorChooser(colorChooser1, 0));
    
    colorChooser2 = new JButton("Color 2");
    controls.add (colorChooser2);
    setColor(colorChooser2, colors[1]);
    colorChooser2.addActionListener (
        new ColorChooser(colorChooser2, 1));

We implement this with our own subclass of ActionListener, ColorChooser.


ColorChooser

colorchooser.java

The JColorChooser invoked in the first line pops up the stnadard Java color selection box.

4. Implement custom drawing

The proper moment for drawing GUI elements is a bit tricky.

Think of some of the various situations in which all or part of a window needs to be redrawn:

Any of these can force part or all of an application to need redrawing. Some of these (state changes) are under direct program control. Most are not.


paint and repaint

    canvas = new JPanel () {
        public void paint (Graphics g) {
          super.paint(g);
          drawLines (g, getSize());
        }
      };

Paint and Repaint


Repainting the StringArt Canvas

repainting.java


The Full Listing

StringArt.java