Java Programming   Java Programming
 |Sofia Home | Content Gallery |
Home
Syllabus
Schedule
Lessons
Assignments
Resources

Lesson 14.4 New Components

New JFC Components

The wealth of new "widgets" available in the JFC is truely staggering. Some of them--the text-editor kits, for instance--are massively complex; you could spend an almost infinte amount of time exploring all of the ins and outs. Since this is likely more time than you have--and certainly more time than I have--we're just going to look at several new classes that you might find handy. 

In this section, you'll learn about a few new Swing components that don't replace existing AWT components. These  components include:

  • JSlider, for simulating analog input
  • JProgressBar, for giving users up-to-the-second feedback
  • JToolbar for creating detachable, dockable toolbars
For each class, I'll create a simple application rather than an applet, that uses one or more of the widgets. Once you see how to get the basic functionality from the component, you will be ready to explore more on your own. 

Ready? Let's start with the JSlider.

In one of your homework assignments, you built the Spinner control, which allowed the user to enter bounded numeric input. 

The JSlider control, shown here, is useful in a similar set of circumstances.

Image: Running the JSliderApp program

Back to Top

JSlider Features

The JSlider works like the AWT Scrollbar, but looks more "professional". Here are the basic JSlider features:
  • To construct a JSlider object, you specify the orientation [HORIZONTAL or VERTICAL], along with minimum, maximum, and initial values. As with scrollbars, there are several constructors that allow you to specify fewer arguments, providing default values for those omitted.
  • A JSlider fires ChangeEvents, unlike the Scrollbar class which fires AdjustmentEvents. To respond to these events you implement the ChangeListener interface, which works very much like AdjustmentListener.
  • You can set and retrieve the current value of the JSlider through the mutator and accessor methods setValue() and getValue().
  • A JSlider will automatically paint both major and minor "tick-marks" and numeric labels at each major tick mark [as you can see in the image above].

  • This behavior is completely under your control and is manipulated by the setMajorTickSpacing(), setMinorTickSpacing(), setPaintTicks(), and setPaintLabels() methods. By default, the major and minor tick spacing is zero, and painting is off.

The JSliderApp Example

The JSliderApp program shows you how to use the basic functionality of the JSlider control. 

You can click here to download JSliderApp.java. If you want to compile and run the program on your own computer, click here to download GApp.java (if you haven't already done so.) Place both GApp.java and JSliderApp.java in the same directory when you compile and run the program.

Section 1: Fields

The JSliderApp program contains two fields: s1, a JSlider initialized like this:  
JSlider s1 = new JSlider( JSlider.HORIZONTAL,
                          0,    // Miniumum
                          150,  // Maximum
                          25    // Initial value
                        );

output, a JLabel initialized like this:

JLabel output = new JLabel("25", JLabel.CENTER);
Section 2: Constructor

The JSliderApp constructor has four major steps:

Step 1: The JSlider is initialized like this:  

s1.setMajorTickSpacing(25);   // Default is 0
s1.setMinorTickSpacing(5);    // Default is 0
s1.setPaintTicks(true);       // false by default
s1.setPaintLabels(true);    // false by default
    Note that both major and minor tick spacing is specified and the application is told to paint both labels and tick marks.

    Step 2: The JSlider is told to report any changes to the current JSliderApp object like this:
    s1.addChangeListener(this);

    For this to work, the class JSliderApp has to implement ChangeListener, which it does.

    Step 3: The JLabel output is fancied up so it looks nice like this:
    output.setFont(new Font("SansSerif", Font.BOLD, 36));
    output.setBackground(Color.white);
    output.setForeground(Color.red);

    Step 4: A BorderLayout is used to arrange the components:
    setLayout(new BorderLayout());
    add(s1, BorderLayout.NORTH);
    add(output, BorderLayout.SOUTH);

Seciton 3: The stateChanged() Method

The only other method, [besides main(), which simply launches the application], is the stateChanged() method which updates the JLabel output whenever the JSlider is moved. Here's what the stateChanged() method looks like:

    public void stateChanged(ChangeEvent e) 
    {
      output.setText("" + s1.getValue());
    }
Back to Top

JProgressBar

The JProgressBar class, shown here, allows you to keep your users informed about the progress of any lengthy operation.

Image: Running the JProgressBar application 

JProgressBar Features

Here is what you need to know to use a JProgressBar:
  • To construct a JProgressBar, you pass the orientation [which defaults to HORIZONTAL, the minium and the maximum. Note that you don't specify the initial value, because it is assumed to be zero. 
  • Because the JProgressBar is usually reinitialized at the beginning of any task, the default--no arg--constructor is often used instead.
  • You can set and retrieve the current value of the JProgressBar by using setValue() and getValue(). Normally, however, you'll just use setValue() when you want to update the user on the progress of your operation.
  • Like the JSlider class, the JProgressBar fires ChangeEvents. Most of the time, however, you won't need to respond to these.
  • You can change the appearance of the JProgressBar by using the methods setBorderPainted(), setStringPainted(), and setString(). The JProgressBarApp example program, which follows, shows how this works.

The JProgressBarApp Example

The JProgressBarApp program shows you how to use the basic functionality of the JProgressBar control. 

You can click here to download JProgressBarApp.java. If you want to compile and run the program on your own computer, click here to download GApp.java (if you haven't already done so.) Place both GApp.java and JProgressBarApp.java in the same directory when you compile and run the program.

Section 1: Fields

The JProgressBarApp program contains two fields: bar, a JProgressBar object initialized like this:  
JProgressBar bar = new JProgressBar();

btn, a JButton initialized like this:

JButton btn = new JButton("Start");

Section 2: Constructor

The JProgressBarApp constructor has three major steps:

Step 1: The JProgressBar is initialized and added to the application like this:  

bar.setBorderPainted(true);
bar.setStringPainted(true);
bar.setValue(0);

setLayout(new BorderLayout());
add(bar, BorderLayout.NORTH);

    The bar is told to paint both its border, with setBorderPainted(), and its interior, with setStringPainted(), and its initial value is set to 0.

    Step 2: The JButton is added to a FlowLayout controlled panel and then added to the bottom of the application like this:
    JPanel p = new JPanel(
               new FlowLayout(FlowLayout.CENTER));
    p.add(btn);
    add(p, BorderLayout.SOUTH);

    Using the extra panel allows the JButton to size itself appropriately.

    Step 3: The JButton is attached to an anonymous ActionListener, which starts a new Thread whenever the Start button is pressed. Here's what that looks like:
    btn.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent ae)
      {
        new Thread(JProgressBarApp.this).start();
      }
    });

Section 3: The run() Method

The JProgressBarApp implements the Runnable interface. The run() method, which is called whenever the "Start" JButton is pressed, carries out these six steps:

Step 1: The Start JButton itself is disabled like this, since the JProgressBar can only report on the progress of one task at a time:  

btn.setEnabled(false);
    Step 2: The Math.random() method is called to simulate a job of random duration. In real life, of course, you'd use the length of a file or some other "real" job metric.
    int jobLength = (int)(Math.random() * 1000) + 100;

    Step 3: Once the job lenght is known, the JProgressBar can be initialized like this:
    bar.setMaximum(jobLength);  // How long is the job?
    bar.setString(null);        // Display % while painting
    bar.setValue(0);            // Start at 0

    Calling the setString() method with null, causes the JProgressBar to paint the percentage completed inside the bar as the job progresses.

    Step 4: A loop is used to update the JProgressBar after each portion of the job is complete.
    for (int i = 0; i < jobLength; i++)
    {
      // 4. After each "chunk", update the progress bar
      bar.setValue(i);

      try { Thread.sleep(10); }
      catch (InterruptedException ie) { }
    }

    In real life, you probably wouldn't use a loop like this, but would update the bar after each packet was received, or each block was transferred, or each line-item was tallied, all depending on the application. You also wouldn't use a Thread.sleep() call, like I've used here to simulate real work being done.

    Note, however, that you do have to update the JProgressBar by calling setValue(); this does not occur automatically.

Step 5: Let the user know that the job is finished by changing the String displayed in the JProgressBar like this:

bar.setValue(jobLength);
bar.setString("Job Finished");

Step 6: Reset the "Start" JButton in anticipation of the next job like this:

btn.setEnabled(true);
Back to Top

JToolBar

The JToolBar class creates a floating window that contains JButtons and other controls.

By default, the bar is attached to the upper-left corner of the window.

Image:Running the JToolBarApp with the buttons in the default docked position.
You can move the bar by dragging 
it to any of the four sides of the main window. When you drop the toolbar it 
will "dock itself against that edge.
Image: Running the JToolBarApp with the toolbar docked on the bottom.
By dropping the toolbar outside of the main window, you can use it as a floating tool "pallete" that still sends commands to the main window.

If you close the floating toolbar, it will place itself back in the default position again.

Image: Running the JToolBarApp with the toolbar floating.

JToolBar Features

Here is what you need to know to use a JToolBar:
  • The JToolBar class has two constructors: the default constructor which is used most often, and a second constructor that allows you to supply an orientation (HORIZONTAL or VERTICAL). 
  • You can add any kind of components to the toolbar, but most of the time you'll add JButtons.
  • By default, JToolBars are "floatable." If you want your toolbars to stay put, you can send them the setFloatable(false) message.
  • When you add JToolBar to your main window, you must use a BorderLayout; it won't work right otherwise.
  • You can change the alignment of the components inside your JToolBar by using the setAlignmentX() message. This is only necessary if your toolbar contains irregularly sized components; the toolbar will look better if you avoid using different sized components, however.

The JToolBarApp Example

The JToolBarApp program shows you how to use the basic functionality of the JToolBar container. 

You can click here to download JToolBarApp.java. If you want to compile and run the program on your own computer, click here to download GApp.java (if you haven't already done so.) Place both GApp.java and JToolBarApp.java in the same directory when you compile and run the program. You'll also need the following four GIF files when you run your program. Click here to download Car1.GIF, Car2.GIF, Car3.GIF, and Car4.GIF.

Section 1: Fields

The JToolBarApp program contains one field: theLabel, a JLabel object used to display a String when a toolbar button is pressed. The JLabel is initialized like this:  
private JLabel theLabel = new JLabel("", JLabel.CENTER);

Section 2: Constructor

The JToolBarApp constructor has four steps:

Step 1: A JToolBar object is created using the default constructor like this:  

JToolBar tbar = new JToolBar();

    Step 2: The addBtn() method is called four times to add each of the four JButtons to the JToolBar. Alternatively, all of the buttons could be added in a single method.

    addBtn(tbar, "Car1.GIF", "Blue");
    addBtn(tbar, "Car2.GIF", "Red");
    addBtn(tbar, "Car3.GIF", "Yellow");
    addBtn(tbar, "Car4.GIF", "Green");

    The addBtn() method takes three arguments: 1) a reference to the JToolBar, 2) the name of the file containing the JButton's image, and 3) a String used for the tool-tip and to display when the JButton is pressed.

    Step 3: The JLabel is fancied up in anticipation of its appearance like this:
    theLabel.setFont(
        new Font("Serif", Font.BOLD+Font.ITALIC, 36));

    Step 4: The JLabel and the JToolbar are added to the panel after a BorderLayout is installed. Here's the code:
    setLayout(new BorderLayout());
    add(tbar,     BorderLayout.NORTH);
    add(theLabel, BorderLayout.CENTER);

Seciton 3: The addBtn() Method

The JToolBarApp uses an addBtn() method to create the JButtons to be placed on the JToolbar, and to hook up the JToolTips and install an ActionListener on each JButton

The addBtn() method takes these three arguments:

  1. JToolBar tbar: a reference to the JToolbar object to modify.
  2. String file: the name of the image file to use.
  3. String color: the String used for the tool-tip and action string

The addBtn() method carries out these six steps:

Step 1: The JButton is created by first using the name of the file argument to load an ImageIcon, and then using the ImageIcon to construct the button. Here's the code:  

ImageIcon icon = new ImageIcon(file);
JButton   btn  = new JButton(icon);

Step 2: The String argument color is used to initialize the tool-tip for the button like this:

    btn.setToolTipText(color);

Step 3: A finalString, containing the text that should appear when the JButton is pressed, is constructed using the argument color like this:

    final String op = "Start the " + color + " car.";

The String must be final or you can't use it inside the ActionListener which follows next.

Step 4: An anonymous ActionListener is attached to the JButton object btn, using the Stringop. Inside its actionPerformed() method, the JLabel field, theLabel, is set to display the String op:

    btn.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent evt)
      {
        theLabel.setText(op);
      }
    });

Step 5: Finally, the new JButton is added to the JToolBar, and all is at rest:

    tbar.add(btn);

Something to Talk About

In this section, you learned about three of the dozen, or so, new components available in Java2.

Before you leave this section of this lesson, point your browser at "A Visual Index to the Swing Components". Look through the list of components and find one that you find interesting. Read the tutorial material on that component and then tell us which component you chose, and why.

Please continue to the next section of this lesson.

 

Back to Top

 

Content Developed by Stephen Gilbert, Licensed under a Creative Commons License
Published by the Sofia Open Content Initiative
© 2004 Foothill-De Anza Community College District &The William and Flora Hewlett Foundation