Java Programming (Intermediate), Sample Programs, Set 1

Published:  December 19, 2001
By Richard G. Baldwin

Java Programming Tutorial # 9010


Preface

This is the first in a miniseries of lessons designed specifically to help the students in my "Java Programming (Intermediate)" course study for their exams.  However, others may find the lesson useful as well.

The lesson consists of a set of relatively simple programs, each designed to illustrate one or more important Java concepts.  The concepts involved are identified in the comments at the beginning of each program.

The programs are designed to illustrate the code without providing a detailed discussion of the code.  You are referred to the other lessons in my online Java tutorials for detailed discussions of the OOP concepts illustrated by these programs.

Sample Programs

Program Samp202.java
 
/*File Samp202 
Copyright 2001, R.G.Baldwin
Rev 12/03/01

Tested using JDK 1.3 under Win

Illustrates:
Disabling the X button in the upper 
right of the JFrame.  It doesn't
terminate the program or hide the 
JFrame when it is clicked.  The Close
selection on the control menu is
similarly disabled.

Border layout manager.

Providing a JButton to terminate the
program and return control to the 
operating system when it is clicked.

Placing the JButton in the center of a
JFrame.

Using an anonymous inner class action
listener to support the JButton.

The default Swing Look & Feel 
(probably Metal);


The behavior of the program is as 
follows:
  
The GUI is constructed of Swing 
components using Sun's default look and
feel (probably Metal).

A single JFrame object appears on the 
screen with a width of 200 pixels and a
height of 100 pixels.  A single JButton
appears in the center of the frame with
the caption Quit.

Student name appears in the banner at 
the top of the JFrame object.

When the user clicks on the button with
the X in the top-right corner of the 
JFrame, nothing happens.  In other 
words, this button is totally disabled.
The Close selection on the control 
menu is similarly disabled.

When the user clicks the button with 
the caption Quit, the program 
terminates and returns control to the 
operating system.

**************************************/

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

public class Samp202 {
  public static void main(
                        String[] args){
    new Samp202GUI();
  }//end main
}//end class Samp202
//===================================//

class Samp202GUI {
  public Samp202GUI(){//constructor
    //create a new JFrame object
    JFrame theFrame = new JFrame();
    theFrame.setSize(200,100);
    theFrame.setTitle(
                    "Richard Baldwin");
    JButton quitButton = 
                   new JButton("Quit");
    theFrame.getContentPane().
              add(quitButton,"Center");
               
    //Set the desired action for when
    // the user clicks the X button in
    // the upper right of the JFrame.
    theFrame.setDefaultCloseOperation(
           JFrame.DO_NOTHING_ON_CLOSE);

    theFrame.setVisible(true);
    
    //Register an anonymous action 
    // lister to terminate the program
    // when the user clicks the Quit 
    // button
    quitButton.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                        ActionEvent e){
          System.exit(0);
        }//end actionPerformed()
      }//end new ActionListener
    );//end addActionListener

  }//end constructor
}//end class Samp202GUI

Program Samp204.java
 
/*File Samp204 
Copyright 2001, R.G.Baldwin
Rev 12/03/01

Tested using JDK 1.3 under Win

Illustrates:
Motif L&F (JButtons are outlined in 
red).

Swing JButton, JToggle, and JLabel 
components.

Border layout manager.

Changing background color of component.

Making a component opaque.


The behavior of the program is as 
follows:
  
The GUI is constructed of Swing 
components using Sun's motif look and 
feel (when the JFrame is active, the 
gray JButton in Motif L&F button is 
outlined in red).

A single JFrame object appears on the 
screen with a width of 200 pixels and a
height of 150 pixels.  A JButton
appears at the top of the frame with
the caption "JButton in Motif L&F".

A JToggleButton appears at the bottom
of the JFrame with the caption 
"JToggleButton in Motif L&F".

An opaque JLabel with a red background
appears in the middle of the JFrame
with the text "JLabel in Motif L&F". 
(This text changes when the buttons are
clicked.)

Student name appears in the banner at 
the top of the JFrame object.

When the user clicks on either of the
large buttons, the text in the JLabel 
changes to indicate which button was 
clicked.

When the user clicks on the button with
the X in the top-right corner of the 
JFrame, the program terminates and 
returns control to the operating 
system.

**************************************/

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

public class Samp204 {
  public static void main(
                        String[] args){
    new Samp204GUI();
  }//end main
}//end class Samp204
//===================================//

class Samp204GUI {
  JLabel label;
  public Samp204GUI(){//constructor
    //Create a new JFrame object
    JFrame theFrame = new JFrame();
    theFrame.setSize(200,150);
    theFrame.setTitle(
                    "Richard Baldwin");
                    
    //Create a JButton object and add
    // it to the JFrame under the
    // default BorderLayout manager.
    JButton buttonA = new JButton(
               "JButton in Motif L&F");
    theFrame.getContentPane().
                  add(buttonA,"North");
               
    //Create a new JToggleButton and
    // add it to the JFrame.
    JToggleButton buttonB = 
         new JToggleButton(
         "JToggleButton in Motif L&F");
    theFrame.getContentPane().
               add(buttonB,"South");

    //Create a new JLabel object, give
    // it a red opaque background, and
    // add it to the JFrame.
    label = new JLabel(
                "JLabel in Motif L&F");
    label.setOpaque(true);
    label.setBackground(Color.red);
    theFrame.getContentPane().
                   add(label,"Center");

    //Set the L&F for the GUI
    String plafClassName = 
       "com.sun.java.swing.plaf.motif."
                  + "MotifLookAndFeel";
    try{
       UIManager.setLookAndFeel(
                        plafClassName);
     }catch(Exception ex){
               System.out.println(ex);}
       
     //Cause the L&F to become visible.
     SwingUtilities.
       updateComponentTreeUI(theFrame);

    //Make the whole thing visible
    theFrame.setVisible(true);
    
    //Register an anonymous action 
    // lister to modify the text in the
    // JLabel when the user clicks the
    // JButton.
    buttonA.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                        ActionEvent e){
          label.setText(
                "JButton was clicked");
        }//end actionPerformed()
      }//end new ActionListener
    );//end addActionListener
     
    //Register an anonymous action 
    // lister to modify the text in the
    // JLabel when the user clicks the
    // JToggleButton.
    buttonB.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                        ActionEvent e){
         label.setText(
         "JToggle button was toggled");
        }//end actionPerformed()
      }//end new ActionListener
    );//end addActionListener

    //Register an anonymous window
    // listener to terminate the 
    // program when the user clicks the
    // close button on the JFrame.
    theFrame.addWindowListener(
                   new WindowAdapter(){
      public void windowClosing(
                        WindowEvent e){
        System.exit(0);}});
      
  }//end constructor
}//end GUI class

Program Samp206.java
 
/*File Samp206 
Copyright 2001, R.G.Baldwin
Rev 12/03/01

Tested using JDK 1.3 under Win

Illustrates:
Windows L&F (probably possible only on
Windows systems).

Swing JButton, JToggle, and JLabel 
components.

Border layout manager.

Changing background color of component.

Making a component opaque.


The behavior of the program is as 
follows:
  
The GUI is constructed of Swing 
components using Sun's Windows look and
feel.

A single JFrame object appears on the 
screen with a width of 200 pixels and a
height of 150 pixels.  A JButton
appears at the top of the frame with
the caption "JButton in Windows L&F".

A JToggleButton appears at the bottom
of the JFrame with the caption 
"JToggleButton in Windows L&F".

An opaque JLabel with a red background
appears in the middle of the JFrame
with the text "JLabel in Windows L&F". 
(This text changes when the buttons are
clicked.)

Student name appears in the banner at 
the top of the JFrame object.

When the user clicks on either of the
large buttons, the text in the JLabel 
changes to indicate which button was 
clicked.

When the user clicks on the button with
the X in the top-right corner of the 
JFrame, the program terminates and 
returns control to the operating 
system.

**************************************/

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

public class Samp206 {
  public static void main(
                        String[] args){
    new Samp206GUI();
  }//end main
}//end class Samp206
//===================================//

class Samp206GUI {
  JLabel label;
  public Samp206GUI(){//constructor
    //Create a new JFrame object
    JFrame theFrame = new JFrame();
    theFrame.setSize(200,150);
    theFrame.setTitle(
                    "Richard Baldwin");
                    
    //Create a JButton object and add
    // it to the JFrame under the
    // default BorderLayout manager.
    JButton buttonA = new JButton(
             "JButton in Windows L&F");
    theFrame.getContentPane().
                  add(buttonA,"North");
               
    //Create a new JToggleButton and
    // add it to the JFrame.
    JToggleButton buttonB = 
       new JToggleButton(
       "JToggleButton in Windows L&F");
    theFrame.getContentPane().
               add(buttonB,"South");

    //Create a new JLabel object, give
    // it a red opaque background, and
    // add it to the JFrame.
    label = new JLabel(
              "JLabel in Windows L&F");
    label.setOpaque(true);
    label.setBackground(Color.red);
    theFrame.getContentPane().
                   add(label,"Center");

    //Set the L&F for the GUI
    String plafClassName = 
       "com.sun.java.swing.plaf." +
          "windows.WindowsLookAndFeel";
    try{
       UIManager.setLookAndFeel(
                        plafClassName);
     }catch(Exception ex){
               System.out.println(ex);}
       
     //Cause the L&F to become visible.
     SwingUtilities.
       updateComponentTreeUI(theFrame);

    //Make the whole thing visible
    theFrame.setVisible(true);
    
    //Register an anonymous action 
    // lister to modify the text in the
    // JLabel when the user clicks the
    // JButton.
    buttonA.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                        ActionEvent e){
          label.setText(
                "JButton was clicked");
        }//end actionPerformed()
      }//end new ActionListener
    );//end addActionListener
     
    //Register an anonymous action 
    // lister to modify the text in the
    // JLabel when the user clicks the
    // JToggleButton.
    buttonB.addActionListener(
      new ActionListener(){
        public void actionPerformed(
                        ActionEvent e){
         label.setText(
         "JToggle button was toggled");
        }//end actionPerformed()
      }//end new ActionListener
    );//end addActionListener

    //Register an anonymous window
    // listener to terminate the 
    // program when the user clicks the
    // close button on the JFrame.
    theFrame.addWindowListener(
                   new WindowAdapter(){
      public void windowClosing(
                        WindowEvent e){
        System.exit(0);}});
      
  }//end constructor
}//end GUI class

Program Samp208.java
 
/*File Samp208 
Copyright 2001, R.G.Baldwin
Rev 12/03/01

Tested using JDK 1.3 under Win

Illustrates:
A classic mouse listener for coordinate
 data.
 
Use of the getContentPane method for
adding a component to a JFrame object.

Use of an anonymous inner class window
listener object.

Extending a listener adapter class.

Implementing a listener interface.

Use of ordinary (non-anonymous) inner
classes.

Use of paintComponent method instead of
paint method.  The paintComponent 
method is required when custom painting
objects instantiated from subclasses of
JComponent.

Two different approaches for making 
certain that the background is cleared
so that old coordinates go away when 
new coordinates are displayed.



The behavior of the program is as 
follows:
  
The GUI is constructed of Swing 
components.

A single JFrame object appears on the 
screen with a width of 200 pixels and a
height of 500 pixels.

Student name appears in the banner at 
the top of the JFrame object.

When the user clicks on the button with
the X in the top-right corner of the 
JFrame, the program terminates and
returns control to the operating
system.

When a mouse press occurs within the 
JFrame object, the program displays the
mouse coordinates near the point of 
the mouse press, with the horizontal 
coordinate (X) being displayed first 
and the vertical coordinate (Y) being 
displayed second, and the two separated
by a comma and a space, as in 69, 72

**************************************/

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

public class Samp208 {
  public static void main(
                        String[] args){
    new Samp208GUI();
  }//end main
}//end class Samp208
//===================================//

class Samp208GUI {
  public Samp208GUI(){//constructor
    //create a new JFrame object
    JFrame theFrame = new JFrame();
    theFrame.setSize(200,500);
    theFrame.setTitle(
                    "Richard Baldwin");

    DisplaySpace displayWindow = 
                    new DisplaySpace();
    theFrame.getContentPane().
           add(displayWindow,"Center");
    theFrame.setVisible(true);
        
    //Instantiate and register a 
    // Listener object that will 
    // process mouse events to 
    // determine and display the 
    // coordinates when the user 
    // presses the mouse button
    // within the JFrame.
    displayWindow.addMouseListener(
      new MProc1(displayWindow));
  
    //Instantiate and register a window
    // listener to terminate the 
    // program when the user clicks the
    // close button on the JFrame. This
    // is an anonymous inner class.
    theFrame.addWindowListener(
                   new WindowAdapter(){
      public void windowClosing(
                        WindowEvent e){
        System.exit(0);}});
      
  }//end constructor
//===================================//

//This is an inner class.
class DisplaySpace extends JPanel{

  int clickX;
  int clickY;
  
  //Override paintComponent instead of
  // paint for subclasses of 
  // JComponent.
  public void paintComponent(
                           Graphics g){
    //Alternate approaches for clearing
    // the background.  Either will
    // do the job.
//  super.paintComponent(g);
    setOpaque(false);
    
    //Draw the new coordinates
    g.drawString("" + clickX + ", " + 
               clickY, clickX, clickY);
  }//end paint()
}//end inner class DisplaySpace
//===================================//
 
//This is an inner class.
//This listener class monitors for 
// mouse presses and displays the 
// coordinates of the mouse pointer 
// when the mouse is pressed.
class MProc1 implements MouseListener{
  DisplaySpace refToWin; 
  
  //constructor
  MProc1(DisplaySpace inWin){
    //save ref to window
    refToWin = inWin;
  }//end constructor

  //Empty interface methods
  public void mouseClicked(
                        MouseEvent e){}
  public void mouseReleased(
                        MouseEvent e){}
  public void mouseEntered(
                        MouseEvent e){}
  public void mouseExited(
                        MouseEvent e){}

  //Override the mousePressed method to
  // determine and display the 
  // coordinates when the mouse is 
  // pressed.  
  public void mousePressed(
                         MouseEvent e){
    //Get X and Y coordinates of mouse
    // pointer and store in the JPanel
    // object.
    refToWin.clickX = e.getX();
    refToWin.clickY = e.getY();
    //Request a repaint to display 
    // coordinate information
    refToWin.repaint();
  }//end mousePressed()
}//end inner class MProc1

}//end outer class Samp208GUI

Program Samp218.java
 
/*File Samp218 
Copyright 2001, R.G.Baldwin
Rev 12/03/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the Iterator interface.  Also 
requires that the student not become 
confused by downcasting.


The behavior of the program is as 
follows:

The program will accept, store, 
retrieve, and display an arbitrary 
number of command-line arguments.

For example, for a command-line input 
of:

java Samp218 a bc def ghij

The output is:

Samp218
Richard Baldwin
a
bc
def
ghij

**************************************/
import java.util.*;

class Samp218{
  public static void main(
                        String[] args){

    Samp220Container container = 
                new Samp220Container();
    for(int cnt = 0; cnt < args.length;
                                cnt++){
      container.storeData(args[cnt]);
    }//end for loop
   
    Object iterator = container.
                         getIterator();
    while(((Iterator)iterator).
                            hasNext()){
      System.out.println(
          ((Iterator)iterator).next());
    }//end while loop
  }//end main()
}//end controlling class
//===================================//

class Samp220Container extends Vector{
  
  Samp220Container(){//constructor
    System.out.println("Samp218");
    System.out.println(
                    "Richard Baldwin");
  }//end constructor 
  //---------------------------------//

  void storeData(String a){
    this.addElement(a);
  }//end storeData
  //---------------------------------//
  
  //This method will return an Iterator
  // object as Type Object to a using 
  // program.
  Object getIterator(){
    return this.iterator();
  }//end getIterator()
  //---------------------------------//

}//end class Samp220Container

Program Samp226.java
 
/*File Samp226 
Copyright 2001, R.G.Baldwin
Rev 12/16/01

Tested using JDK 1.3 under Win

Illustrates:
Instantiating an object that extends
Component and overrides paint.

Overriding paint to display a name in
the Component object.

Placing the Component object in a Frame
for display.

The program displays your name 
generally in the center of a 200 x 100 
Frame when executed.
**************************************/

import java.awt.*;
import java.awt.event.*;

public class Samp226 extends Component{
  public void paint(Graphics screen){
    screen.drawString(
              "Richard Baldwin",50,35);
  }//end paint()
   
  public static void main(
                        String[] args){
    //Create a Frame for the Component
    // to run in
    Frame myFrame = new Frame(
                    "Richard Baldwin");
    myFrame.setSize(200,100);
    //Instantiate a Component object.
    Component component = 
                         new Samp226();
    //Add the Component object to the 
    // Frame object    
    myFrame.add(component);
    //Make the whole thing visible    
    myFrame.setVisible(true);
     
    //This code will terminate the 
    // program when the user clicks 
    // the close button on the Frame.
    myFrame.addWindowListener(
      new WindowAdapter(){
        public void windowClosing(
                        WindowEvent e){
          System.exit(0);}});
  }//end main
} //End Samp226

Program Samp228.java
 
/*File Samp228 
Copyright 2001, R.G.Baldwin
Rev 12/16/01

Tested using JDK 1.3 under Win

Illustrates:
A Java program and all files necessary 
to run it as an applet.

Here are the contents of an appropriate
HTML file:
  
<HTML><BODY>
<applet code="Samp228.class" 
        width=200 height=100>
</applet>
</BODY></HTML>

The program displays your name 
generally in the center of a 200 x 100
applet window when run as an applet
using the appletviewer program.

**************************************/

import java.applet.Applet;
import java.awt.*;

public class Samp228 extends Applet {
  public void paint(Graphics screen) {
    screen.drawString(
              "Richard Baldwin",50,35);
  }//end paint()
} //End Samp228

Program Samp238.java
 
/*File Samp238 
Copyright 2001, R.G.Baldwin
Rev 12/06/01

Tested using JDK 1.3 under Win

Illustrates:
Use of the TreeSet class to eliminate
duplicate elements in a Collection.

Use of TreeSet class to sort elements
in a collection into their natural
order.

Use of Iterator to display elements
in the collection.

The program adds three names to a 
Collection object with each name being
added twice.  The Collection object
is instantiated from the TreeSet class,
which implements the Collection
interface and also implements the Set
interface.

The program then uses an Iterator to
fetch and display the contents of the
Collection object.  The output is as
shown below.  Note that duplicate 
names have been eliminated and the
names are sorted into natural order.

Dick
Harry
Tom
**************************************/

import java.util.*;
class Samp238{
  public static void main(
                        String[] args){
    Collection var = new TreeSet();
    String me = "Dick";
    String myFriend = "Tom";
    String myOtherFriend = "Harry";
    var.add(me);
    var.add(myFriend);
    var.add(myOtherFriend);
    var.add(me);
    var.add(myFriend);
    var.add(myOtherFriend);

    Iterator iter = var.iterator();
    while(iter.hasNext()){
      System.out.println(iter.next());
    }//end while loop
    System.out.println();
  }//end main
}//end class Exam1Prob04  

Program Samp242.java
 
/*File Samp242 
Copyright 2001, R.G.Baldwin
Rev 12/19/01

Tested using JDK 1.3 under Win

Illustrates:
Use of setBounds to control the initial
location of a frame on the screen and 
the location of a Panel in a Frame.

Use of a null layout manager to allow
for absolute positioning of components
in a Frame.
**************************************/
import java.awt.*;
import java.awt.event.*;

public class Samp242 {
  public static void main(
                        String[] args){
    new Samp242GUI();
  }//end main
}//end class Samp242
//-----------------------------------//

class Samp242GUI {
  public Samp242GUI(){//constructor
    Frame myFrame1 = new Frame();
    myFrame1.setBounds(50,50,300,150);
    myFrame1.setTitle(
        "Copyright 2001, R.G.Baldwin");
    myFrame1.setLayout(null);
    MyPanel myPanel = new MyPanel();
    myFrame1.add(myPanel);       
    myFrame1.setVisible(true);
   
    //Instantiate and register a 
    // Listener object which will 
    // terminate the program when the 
    // user closes the window.
    myFrame1.addWindowListener(
                         new WProc1());    
        
  }//end constructor
  
//===================================//
//Begin inner classes
class MyPanel extends Panel{
  MyPanel(){//constructor
    setBounds(50,50,100,50);  
    setBackground(Color.red);
  }//end constructor
}//end class MyPanel
//===================================//

//The following listener is used to 
// terminate the program when the user 
// closes the Frame object.
class WProc1 extends WindowAdapter{
  public void windowClosing(
                        WindowEvent e){
    System.exit(0);
  }//end windowClosing()
}//end class WProc1
//===================================//
  
}//end class Samp250GUI

Program Samp244.java
 
/*File Samp244 
Copyright 2001, R.G.Baldwin
Rev 12/19/01

Tested using JDK 1.3 under Win

Illustrates:
Use of setBounds to control the 
location of a JPanel in a JPanel.

Use of a JPanel to create a display 
area inside a JFrame.

Use of the name property of a 
component to identify the source of
a mouse event.

Use of default BorderLayout manager of
the content pane of a JFrame.

Use of the default "Center" position of
a BorderLayout manager to fill the
remaining space in a content pane.

Use of a null layout manager to allow
for absolute positioning of components
in a JPanel.

Explicitly setting the L&F of the
JFrame to Motif.

Use of the paintComponent method to
draw coordinate values on a JPanel.

Use of super.paintCompoennt to clear
the background of a JPanel and erase
old coordinate values.
**************************************/
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Samp244 {
  public static void main(
                        String[] args){
    new Samp244GUI();
  }//end main
}//end class Samp244
//-----------------------------------//

class Samp244GUI {
  public Samp244GUI(){//constructor
    JFrame myJFrame = new JFrame();
    myJFrame.setBounds(50,75,300,150);
    myJFrame.setTitle(
        "Copyright 2001, R.G.Baldwin");
    DisplayArea displayArea = 
                     new DisplayArea();
    displayArea.setName("displayA");
    displayArea.setLayout(null);
    myJFrame.getContentPane().add(
             new JButton(
              "Dummy Button"),"South");
    myJFrame.getContentPane().add(
                          displayArea);
    
    MyJPanel myJPanel = new MyJPanel();
    myJPanel.setName("displayB");    
    displayArea.add(myJPanel);
    myJFrame.setVisible(true);
   
    String plafClassName = 
     "com.sun.java.swing.plaf.motif." +
                    "MotifLookAndFeel";
    try{
       UIManager.setLookAndFeel(
                        plafClassName);
     }catch(Exception ex){
               System.out.println(ex);}
       
     //Cause the L&F to become visible.
     SwingUtilities.
       updateComponentTreeUI(myJFrame);
   
    //Instantiate and register a 
    // Listener object which will 
    // terminate the program when the 
    // user closes the window.
    myJFrame.addWindowListener(
                         new WProc1());
    
    //Instantiate and register a 
    // Listener object which will 
    // process mouse events on either 
    // the DisplayArea object or the 
    // myJPanel object.
    MouseProc mouseProcCmd = 
               new MouseProc(
                 displayArea,myJPanel);
    displayArea.addMouseListener(
                         mouseProcCmd);
    myJPanel.addMouseListener(
                         mouseProcCmd);
  }//end constructor
  
//===================================//
//Begin inner class definitions
class DisplayArea extends JPanel{
  int xCoor;
  int yCoor;
  
  DisplayArea(){
    setBackground(Color.red);
  }//end constructor
  
  public void paintComponent(
                           Graphics g){
    super.paintComponent(g);
    //Display coordinate information 
    // on the object
    g.drawString("" + yCoor + ", " + 
                  xCoor, xCoor, yCoor);
  }//end paintComponent()
}//end class DisplayArea
//-----------------------------------//

class MyJPanel extends JPanel{
  int xCoor;
  int yCoor;

  MyJPanel(){//constructor
    setBounds(25,15,100,50);  
    setBackground(Color.green);
  }//end constructor
  
  public void paintComponent(
                           Graphics g){
    super.paintComponent(g);
    //Display coordinate information 
    // on the object
    g.drawString("" + xCoor + ", " + 
                  yCoor, xCoor, yCoor);
  }//end paintComponent()
}//end class MyJPanel
//-----------------------------------//
//This listener class monitors for 
// mouse presses and displays the 
// coordinates of the mouse pointer 
// when the mouse is pressed.  The 
// listener object distinguishes 
// between two different objects on the
// basis of their component names and 
// displays the coordinate information
// on the object which generated the 
// mouse event.

class MouseProc extends MouseAdapter{
  //Save references to the objects here
  DisplayArea refToJFrame;
  MyJPanel refToJPanel;
  
  MouseProc(DisplayArea inJFrame,
                    MyJPanel inJPanel){
    refToJFrame = inJFrame;
    refToJPanel = inJPanel;
  }//end constructor

  //Override the mousePressed() method 
  // to respond whenever the mouse is 
  // pressed on one of the objects.  
  // Distinguish between the objects 
  // using the component name and 
  // display the coordinates of the 
  // mouse on the correct object.
  public void mousePressed(
                         MouseEvent e){
     if( e.getComponent().getName().
        equals(refToJFrame.getName())){
      refToJFrame.xCoor = e.getX();
      refToJFrame.yCoor = e.getY();
      refToJFrame.repaint();
    }else{
      refToJPanel.xCoor = e.getX();
      refToJPanel.yCoor = e.getY();
      refToJPanel.repaint();
    }//end if-else
  }//end mousePressed()
}//end class MouseProc
//-----------------------------------//

//The following listener is used to 
// terminate the program when the user 
// closes the JFrame object.
class WProc1 extends WindowAdapter{
  public void windowClosing(
                        WindowEvent e){
    System.exit(0);
  }//end windowClosing()
}//end class WProc1
//-----------------------------------//
}//end class Samp244GUI definition

Program Samp246.java
 
/*File Samp246 
Copyright 2001, R.G.Baldwin
Rev 12/06/01

Tested using JDK 1.3 under Win

Illustrates:
Use of setBounds to control the initial
location of a Frame on the screen.  Two
Frame objects are placed so that they
overlap on the screen.

Use of the name property of a 
component to identify the source of
a mouse event.

Registering the same window listener on
two different Frame objects.

Registering the same mouse listener on
two different Frame objects.

Use of the paintComponent method to
draw coordinate values on a JPanel.

Mixing Swing and AWT components

Motif L&F

Difference between PaintComponent and
Paint methods.

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

public class Samp246 {
  public static void main(
                        String[] args){
    new Samp246GUI();
  }//end main
}//end class Samp246
//-----------------------------------//

class Samp246GUI {
  public Samp246GUI(){//constructor
    MyCustomFrame myFrame1 = 
                  new MyCustomFrame();
    myFrame1.setBounds(0,0,300,150);
    myFrame1.setName("customFrame");
    myFrame1.setBackground(
                          Color.green);
    myFrame1.setTitle(
        "Copyright 2001, R.G.Baldwin");
    myFrame1.add(new Button(
               "Dummy Button"),"East");
    myFrame1.setVisible(true);
    
    Frame myFrame2 = new Frame();
    myFrame2.setBounds(50,50,300,150);
    myFrame2.setTitle(
        "Copyright 2001, R.G.Baldwin");
    DisplayArea displayArea = 
                     new DisplayArea();
    displayArea.setName("displayB");
    displayArea.setBackground(
                            Color.red);
    myFrame2.add(new JButton(
              "Dummy JButton"),"West");
    myFrame2.add(displayArea);
    myFrame2.setVisible(true);
   
    String plafClassName = 
     "com.sun.java.swing.plaf.motif." +
                    "MotifLookAndFeel";
    try{
       UIManager.setLookAndFeel(
                        plafClassName);
     }catch(Exception ex){
               System.out.println(ex);}
     SwingUtilities.
       updateComponentTreeUI(myFrame2);
   
    WProc1 winProcCmd1 = new WProc1();
    myFrame1.addWindowListener(
                          winProcCmd1);
    myFrame2.addWindowListener(
                          winProcCmd1);
    
    MouseProc mouseProcCmd = 
               new MouseProc(
                 myFrame1,displayArea);
    myFrame1.addMouseListener(
                         mouseProcCmd);
    displayArea.addMouseListener(
                         mouseProcCmd);
    
  }//end constructor
  
//===================================//
//Begin inner class definitions
class DisplayArea extends JPanel{
  int xCoor;
  int yCoor;
  
  public void paintComponent(
                           Graphics g){
    super.paintComponent(g);
    g.drawString("" + xCoor + ", " + 
                  yCoor, xCoor, yCoor);
  }//end paintComponent()
}//end class DisplayArea
//-----------------------------------//

class MyCustomFrame extends Frame{
  int xCoor;
  int yCoor;
  
  public void paint(Graphics g){
    g.drawString("" + xCoor + ", " + 
                  yCoor, xCoor, yCoor);
  }//end paint()
}//end class DisplayArea
//-----------------------------------//

class MouseProc extends MouseAdapter{
  MyCustomFrame refToFrame1;
  DisplayArea refToFrame2;
  
  MouseProc(MyCustomFrame inFrame1,
                 DisplayArea inFrame2){
    refToFrame1 = inFrame1;
    refToFrame2 = inFrame2;
  }//end constructor

  public void mousePressed(
                         MouseEvent e){
     if( e.getComponent().getName().
        equals(refToFrame1.getName())){
      refToFrame1.xCoor = e.getX();
      refToFrame1.yCoor = e.getY();
      refToFrame1.repaint();
    }else
      if(e.getComponent().getName().
        equals(refToFrame2.getName())){
      refToFrame2.xCoor = e.getX();
      refToFrame2.yCoor = e.getY();
      refToFrame2.repaint();
    }//end if-else
  }//end mousePressed()
}//end class MouseProc
//-----------------------------------//

class WProc1 extends WindowAdapter{
  public void windowClosing(
                        WindowEvent e){
    System.exit(0);
  }//end windowClosing()
}//end class WProc1
//-----------------------------------//

}//end class Samp246GUI definition

Program Samp248.java
 
/*File Samp248 
Copyright 2001, R.G.Baldwin
Rev 12/16/01

Tested using JDK 1.3 under Win

Illustrates:
Use of setBounds to control the initial
location of a frame on the screen and 
the location of a JToggleButton in a 
JPanel.

Use of a JPanel to create a display 
area inside a JFrame.

Use of the name property of a 
component to identify the source of
a mouse event.

Use of default BorderLayout manager of
the content pane of a JFrame.

Use of the default "Center" position of
a BorderLayout manager to fill the
remaining space in a content pane.

Use of a null layout manager to allow
for absolute positioning of components
in a JPanel.

Explicitly setting the L&F of one
JFrame to Metal and the L&F of another
JFrame to Motif.

Registering the same window listener on
two different JFrame objects.

Registering the same mouse listener on
three different objects.

Use of the paintComponent method to
draw coordinate values on a component.

Use of super.paintCompoennt to clear
the background of a component and erase
old coordinate values.

The program displays two JFRame objects
on the screen. Each contains a JButton
with no listener registered on the
JButton objects.

One JFrame also contains a 
JToggleButton  A mouse listener is
registered on this component causing
coordinate values to be displayed 
whenever the mouse is pressed on it.

A mouse listener is also registered on
the two JFrame objects causing 
coordinate values to be displayed when
the mouse is pressed on them.

A WindowListener is registered on both
JFrame objects to terminate the program
when the close button is pressed on
either JFrame object.

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

public class Samp248 {
  public static void main(
                        String[] args){
    new Samp248GUI();
  }//end main
}//end class Samp248
//-----------------------------------//

class Samp248GUI {
  public Samp248GUI(){//constructor
    JFrame myJFrame1 = new JFrame();
    myJFrame1.setBounds(0,150,300,150);
    myJFrame1.setTitle(
         "Copyright 2001,R.G.Baldwin");
    DisplayArea displayAreaA = 
                     new DisplayArea();
    displayAreaA.setName("displayA");
    displayAreaA.setBackground(
                          Color.green);
    myJFrame1.getContentPane().add(
      new JButton("A JButton"),"East");
    myJFrame1.getContentPane().add(
                         displayAreaA);
    myJFrame1.setVisible(true);
    
    JFrame myJFrame2 = new JFrame();
    myJFrame2.setBounds(0,0,300,150);
    myJFrame2.setTitle(
         "Copyright 2001,R.G.Baldwin");
    DisplayArea displayAreaB = 
                     new DisplayArea();
    displayAreaB.setName("displayB");
    displayAreaB.setLayout(null);
    displayAreaB.setBackground(
                          Color.white);
    myJFrame2.getContentPane().add(
                new JButton(
                 "A JButton"),"North");
    myJFrame2.getContentPane().add(
                         displayAreaB);
    
    MyJToggleButton myJToggleButton = 
                 new MyJToggleButton();
    myJToggleButton.setName(
                           "displayC");
    displayAreaB.add(myJToggleButton);
    myJFrame2.setVisible(true);
    
    String plafClassName = 
     "com.sun.java.swing.plaf.motif." +
                    "MotifLookAndFeel";
    try{
       UIManager.setLookAndFeel(
                        plafClassName);
     }catch(Exception ex){
               System.out.println(ex);}
       
     //Cause the L&F to become visible.
     SwingUtilities.
                 updateComponentTreeUI(
                            myJFrame1);
   
    plafClassName = 
            "javax.swing.plaf.metal." +
                    "MetalLookAndFeel";
                    
    try{
       UIManager.setLookAndFeel(
                        plafClassName);
     }catch(Exception ex){
               System.out.println(ex);}
       
     //Cause the L&F to become visible.
     SwingUtilities.
                 updateComponentTreeUI(
                            myJFrame2);
   
    //Instantiate and register a 
    // Listener object which will 
    // terminate the program when the 
    // user closes either window.
    WProc1 winProcCmd1 = new WProc1();
    myJFrame1.addWindowListener(
                          winProcCmd1);
    myJFrame2.addWindowListener(
                          winProcCmd1);
    
    //Instantiate and register a 
    // Listener object which will 
    // process mouse events on either 
    // DisplayArea object or the 
    // myJToggleButton object.
    MouseProc mouseProcCmd = 
      new MouseProc(displayAreaA,
         displayAreaB,myJToggleButton);
    displayAreaA.addMouseListener(
                         mouseProcCmd);
    displayAreaB.addMouseListener(
                         mouseProcCmd);
    myJToggleButton.addMouseListener(
                         mouseProcCmd);
    
  }//end constructor
  
//===================================//
//Begin inner class definitions
class DisplayArea extends JPanel{
  int xCoor;
  int yCoor;

  DisplayArea(){//constructor
    setSize(300,150);
  }//end constructor
  
  public void paintComponent(
                           Graphics g){
    super.paintComponent(g);
    //Display coordinate information 
    // on the object
    g.drawString("" + yCoor + ", " + 
                  xCoor, xCoor, yCoor);
  }//end paintComponent()
}//end class DisplayArea
//-----------------------------------//

class MyJToggleButton 
                 extends JToggleButton{
  int xCoor;
  int yCoor;

  MyJToggleButton(){//constructor
    setBounds(100,25,100,50);
    setBackground(Color.yellow);
  }//end constructor
  
  public void paintComponent(
                           Graphics g){
    super.paintComponent(g);
    g.drawString("" + yCoor + ", " 
                + xCoor, xCoor, yCoor);
  }//end paintComponent()
}//end class MyJToggleButton
//-----------------------------------//
//This listener class monitors for 
// mouse presses and displays the 
// coordinates of the mouse pointer 
// when the mouse is pressed.  The 
// listener object distinguishes 
// between three different objects on 
// the basis of their component names 
// and displays the coordinate 
// information on the visual object 
// which generated the mouse event.

class MouseProc extends MouseAdapter{
  DisplayArea refToJFrame1;
  DisplayArea refToJFrame2;
  MyJToggleButton refToJToggleButton;
  
  //constructor
  MouseProc(DisplayArea inJFrame1,
     DisplayArea inJFrame2,
     MyJToggleButton inJToggleButton){
    refToJFrame1 = inJFrame1;
    refToJFrame2 = inJFrame2;
    refToJToggleButton = 
                       inJToggleButton;
  }//end constructor

  //Override the mousePressed() method 
  // to respond whenever the mouse is 
  // pressed on one of the objects.  
  // Distinguish between the three 
  // objects using the component name 
  // and display the coordinates of 
  // the mouse on the correct object.
  public void mousePressed(
                         MouseEvent e){
     if( e.getComponent().getName().
                   equals(refToJFrame1.
                            getName()))
    { //display coordinates on one 
      // object
      refToJFrame1.xCoor = e.getX();
      refToJFrame1.yCoor = e.getY();
      refToJFrame1.repaint();
    }else if( e.getComponent().
         getName().equals(refToJFrame2.
                            getName()))
    { //display coordinates on  
      // another object
      refToJFrame2.xCoor = e.getX();
      refToJFrame2.yCoor = e.getY();
      refToJFrame2.repaint();
    }else
    {//display coordinates on the third
     // object
      refToJToggleButton.xCoor = 
                              e.getX();
      refToJToggleButton.yCoor = 
                              e.getY();
      refToJToggleButton.repaint();
    }//end if-else
  }//end mousePressed()
}//end class MouseProc
//-----------------------------------//

//The following listener is used to 
// terminate the program when the user 
// closes either JFrame object.
class WProc1 extends WindowAdapter{
  public void windowClosing(
                        WindowEvent e){
    System.exit(0);
  }//end windowClosing()
}//end class WProc1
//-----------------------------------//
}//end class Samp248GUI definition


Copyright 2001, Richard G. Baldwin.  Reproduction in whole or in part in any form or medium without express written permission from Richard Baldwin is prohibited.

About the author

Richard Baldwin is a college professor (at Austin Community College in Austin, TX) and private consultant whose primary focus is a combination of Java and XML. In addition to the many platform-independent benefits of Java applications, he believes that a combination of Java and XML will become the primary driving force in the delivery of structured information on the Web.

Richard has participated in numerous consulting projects involving Java, XML, or a combination of the two.  He frequently provides onsite Java and/or XML training at the high-tech companies located in and around Austin, Texas.  He is the author of Baldwin's Java Programming Tutorials, which has gained a worldwide following among experienced and aspiring Java programmers. He has also published articles on Java Programming in Java Pro magazine.

Richard holds an MSEE degree from Southern Methodist University and has many years of experience in the application of computer technology to real-world problems.

baldwin.richard@iname.com

-end-