Java/Swing  Step-by-Step Guide

Tutorial 5

Input/Output GUI Elements


GOAL: Work and gain experience using GUI elements that serve as both input and output from the application and user
PREREQUISITES: Tutorial 4

Create Check Box
  1. Drag a JCheckbox to the window.  Left-Mouse-Button double-click on it to change the text property to "Timer Control Sliders".  Right-Mouse-Button single-click on it, and then Change Variable Name... to "chkTimerControlSliders"
  2. In the Source view of the JFrame, we will create a class that responds to the Timer object.  While we could put this all into an anonymous event listener, the code is complicated enough that a separate class is better.  Add the following to your SwingExampleFrame class (above main is a good place for it).
     public void actionPerformed(java.awt.event.ActionEvent evt) {

    // Each time the timer goes off the total number of seconds will be incremented
    // and the timer text field will be updated to display the total seconds elapsed.
    m_seconds++;
    timerEcho.setText(m_seconds + ": Seconds have passed");

    // If the ControlSliders check box is selected, then the horizontal and
    // vertical sliders will also be decremented.
    if(chkTimerControlSliders.isSelected()){
    hSliderBar.setValue(hSliderBar.getValue() - 1);
    vSliderBar.setValue(vSliderBar.getValue() - 1);
    }

    // When both sliders reach 0, the ControlSliders checkbox will be unselected.
    if((hSliderBar.getValue()==0) && (vSliderBar.getValue()==0))
    chkTimerControlSliders.setSelected(false);
    }
    }
  3. Change the SwingExampleFrame's constructor so that it creates a Timer object, that will call the above code, like so:
     public SwingExampleFrame() {
    initComponents();
    // Creates a timer that will go off every 1000 ms.
    javax.swing.Timer t = new javax.swing.Timer(1000, new TimerListener());
    t.start(); // Start the timer
    }


» Written by William Frankhouser (wjf2@washington.edu)
» Adapted by Michael Panitz.
» Advised by Kelvin Sung (ksung@washington.edu) as part of the project sponsored by the National Science Foundation under Grant No. 0442420. Any opinions, findings, and conclusions or recommendations expressed in this material are those of the author(s) and do not necessarily reflect the views of the National Science Foundation.
» Produced in the "Essential Concepts for Building Interactive Computer Graphics Applications", A.K. Peters, Ltd.