Graphical programming and events

Home

Simpel frame
JDialog - Making a screen dependent on another screen
Event handling
Changing look and feel
Menus and event handling

 

Simpel frame

This example shows how to implement a simple frame, add a text, add a rectabgle and a filled rectangle and an image.

Object hierarchy:

JFrame->Frame->Window->Container->Component->Object

Classes:

Exiting the program. Unfortunately a program can't be close just by closing the frame. Instead it is necessary to implement a Windows Listener through the interface WindowListener. This means that you will have to implement alle the methods in this interface, even though you will only need the windowClosing method. See how it is impelmented in the FirstFrame class. Note: This can be implemented more simpel without using the WindowsListener interface. See the next example of Event handling.

//Subclass of JFrame and uses the WindowsListener interface
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


class FirstFrame extends JFrame implements WindowListener
{
   public FirstFrame()
   {
//  Properties of the frame
    setSize(400,400);
    setTitle("My first frame");
    setLocation(225,155);
    addWindowListener(this);
    setResizable(true);


//  Adding a panel to the pane
    Container myContentPane = getContentPane();
//  Adding a panel
    myContentPane.add(new myPanel());
   }

//  Here comes all the WindowsListener methods
    public void windowClosing(WindowEvent e) {
      System.exit(0);
    }

    public void windowClosed(WindowEvent e) {
    }

    public void windowOpened(WindowEvent e) {
    }

    public void windowIconified(WindowEvent e) {
    }

    public void windowDeiconified(WindowEvent e) {
    }

    public void windowActivated(WindowEvent e) {
    }
    public void windowDeactivated(WindowEvent e) {
    }
}
//Performs all graphical operations.
import javax.swing.*;
import java.awt.*;

class myPanel extends JPanel
{
  public void paintComponent(Graphics g)
  {//This method overrides the paintComponent method in JPanel
   //You should never call it yourself, bevause it is automatically
   //called when a part of the application needs to be redrawn

   //Force a paint
   super.paintComponent(g);

   //Set backgrounbd color for panel
   setBackground(Color.orange);

   // You can optionally set a font
   Font myFont = new Font("SansSerif",Font.BOLD + Font.ITALIC,20);
   g.setFont(myFont);

   //Optionally set a color. You can also define your own colors using
   // g.SetColor(new Color(0, 128, 125)); See the rectangle below
   g.setColor(Color.red);


   //Draw a filled rectangel and fill it with a custom color
   g.setColor(new Color(0,128,128));
   g.fill3DRect(100,10,145,30,true);

   //Set color to red and write to the screen
   g.setColor(Color.red);
   g.drawString("Henrik Frank !",102,32);


   //Show a GIF picture
   Image myImage = Toolkit.getDefaultToolkit().getImage("D:/Slam/Henrikfrank.gif");
   g.drawImage(myImage,100,80,this);

  //Draw a rectange around the picture
   g.draw3DRect(95,75,160,210,true);

   }
}
//Main class for the application
public class FirstFrame_Test
{
  public static void main(String[] args)
  { FirstFrame frame1 = new FirstFrame();
    frame1.show();
  }
}

Result:

 

JDialog - Making a screen dependent on another screen

The JDialog cam be used to make a screen dependent of another screen (disappearing when the other window is iconified, for example ). JDialog can be used both as a modal and non-modal screen. The example below shows the basic steps for making a dialog screen and call it. You will also have to add a content pane, setting size and position etc.

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
// Create JDialog
public class ViewOrder extends JDialog
{

  public ViewOrder(JFrame parent)
  { super(parent, "View sales order",true); //Parent screen, Caption, Modal 
    
  }
}

// Call JDialog
Public class ........

 private void ViewOrder()
  { ViewOrder viewOrder = new ViewOrder(this);
    viewOrder.show();

  }

 

 

Event handling

Overview of how event handling works:

The example below consists of a frame with two buttons a blueButton and a yellowButton. When the blueButton is pressed the background color changes to blue, and when the yelloeButton is pressed the background color changes to yellow. Note that there are two methods to catch which button is pressed. In the example both methods are shown, but the one is commented out.

In the example the event listner is implemented i ButtonPanel, sp it handles ist own events, but you are free to use any objects as the listener.

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


public class ButtonFrame extends JFrame
{

  public ButtonFrame()
  { //Set frame properties
    setSize(400,400);
    setTitle("Event handling");
    setLocation(225,155);

    //To avoid writing all the code for the WindowsListener interface
    //to implement Exit of the application, you can avoid the
    //WindowsListener interface by writing this code
    addWindowListener(new WindowAdapter()
      {  public void windowClosing(WindowEvent e)
         { System.exit(0);
         }
      } );
    Container myPane = getContentPane();
    myPane.add(new ButtonPanel());

  }
}

 

//Creates a panel with buttons. This class also implements a listener object,
//namely the panel itself. This mean that every time a user clicks on a button
//on the panel, the panel (Listener object) receives an ActionEvent, that
//indicates a button click. This requires that the panel implemenst an
//ActionListener interface which has one method actionPerformed

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


class ButtonPanel extends JPanel implements ActionListener
{
  public ButtonPanel()
  {//Create buttons
   yellowButton = new JButton("Yellow");
   blueButton = new JButton("Blue");

  // Note the next two lines are only necessary if you want to
  // use comand.equals to test which button has been pressed
   blueButton.setActionCommand("BluePressed");
   yellowButton.setActionCommand("YellowPressed");

   //Add buttons
   add(yellowButton);
   add(blueButton);

   //Add eventhanding to the buttons
   blueButton.addActionListener(this);
   yellowButton.addActionListener(this);
  }
  //Event handler method from the ActionListener interface
  public void actionPerformed(ActionEvent evt)
  {// The getSource method of the EventObject class (The superclass of all other
   // event classes), tells the source of the event
   Object mySource = evt.getSource();

   //Check which button was the source and  change the background color
   //accordingliy
   Color panelColor  = getBackground();
   //There are two ways to methods to check the buttons. The first is commented
   //out. The difference is that method 2 do not require an instance of the
   //button.

   /* if ( mySource == blueButton)
     panelColor = Color.blue;
   else if ( mySource == yellowButton)
     panelColor = Color.yellow; */
   String command = evt.getActionCommand();
   if (command.equals("BluePressed"))
     panelColor = Color.blue;
   else if (command.equals("YellowPressed"))
     panelColor = Color.yellow;

   //Set background color
   setBackground(panelColor);
   repaint();


   }

 private JButton yellowButton;
 private JButton blueButton;

}
//Main class to test the project
public class Test_EventHandling
{
  public static void main(String[] args)
  { ButtonFrame frame1 = new ButtonFrame();
    frame1.show();
  }
}

Result (After the yellow button has been pressed):

 

Changing look and feel

Swing programs use by default Metal look and feel, but this can be changed ti Motif or Windows. Beklow is an example of how to do this dynamically.

The code in this example is nearly indetical to thwe code from the preceeding example, but the buttons now change the look and feel of sthe application.

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


public class ButtonFrame extends JFrame
{

  public ButtonFrame()
  { setSize(400,400);
    setTitle("Event handling");
    setLocation(225,155);

    addWindowListener(new WindowAdapter()
      {  public void windowClosing(WindowEvent e)
         { System.exit(0);
         }
      } );
    Container myPane = getContentPane();
    myPane.add(new ButtonPanel());

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

class ButtonPanel extends JPanel implements ActionListener
{
  public ButtonPanel()
  {//Create buttons
   windowsButton = new JButton("Windows");
   motifButton = new JButton("Motif");
   metalButton = new JButton("Metal");

   windowsButton.setActionCommand("WindowsPressed");
   motifButton.setActionCommand("MotifPressed");
   metalButton.setActionCommand("MetalPressed");

   //Add buttons
   add(windowsButton);
   add(motifButton);
   add(metalButton);

   //Add eventhanding to the buttons
   windowsButton.addActionListener(this);
   motifButton.addActionListener(this);
   metalButton.addActionListener(this);
  }

  //Event handler from the ActionListener interface
  public void actionPerformed(ActionEvent evt)
  {  Object mySource = evt.getSource();
     String plaf = "";

     String command = evt.getActionCommand();
     if (command.equals("WindowsPressed"))
       // Windows look and feel
       plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
     else if (command.equals("MotifPressed"))
       // Motif look and feel
       plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
     else if (command.equals("MetalPressed"))
       // Metal look and feel
       plaf = "com.sun.java.swing.plaf.metal.MetalLookAndFeel";


      //Here comes the change of look and feel
      try
        { //Call the static setLookAndFeel method and give it the name of the
          //look and feel you want
          UIManager.setLookAndFeel(plaf);
          //Refresh components
          SwingUtilities.updateComponentTreeUI(this);
         }
       catch(Exception e) {}



   }

 private JButton windowsButton;
 private JButton motifButton;
 private JButton metalButton;
}
public class Test {

  public static void main(String[] args) 
  { ButtonFrame frame1 = new ButtonFrame();
    frame1.show();
  }
  
}

Result:

Metal

Windows

Motif

 

Menus and event handling

In this example the backcolor of the panel can changed either by chossing a color from a menu, pressing a button or pressing a key ( b = blue, r = red, y = yellow).

This example shows:

It also demonstarytes how to use the AbstractAction for event handling. Instead of using the Action interface which requires that you impmenet all its seven methods, it' easyer to subclass the AbstractAction class in wgixch you only have to implement an actionPerformed method.

Example:

 

 

//------------------------------------------------------------------
// CloseappAction. Performs the Exit command from the File menu
//------------------------------------------------------------------
import java.awt.event.*;
import javax.swing.*;

class CloseappAction extends AbstractAction
{
  public CloseappAction()
  { putValue(Action.NAME, "Exit");
  }
  public void actionPerformed(ActionEvent evt)
  {
    System.exit(0);
  }
}
//------------------------------------------------------------------
// ColorAction. Action object that sets the background color. 
// Called from menus, pushbuttons or key strokes.
// Note that the ColorAction class is called regardless of
// it is a blue, red or yellow action. It is only the parameters
// for the method that makes the difference
//------------------------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ColorAction extends AbstractAction
{

  public ColorAction(String p_name, Color c, Component comp)
  { //Parameters:
    //  p_name : Name of the action
    //  c      : Color the background should be changed to
    //  comp   : The componen that should be painted
    //           In this case it is always the panel

    //Save values
    putValue(Action.NAME, p_name);
    putValue("Color", c);
    target = comp;
  }

  public void actionPerformed(ActionEvent evt)
  { // Get color and change backcolor
    Color c = (Color)getValue("Color");
    target.setBackground(c);
    target.repaint();
  }

  private Component target;
}
//------------------------------------------------------------------
// MyFrame. Class that subclasses JFrame. In this class panel, menus,
// and buttons are added to he interface, and eventhandling (Action)
// is implemented. 
//------------------------------------------------------------------

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

public class MyFrame extends JFrame
{

  public MyFrame()
  {
    setTitle("Menuer");
    setSize(300,200);
    setLocation(225,155);

    addWindowListener(new WindowAdapter()
      {  public void windowClosing(WindowEvent e)
         { System.exit(0);
         }
      } );

    //Add instance of JPanel
    JPanel panel1 = new JPanel();
    Container myPane = getContentPane();
    myPane.add(panel1);


    //Define actions for menus and buttons
    Action saveFile = new SaveAction();
    Action closeApp = new CloseappAction();
    Action blueAction = new ColorAction("Blue",Color.blue,panel1);
    Action redAction = new ColorAction("Red",Color.red,panel1);
    Action yellowAction = new ColorAction("Yellow",Color.yellow,panel1);

    //-----------------------------------------------------------------
    // Keystrokes b = blue r = red y = yellow
    //-----------------------------------------------------------------
    panel1.registerKeyboardAction(blueAction,
                                  KeyStroke.getKeyStroke(KeyEvent.VK_B,0),
                                  JComponent.WHEN_IN_FOCUSED_WINDOW);

    panel1.registerKeyboardAction(redAction,
                                  KeyStroke.getKeyStroke(KeyEvent.VK_R,0),
                                  JComponent.WHEN_IN_FOCUSED_WINDOW);

    panel1.registerKeyboardAction(yellowAction,
                                  KeyStroke.getKeyStroke(KeyEvent.VK_Y,0),
                                  JComponent.WHEN_IN_FOCUSED_WINDOW);

    //-----------------------------------------------------------------
    // Buttons
    //-----------------------------------------------------------------

    panel1.add(new JButton(blueAction));
    panel1.add(new JButton(redAction));
    panel1.add(new JButton(yellowAction));

    //-----------------------------------------------------------------
    // Build the menus
    //-----------------------------------------------------------------

    //File menu
    JMenu myFileMenu = new JMenu("File");
    myFileMenu.add(saveFile);
    myFileMenu.addSeparator();
    myFileMenu.add(closeApp);

    // We are not using the Save menu, so we disable it
    saveFile.setEnabled(false);

    //Color menu
    JMenu myColorMenu = new JMenu("Color");
    myColorMenu.add(blueAction);
    myColorMenu.add(redAction);
    myColorMenu.add(yellowAction);

    //Build the menu bar
    JMenuBar myMenuBar = new JMenuBar();
    myMenuBar.add(myFileMenu);
    myMenuBar.add(myColorMenu);
    setJMenuBar(myMenuBar);
  }
}
// Test_Menus. Test class
import javax.swing.*;

public class Test_Menus
{
  public static void main(String[] args)
  { JFrame frame1 = new MyFrame();
    frame1.show();
  }
}

 

 

 

Converted from CHM to HTML with chm2web Standard 2.7 (unicode)