Lecture 7A
Java Roadmap
CustomComponent
Swing
Running Swing
SwingDesign-
Demo
JButton      -    Demo
JPanel & Layouts
                    -   
Demo
JComponent's
                    -   
Demo
More JComponent's
                    -   
Demo
Swingset    -   
Demo
Converting Code
Using Plug-in
Lectures

1A: Introduction
1B: Java Intro
2A: BuildingBlocks
2B: Objects
3A: More Objects
3B: Exceptions
       & Threads
4A: Waves
4B: Nuclear &
       Particle
5A: AWT
5B: More AWT
      & Graphics
6A:Detectors &
      Simulation
6B: LHC/Atlas &
     RandomSims    
7A: Swing
7B: Java2D
8A: Java Apps
8B: Dialogs &
    MoreClasses
9A: Java I/O
9B: Utilities,
        Unicode
10A: More
    Threading
10B: File
    Handling
11A: Array,Print,
    Images
11B: SimplePhysics
    Simulation
12A: Tips &
    Techniques
12B: More Tips &
    Techniques
13A: Satellite
    
Simulations
13B: Intro to Java
    Networking
14A: Java Servers
14B: HTTP Server
15A: ServerClient
15B: ServerClient
   Expt.Simulation
16A: Course
          Review
16B: ExerciseTest
        Discussion

    Contacts
    Description
    Exercises
    Index
    Outline
    Q&A
    Resources
    StudentInfoForm
    Student Pages
    What's New

 

Home : Lectures : Lecture 7A : More JComponents 2
Swing - More JComponents 2
JCheckBox, JRadioButton, JList & JScrollbar

The demo applets here will illustrate several more of the Swing JComponent's.

Checkboxes are useful for providing options that can be applied simultaneously:

 CheckBoxDemo with Plug-in
(without Plug-in)

CheckBoxDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CheckBoxDemo extends JApplet
                   implements ActionListener {

  JCheckBox red,green,blue;
  OutputPanel outputPanel;

  public void init()  {

    // Create a JPanel and then create three
    // JCheckBox objects and add them to the panel.

    JPanel p = new JPanel();

    red = new JCheckBox("Red");
    red.addActionListener(this);
    p.add(red);

    green = new JCheckBox("Green");
    green.addActionListener(this);
    p.add(green);

    blue = new JCheckBox("Blue");
    blue.addActionListener(this);
    p.add(blue);

    // Put the buttons at the bottom of the applet
    getContentPane().add(p, "South");

    // An instance of OutputPanel will be put on
    // the top of the applet and used to show
    // the colors chosen by the buttons.

    outputPanel = new OutputPanel();

    getContentPane().add(outputPanel, "Center");

  }

  // This class is the actionlistener for the
  // check boxes. So the events come here when
  // the user clicks on a box.

  public void actionPerformed(ActionEvent evt){

    // Set each of the RGB values at either
    // 0 or 255 (0xFF in hex format).

    int cr = (red.isSelected()   ? 0xFF : 0);
    int cg = (green.isSelected() ? 0xFF : 0);
    int cb = (blue.isSelected()  ? 0xFF : 0);

    // Then tell the output panel to show this
    // combination of colors.

    outputPanel.setColor(cr,cg,cb);
  }
}

// Create a JPanel sub-class called OutputPanel.
// It provides a method to set its color
// plus a paintComponent method.

class OutputPanel extends JPanel{
  Color bgColor = Color.black;

  // Set the color by passing the 3 RGB component
  // values (with ranges 0-255).

  void setColor(int cr, int cg, int cb){
    bgColor = new Color(cr,cg,cb);
    repaint();
  }

  // For Swing components you must override
  // paintComponent() rather than paint().

  public void paintComponent(Graphics g){
    // First call the paintComponent of the
    // superclass, in this case JPanel.

    super.paintComponent(g);

    // Now we fill a rectangle the size of the
    // panel with the chosen color.

    g.setColor(bgColor);
    g.fillRect(0, 0, getWidth(), getHeight() );
  }
}

Radio buttons are for those cases where only one of several options can be chosen:

 RadioButtonDemo with Plug-in
(without Plug-in)

RadioButtonDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class RadioButtonDemo extends JApplet
                   implements ActionListener {

  JRadioButton red,green,blue;
  OutputPanel outputPanel;

  public void init()  {

    // Create a JPanel and then create a ButtonGroup
    // with three JRadioButton's. Then add them to
    // the panel

    JPanel p = new JPanel();

    // RadioButtons need to be organized with a
    // ButtonGroup object.

    ButtonGroup group = new ButtonGroup();

    red = new JRadioButton("Red", true);
    red.addActionListener(this);
    // Add the JRadioButton instance to both the
    // ButtonGroup and the panel.

    group.add(red);
    p.add(red);

    green = new JRadioButton("Green", false);
    green.addActionListener(this);
    group.add(green);
    p.add(green);

    blue = new JRadioButton("Blue", false);
    blue.addActionListener(this);
    group.add(blue);
    p.add(blue);

    getContentPane().add(p, "South");

    outputPanel = new OutputPanel();
    // Initialize panel to red.
    outputPanel.setColor(0xFF,0,0);

    getContentPane().add(outputPanel, "Center");

  }

  // This class is the actionlistener for the
  // radio buttons. So the events come here when
  // the user clicks on a box.

  public void actionPerformed(ActionEvent evt)  {
    // Default color component values.
    int cr=0;
    int cg=0;
    int cb=0;
    // Only one button can be selected at a time
    // so choose one color and then set the output
    // panel color.

    Object source = evt.getSource();
    if( source == red)
        cr = 0xFF;
    else if(source == green)
        cg = 0xFF;
    else if(source == blue)
        cb = 0xFF;

    outputPanel.setColor(cr,cg,cb);
  }
}

class OutputPanel.....same as above.

 

The JList component provides a way of offering a list of items from which the user can select.

Depending on how the JList instance is configured, either a single item can be selected, or multiple items selected.

 ListDemo with Plug-in
(without Plug-in)

 

ListDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

// The following package needed for ListSelectionListener
// interface and ListSelectionEvent names.

import javax.swing.event.*;

public class ListDemo extends JApplet
             implements ListSelectionListener {

  JRadioButton red,green,blue;
  OutputPanel outputPanel;

  public void init()  {

    // Create a JPanel and then create three
    // a JList with several color choices and
    // and add it to the control panel.

    JPanel p = new JPanel();

    String [] colors = {
      "Red","Green","Blue","Yellow","White","Black"};

    JList colorList = new JList(colors);

    // Show only 4 items in the list at a time.
    colorList.setVisibleRowCount(4);

    // Allow only one of the items to be selected.
    colorList.setSelectionMode(
      ListSelectionModel.SINGLE_SELECTION)
;

    // Select initially the top item.     colorList.setSelectedIndex(0);

    colorList.addListSelectionListener(this);

    // Add to a JScrollPane so that we can have
    // a scroller to view other items.

    JScrollPane scrollPane = new JScrollPane(colorList);
    p.add(scrollPane)
;

    getContentPane().add(p, "South");

    outputPanel = new OutputPanel();
    // Initialize panel to red.
    outputPanel.setColor(0xFF,0,0);

    getContentPane().add(outputPanel, "Center");

  }

  // This class implements the ListSelectionListener
  // so events come to this valueChanged method.

  public void valueChanged(ListSelectionEvent evt)  {

    // Default color component values.
    int cr=0;
    int cg=0;
    int cb=0;

    // Get the reference to the JList object
    JList source = (JList)evt.getSource();
    // and get an array of the selected items.
    Object [] values = source.getSelectedValues();

    // In this case only one value can be selected
    // so just look at first item in array.

    String colorSelected = (String)values[0];
    if( colorSelected.equals("Red") )
        cr = 0xFF;
    else if(colorSelected.equals("Green") )
        cg = 0xFF;
    else if(colorSelected.equals("Blue") )
        cb = 0xFF;
    else if(colorSelected.equals("Yellow") ){
        cr = 0xFF;
        cg = 0xFF;
    }else if(colorSelected.equals("White") ){
        cr = 0xFF;
        cg = 0xFF;
        cb = 0xFF;
    }

    outputPanel.setColor(cr,cg,cb);
  }
}

class OutputPanel.....same as above.

Scrollbars allow the user to choose from a continuous range of values rather than from discrete values in a set of radio buttons or in a list.

 ScrollBarDemo with Plug-in
(without Plug-in)

ScrollBarDemo.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ScrollBarDemo extends JApplet
                           implements AdjustmentListener{
  JLabel redLabel;
  JLabel greenLabel;
  JLabel blueLabel;

  JScrollBar red;
  JScrollBar green;
  JScrollBar blue;

  OutputPanel outputPanel;

  public void init() {

    Container contentPane = getContentPane();

    // Create a JPanel and then create three
    // JScrollBar objects plus a JLabel for each.
    // Add these objects to the panel via a
    // GridLayout manager.

    JPanel p = new JPanel();
    p.setLayout(new GridLayout(3, 2));

    p.add(redLabel = new JLabel("Red 0"));

    // Setup the scroll bar to lay horizontal.
    //
    // initial value = 0
    // visible area  = 0 - scrollbar used here as
    //                     a slider rather to scroll
    //                     through text area.
    //       minimum = 0
    //       maximum = 255
    //

    p.add(red = new JScrollBar(Adjustable.HORIZONTAL,
         0, 0, 0, 255)
);
    // Set the increment value at each step in the
    // scroll bar movement.

    red.setBlockIncrement(8);
    red.addAdjustmentListener(this);

    p.add(greenLabel = new JLabel("Green 0"));
    p.add(green = new JScrollBar(Adjustable.HORIZONTAL,
         0, 0, 0, 255)
);
    green.setBlockIncrement(8);
    green.addAdjustmentListener(this);

    p.add(blueLabel = new JLabel("Blue 0"));
    p.add(blue = new JScrollBar(Adjustable.HORIZONTAL,
         0, 0, 0, 255)
);
    blue.setBlockIncrement(8);
    blue.addAdjustmentListener(this);

    contentPane.add(p, "South");

    outputPanel = new OutputPanel();
    outputPanel.setColor(0, 0, 0);
    contentPane.add(outputPanel, "Center");
  }

  // This class is the AdjustmentListener for the
  // scroll bar. So the events come here when the
  // scroll bar is moved.

  public void adjustmentValueChanged(AdjustmentEvent evt){

    // Use the labels to show the numerical values of the
   
// scroll bar settings.
    redLabel.setText(  "Red "   + red.getValue()  );
    greenLabel.setText("Green " + green.getValue());
    blueLabel.setText( "Blue "  + blue.getValue() );

    // Get the values from each scroll bar and pass
   
// them as the color component values.
   
outputPanel.setColor(red.getValue(), green.getValue(),
                         blue.getValue()
);

    outputPanel.repaint();
  }
}

class OutputPanel.....same as above.

 

Home Lectures Resources Index Contacts Students


Physics Simulations with JavaTM
KTH, Kurskod: 5A1418
Curator: Clark S. Lindsey