Monday, February 26, 2007

Lecture 18

  1. Create the component

  2. Create a listener

  3. Create an instance of the listener

  4. Add (“register”) the listener to the component

  5. Add the component to the JFrame

  • You can skip steps 2 – 4 if your program doesn’t require an action

  • How does this work?

    • Create a visual interface

    • A JFrame

    • A button

  • Then implement a listener

    • this is the code which you wish to perform once the button Is pressed

  • register the listener to the button

    • when the button is pressed

    • Java calls ActionPerformed

      • You do not call ActionPerformed

      • ActionPerformed is an automation in Java

  • Registration tells Java to call it when the button is pressed

    • And then reads the listener


  • can add a line of text using JLabel component

    1. create a component

    2. JLabel MyLabel = new JLabel(“My Label”);

    3. Skip

    4. Skip

    5. Skip

    6. Add the component to the JFrame

      • MyWindow.add(MyLabel);


  • We require a way to arrange multiple objects within a window

  • Java technique which accomplishes that is the layout

    • BorderLayout

    • GridLayout

      • FlowLayout

  • JFrame contains a method setLayout()

  • MyWindow.setLayout(Layout l);

  • Executing this sets the layout of the window to the layout object l.

  • Andrew is not sure that setLayout take a Layout as its param, he will find out for next class


  • When Adding a component also specify a region in which It goes

    • MyWindow.add(MyButton, BorderLayout.North/East/South/West/Center)


GridLayout GL;

GL = new GridLayout (2, 3)

//2 = rows, 3 = columns


JLabel Label 1 = new JLabel (“1”)

MyWindow.add (Label 1);

Flow Layout

flowLayout FL;

FL = newFlowLayout ();

MyWindow.setLayout (FL);

// add components

Good JFrame Practice

  • Up to now, everything has been done in main

  • This is bad practice because the window is an object

  • It should be treated as such

  • We are creating a modification of JFrame

  • Use inheritance

No comments: