Title: Event Handling
1Event Handling
2The Plan
- Sequential (Single Thread) Model
- Event Model
- Making the GUI interactive
- Examples
- Practice
3Sequential (Single Thread) Model
Program Start
Program End
4Event Model
Program Thread
AWT Event Loop
5Event Model
Program Thread
6Event Model
AWT Event Loop
7Making the GUI Interactive
- import java.awt.event.
- implements ActionListener
- write methodpublic void actionPerformed(ActionEve
nt e) - call addActionListener(this) for all JButtons
8Examples
GameShell.java
AdderGUI.java
9Examples
AdderGUI.java
import java.awt. import java.awt.event. import
javax.swing. public class AdderGUI
extends JApplet implements ActionListener
10Examples
AdderGUI.java
public void actionPerformed(ActionEvent
ae) String addend0Textaddend0.getText() d
ouble addend0NumberDouble.parseDouble(addend0Text
) String addend1Textaddend1.getText() doubl
e addend1NumberDouble.parseDouble(addend1Text)
double answeraddend0Numberaddend1Number sum.
setText(""answer)
11Examples
AdderGUI.java
private void makeComponents() framenew
JFrame("Game Shell") addend0new
JTextField(8) addend1new JTextField(8) sum
new JTextField(8) computenew
JButton("") compute.addActionListener(this)
plusnew JLabel("") plus.setHorizontalAlignme
nt(SwingConstants.CENTER)
12Examples
GameShell.java
import java.awt. import java.awt.event. import
javax.swing. public class GameShell
extends JApplet implements ActionListener
13Examples
public void actionPerformed(ActionEvent
ae) Object
causeae.getSource()
if(causepause)
if(pause.getText().equals("Pause"))
pause.setText("Resume")
shell.setText("Paused")
else
pause.setText("Pause")
shell.setText("Game Running")
if(causereset)
pause.setText("Start")
shell.setText("Splash")
GameShell.java
14Examples
GameShell.java
pausenew JButton("Start")
pause.addActionListener(this) resetnew
JButton("Start New Game")
reset.addActionListener(this)
15Practice
- Make a 2x2 tic-tac-toe board out of initially
blank Jbuttons. - Make the JButton text change to X when the user
clicks on it. - Make the JButton text change to X and O
alternatively as the user clicks on the
buttons.Hint use a boolean instance variable. - Make the fonts larger, and maybe add images.
- Look at Splash.java and SplashLoop.java in
Splash.jar