Title: TCU CoSc 10403 Programming with Java
1TCU CoSc 10403 Programming with Java
2What is an Event in Java?
- Defn - in programming, an event is (in most
cases) an action taken by the user. - Types of events
- 1) the user presses a key or clicks the mouse
button. - 2) the user clicks on a button, a choice, a
checkbox, etc. - Thus, rather than a program be executed as a long
sequence of instructions, like the following - We have sections of the program which can be
activated by the occurrence of an event.
Sequential Execution
3Basic Event Handling
- The GUI is responsible for constructing the user
interface and for connecting (registering)
widgets to listeners - The listener part implements the appropriate
interface for the type of event(s) of interest. - The code (in the action handler) that performs
the programs action associated with the event(s).
4The Event Loop
- In Java, the programmer creates a section(s) of
code (methods) which will be automatically
invoked whenever an event happens. - Details of the event (the name of the button that
was pressed, the choice box that was changed, the
radio button that was pressed, etc) are returned
to the programmer so that the required processing
takes place. - In Java, events are classified into several
classes (we will study the following) - 1) ActionEvents - generated whenever a change
is made to a JButton, JCheckBox, JComboBox,
JTextField, or JRadioButton.. - 2) TextEvents - generated whenever a change is
made to an AWT TextArea or an AWT TextField (not
implemented in swing). - 3) ItemEvents - generated whenever a change is
made to a JButton, JCheckBox, JComboBox, or
JRadioButton.
The software cycles around in a loop waiting for
an event to occur
Button pressed?
Choice made?
Event loop
Radio button pressed?
Etc
5Event Handlers that We Will Study
Listener interfaces and related classes
6Using Action Events
- Import the required event classes thus giving
your applet the power to receive and handle
messages, such as those sent when a button is
clicked or the mouse is moved. - import java.awt.event.
- State that the class implements an
ActionListener. - public class IRS extends JApplet implements
ActionListener - 34. Declare and create a button variable, giving
it an appropriate name. - JButton calculate new JButton("Calculate
now") - 5. Add the button to the applet window.
- add(calculate)
- 6. Inform the button that this object will
respond to button events, using
addActionListener. - calculate.addActionListener(this)
7What are the Parts?
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class IRS extends JApplet implements
ActionListener -
- // normal declarations for JTextFields,
JLabels, JPanels, and - // other widgets needed for the user interface
- JButton calculate new JButton("Calculate
now") // button for user to use - public void init()
-
- // define layout methods to be used and add
the various - // GUI components to create the user interface
-
- somepanel.add(calculate)
-
- calculate.addActionListener(this)
Step 1
Step 2
Steps 3 4
Step 5
Step 6
Step 7
8Action Event Demo1
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton("Submit")
-
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
-
- public void actionPerformed(ActionEvent e)
-
- System.out.println("Button pressed")
9Action Event Demo2
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton("Submit")
-
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
-
- public void actionPerformed(ActionEvent e)
-
- String s b1.getText() //Gets the label off
of the button
10Action Event Demo3
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton("Submit")
-
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
-
- public void actionPerformed(ActionEvent e)
-
- String s e.getActionCommand() //returns the
command string associated with event
11Action Event Demo4
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton(Finis")
-
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
- b1.setActionCommand("Finish up button
pressed") -
- public void actionPerformed(ActionEvent e)
-
There may be times that a different internal name
is more meaningful than the string used to label
the button (e.g., an application meant to be used
in France might have a button with a French label
but but with a more meaningful internal English
name.
12Action Event Demo5
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton("Submit")
- JButton b2 new JButton("Cancel")
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
- add(b2)
- b2.addActionListener(this)
-
The problem is that this program does not
distinguish between the two buttons.
13Action Event Demo6
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton("Submit")
- JButton b2 new JButton("Cancel")
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
- b1.setActionCommand("Process a Submit Order")
- add(b2)
- b2.addActionListener(this)
- b2.setActionCommand("Process a Order
Cancellation")
14Event Demo(getActionCommand on JTextField)
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JTextField tf1 new JTextField(8)
- JTextField tf2 new JTextField(20)
- public void init()
-
- setLayout(new FlowLayout())
- add(tf1)
- tf1.addActionListener(this)
- tf1.setActionCommand("Text entered into Name
Field") - add(tf2)
- tf2.addActionListener(this)
- tf2.setActionCommand("Text entered into
Address Field")
15Action Event Demo7
- import java.awt.
- import javax.swing.
- import java.awt.event.
- public class ActionEventDemo1 extends JApplet
implements ActionListener -
- JButton b1 new JButton("Submit")
- JButton b2 new JButton("Cancel")
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
- add(b2)
- b2.addActionListener(this)
-
16The JFrame Class
- A Frame is a top-level window with a title and a
border. The size of the frame includes any area
designated for the border. - Calling setVisible(true) makes the frame appear
onscreen. Sometimes you might see the show()
method used instead. The two usages are
equivalent. - By default, the frame window will appear in the
top left corner of the screen. Another location
can be specified using the setlocation() method
on the frame. - The default layout manager is BorderLayout.
- Five steps to get a frame to work
- Create the frame JFrame frame new
Jframe( some title ) - Set the layout frame.setLayout(new
FlowLayout()) - Instantiate the components and add them to the
frame. Frame.add(button1) - Size the frame frame.setSize(200,500)
- Show the frame frame.setVisible(true)
- ????
17The JFrame Class
- Two Constructors that are of interest to us
- JFrame()?Constructs a new frame that is initially
invisible. - JFrame(String title)?Creates a new, initially
invisible Frame with the specified title. - Sizing a JFrame??JFrame frame1 new
JFrame(CoSc 10403) ?. . . - frame1.setSize(100,100) //will appear in upper
left area of screen - frame1.setSize(100,100) //frame of size 100x100
pixels - frame1.setLocation(100,50) //placement 100
pixels over, 50 pixels down - frame1.setBounds(100,50,100,100) //same as
above?
18The JFrame Class
- Useful methods that are of interest to us
- void pack()?Size the window on the basis of the
minimum size to fit all components added to the
frame (i.e., just wide enough to fit the text in
the bottom of the frame and high enough for each
component to display properly). - void setSize(int, int)?Set the total size of the
window - void setBounds(int, int, int, int)?Set the size
and position of the window. - void setLocation(int, int)?Set the location of
the upper left corner of the window - void remove(Component comp)
- Removes the specified component from this
container. - void removeAll()
- Removes all components from the JFrame.
- void setLayout(LayoutManager manager)
- Sets the layout of this component.
19The JFrame Class
- import javax.swing.
- import java.awt.event.
- import java.awt.
- public class JFrameDemo extends JApplet
implements ActionListener -
- JLabel l1 new JLabel("Welcome to my JFrame")
- JButton b1 new JButton("Display Frame")
- JFrame frame
- public void init()
-
- setLayout(new FlowLayout())
- add(b1)
- b1.addActionListener(this)
-
- public void actionPerformed(ActionEvent e)
20JFrame Details
- How do you close a JFrame?
- You can
- Get rid of the JFrame object entirely.
- Just make the JFrame invisible, but ready to be
made visible again an instant later. - Make the JFrame invisible, and put in into cold
storage, ready to be made visible again with a
little thawing. - System.exit( 0 ) the program immediately.
- You can close the JFrame
- when the user clicks the closing X.
- when the user clicks a close menu item.
- programmatically when you decide to close the
JFrame. - programmatically when you decide to shut down the
entire program. - When the user clicks the close X, that does not
make your JFrame object mysteriously disappear or
force it to close, or go invisible. All it does
is send your JFrame a WindowClosing event. Your
JFrame is free to ignore the event, close the
JFrame in any of the four usual ways, or do
something else entirely.The event in no way
closes your JFrame or changes its state. It is
totally up to you what happens. Receiving a
WindowClosingEvent is not an eviction notice it
is just notification the user idly clicked an X.
It does not mean the JFrame is closing or that it
has to close, just that the user would like it to.
21JFrame Details
- Shorthand WindowClosingEvent Handlers
- There are three shortcuts to writing
WindowClosing event handlers. With these
shortcuts, you have no opportunity to add any of
your own application code. - If all you want to do is call dispose() you can
use this, instead of setting up an event handler.
- this.setDefaultCloseOperation (
JFrame.DISPOSE_ON_CLOSE ) - If all you want to do is call setVisible( false )
you can use this, instead of setting up an event
handler. - this.setDefaultCloseOperation (
JFrame.HIDE_ON_CLOSE )?Believe it or not, this
is the default. Beware! - If all you want to do is call System.exit( 0 )
you can use this, instead of setting up an event
handler. - this.setDefaultCloseOperation (
JFrame.EXIT_ON_CLOSE ) - If all you want to write your own custom event
handler, you need to use this, as well as setting
up an event handler. - this.setDefaultCloseOperation( JFrame.DO_NOTHING_O
N_CLOSE )
22JFrame Details
- this.setDefaultCloseOperation ( JFrame.
DO_NOTHING_ON_CLOSE ) - // what happens when user closes the JFrame.
- WindowListener windowListener new
WindowAdapter() -
- // anonymous WindowAdapter class
- public void windowClosing ( WindowEvent w )
-
- // Whatever application code you want to do on
close, e.g. rememberLocation(
MyFrame.this.getX(),MyFrame.this.getY() ) - // Whatever code you want to actually close the
JFrame, e.g. MyFrame.this.setVisible(
false ) MyFrame.this.dispose() - // end windowClosing
- // end anonymous class
- this.addWindowListener( windowListener )
23Other Events (ItemEvents)
- import java.awt.
- import java.awt.event.
- import javax.swing.
- public class ItemEventDemo extends JApplet
implements ItemListener -
- JCheckBox dbRed new JCheckBox("Red")
- JCheckBox dbBlue new JCheckBox("Blue")
- JRadioButton rbWhite new JRadioButton("White")
- JRadioButton rbGreen new JRadioButton("Green")
- ButtonGroup grp new ButtonGroup()
- JComboBox cbb new JComboBox()
- public void init()
-
- setLayout(new FlowLayout())
- add(dbRed)
- dbRed.addItemListener(this)
- add(dbBlue)
- dbBlue.addItemListener(this)
- grp.add(rbWhite)
24Other Events (MouseEvents)
- import java.awt.
- import java.awt.event.
- import javax.swing.
- public class MouseEventDemo extends JApplet
- implements MouseListener
-
- JLabel l1 new JLabel("Click Here")
- JButton b1 new JButton("Cancel")
- JTextField tf new JTextField(10)
- public void init()
-
- setLayout(new FlowLayout())
- add(l1)
- l1.addMouseListener(this)
- add(b1)
- b1.addMouseListener(this)
25MouseEvents
- Mouse events are generated by the following types
of user interaction - A mouse click
- A mouse entering a component's area
- A mouse leaving a component's area
- Any component can generate these events, and a
class must implement the MouseListener interface
to support them. - Methods
- void mouseClicked(MouseEvent e) invoked when
the mouse button has been clicked (pressed and
released) on a component. - void mouseDragged(MouseEvent e) invoked when a
mouse button is pressed on a component and then
dragged. - void mouseEntered(MouseEvent e) - Invoked when
the mouse enters a component. - void mouseExited(MouseEvent e) - Invoked when the
mouse exits a component. - void mouseMoved(MouseEvent e) - Invoked when the
mouse cursor has been moved onto a component but
no buttons have been pushed. - void mousePressed(MouseEvent e) - Invoked when a
mouse button has been pressed on a component.