代写代考 COMPSCI4039: Programming

COMPSCI4039: Programming
Java Swing continued 1

Recall this slide … laying out GUI components …

Copyright By PowCoder代写 加微信 powcoder

JFrame, JPanel, different Layouts, add GUI components, …
JPanel mainPanel = new JPanel(new GridLayout(2, 1)); JPanel myPanel1 = new JPanel(new FlowLayout());
myPanel1.add(button1);
myPanel1.add(button2);
mainPanel.add(myPanel1);
JPanel myPanel2 = new JPanel(new FlowLayout()); myPanel2.add(label1);
myPanel2.add(textField1); mainPanel.add(myPanel2);
this.add(mainPanel);
(See Demo)
Outer JFrame has Border Layout mainPanel is added to Center area

But pressing our buttons didn’t do anything ! We need to deal with this …
● Events within a GUI
○ Button presses using the mouse
○ Pressing inside a JTextField
● Event handling
○ Each user action will generate an ActionEvent object
○ The GUI component (for instance the Button) will get notified by Swing of any user events that
happen on this object (i.e. it gets pressed).
○ We need to tell the program what to do when such events happen.
● Popup dialogue boxes ○ JOptionPanes

Event-based programming
● By default, if we press a button, nothing will happen
○ the user interface delivers an event to the button,
○ but no one is listening …
● We must add a listener object to the button …
● Each button press generates an ActionEvent object
● We must define our own class that implements the Java ActionListener
interface – implementing the actionPerformed(…) method.
● We then register our action listener
object with the button so that it knows what to do when the button is pressed.

Examples: ButtonFrame1 and ButtonFrame2
ButtonFrame1 (above): single click updates text, subsequent clicks do nothing
See the Demo …

Step 1: ButtonFrame1 as an ActionListener
● The easiest way to get a listener object is to use our JFrame object to listen for ActionEvents
● ButtonFrame1 implements ActionListener as well as extending JFrame ○ publicclassButtonFrame1extendsJFrameimplementsActionListener
● We can then get it to listen to the button
○ b.addActionListener(this)
● Remember that this is the ButtonFrame1 object
○ The method that handles the event is in the same class

Step 2: Implement actionPerformed(…) method …
● Finally, we have to define what is done when an ActionEvent is delivered to a listener
● This is done by writing a method called actionPerformed
● Each object that is listening to a button must have an actionPerformed
● In our examples, the ButtonFrame1/ButtonFrame2 object is listening to the
button and so must define the method
public void actionPerformed(ActionEvent e) {… }
● We do not use inner classes for actionPerformed (unlike some examples online etc.)

Some code omitted from the next few examples
// import statements
import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton;
import javax.swing.JFrame;
// JFrame title, close and size
this.setTitle(“Button with listener”); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(300, 100);
// Main method — creates the ButtonFrame1 object
public static void main(String[] args) { ButtonFrame1 gui = new ButtonFrame1(); gui.setVisible(true);
Amend for different examples

ButtonFrame1
// import statements
public class ButtonFrame1 extends JFrame implements ActionListener { private JButton b = new JButton(“click me”);
public ButtonFrame1() {
// JFrame title, close and size
b.addActionListener(this);
this.add(b);
public void actionPerformed(ActionEvent e) {
b.setText(“I was clicked.”);
// Main method — creates the ButtonFrame1 object

ButtonFrame2
// import statements
public class ButtonFrame2 extends JFrame implements ActionListener { int num = 0;
private JButton b = new JButton(“click me”);
public ButtonFrame1() {
// JFrame title, close and size
b.addActionListener(this);
this.add(b);
public void actionPerformed(ActionEvent e) {
b.setText(String.format(“I was clicked %d times”,num)); // Main method — creates the ButtonFrame2 object

Another example – multiple buttons (Beeper1)
Initial screen: two buttons
Clicking right button decrements counter on right hand button and beeps. If counter <1 program exits. Clicking left button increments counter (initially 11) on right hand button Beeper1 - outline import java.awt.BorderLayout; import java.awt.Toolkit; // this is where the beeper comes from! import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JFrame; public class Beeper1 extends JFrame implements ActionListener { JButton button1, button2; int clickCount = 10; // add constructor // add actionPerformed method // add main method Beeper1: constructor public Beeper1() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(400, 200); button1 = new JButton("Please stay"); this.add(button1, BorderLayout.WEST); button1.addActionListener(this); button2 = new JButton("Please go"); this.add(button2, BorderLayout.EAST); button2.addActionListener(this); Standard things - the clever stuff happens on the next slide ActionPerformed - which button? ● In this example, the Beeper1 object is listening to both buttons ● So the actionPerformed method is called no matter which button is pressed ● How can we tell the difference? ● We can work it out from the ActionEvent object which is used to communicate information about the event ○ It knows which button was pressed ! ● The method getSource() returns the button object that was pressed ● We just use an if statement to test which button Beeper1: actionPerformed method public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) { // user has pressed the left button, increment counter clickCount++; button2.setText(Integer.toString(clickCount)); } else if (e.getSource() == button2) { Which button is pressed? Button 1 is pressed but // user has pressed the right button so count down // and beep outcome affects clickCount--; Toolkit.getDefaultToolkit().beep(); } else { } if (clickCount > 0) { button2.setText(Integer.toString(clickCount));
System.exit(0);
End program

Responding to the correct button …
public void actionPerformed(ActionEvent e) { if (e.getSource() == button1) {
// user has pressed the left button …
} else if (e.getSource() == button2) {
// user has pressed the right button …
● Good practice for actionPerformed to use helper methods to process events
● See Beeper2 in code folder for an example of this Lets see the demo !

Changing the “logic” of a GUI
● In principle a GUI controlled program is an automatic endless loop
while (the GUI is open)
listen for and process a registered event
● This can be changed by disabling buttons either after an event has been processed, or after a certain count of clicks
// to disable myButton
myButton.setEnabled(false);
// to re-enable
myButton.setEnabled(true);

Using a button to end a program
● The method that ends a program is System.exit(int n);
○ n=0 means a normal exit
○ n=1 tells the O/S something went wrong
● The event handler for a button click can call this method
if (e.getSource()==quitButton)
System.exit(0);
● We saw something like this in Beeper1: if (clickCount > 0) {
button2.setText(Integer.toString(clickCount)); } else {
System.exit(0);

Summary: Enabling a GUI class to handle ActionEvents
● Import java.awt.event.*
● Add implements ActionListener to the class header
● Use the addActionListener method for each button that is to fire an event: ○ myButton.addActionListener(this)
● Write an actionPerformed method containing the event handling code, using e.getSource() to determine which event occurred

Questions ?

TextField ActionListener example
● Clicking the button will increase the number (first click makes it 1)
● typing “red”, “green” or “blue” in textfield will change background colour accordingly
See MultiListeners1.java and MultilistenersPanel.java in code folder
○ Any other string changes background color to white.

JTextField events
● A JTextField will generate an event when the user types ENTER
● It is an ActionEvent
● So we need to add an ActionListener
○ just like a button
● The event is delivered to the actionPerformed method
● We can find out which text field sent the event from getSource()
○ in the same way as buttons
● We can then call the getText method of JTextField ○ to find out the text that the user entered

MultiListeners1
Two classes:
● MultiListenerPanel.java
○ Defines a JPanel with a button (button1) and TextField (textField1) includes:
○ Constructor with parameter parent (which will be the JFrame including an object of this class)
○ button1 and textField1 have ActionListeners with parameter value parent
● MultiListeners1.java
○ Creates the GUI,
○ has instance variable of type MultiListenerPanel, called panel
○ actionPerformed method uses panel’s getter methods to access button1 and textField1

MultiListenerPanel
public class MultiListenerPanel extends JPanel { JButton button1;
JTextField textField1;
public MultiListenerPanel(ActionListener parent) { this.setBackground(Color.white);
button1 = new JButton(“Click to increase number”); button1.addActionListener(parent);
add(button1);
textField1 = new JTextField(10); textField1.addActionListener(parent); textField1.setText(“white”); add(textField1);
// add getters

MultiListeners1
public class MultiListeners1 extends JFrame implements ActionListener { MultiListenerPanel panel = new MultiListenerPanel(this);
int clickCount = 0;
public MultiListeners1() { //set size etc.
add(panel);
public void actionPerformed(ActionEvent e) {
// main method}
// see next slide

MultiListeners1 contd.
public void actionPerformed(ActionEvent e) {
if (e.getSource() == panel.getButton1()) {
// user has pressed the left button, increment counter
clickCount++; panel.getButton1().setText(Integer.toString(clickCount));
} else if (e.getSource() == panel.getTextField1()) {
if (panel.getTextField1().getText().equals(“red”))
panel.setBackground(Color.red);
if (panel.getTextField1().getText().equals(“blue”)) panel.setBackground(Color.blue);
See next slide

Entering numbers
● A JTextField only delivers strings from the user to the program
● If we want to enter a number, we must
○ Get it as a string using getText
○ Convert the string to a number
● The Integer and Double (wrapper) classes will do this. ○ inti=Integer.parseInt(myString);
○ doubled=Double.parseDouble(myString);
● We saw something similar for the JButton in previous example: ○ panel.getButton1().setText(Integer.toString(clickCount));

Putting numbers into a text field
● If we wanted to put the number num into our text field
○ setText(“”+ num);
Disabling a text field
● Use the setEditable method
○ e.g., myTextField.setEditable(false)
● To re-enable:
○ E.g. myTextField.setEditable(true)

White space
● Leading and trailing white space can cause problems
○ Better to remove it with the trim method of String
○ myString.trim() returns a string with leading and trailing white space removed from
● A NumberFormatError will be thrown if the String is not a number
○ Either by Integer.parseInt() or Double.parseDouble()
○ If we don’t catch it our program may crash with an unhandled exception

Questions ?

The JOptionPane class
● Used to create ‘temporary’ windows
(essentially a dialogue window)
○ associated with, but not embedded in a JFrame
○ usually require the user’s immediate attention
○ used for displaying messages that have no obvious place in
the GUI itself
■ Error messages, information messages, diagnostics,
prompting for yes/no decision ○ disappear once dealt with by the user
● Very seldom used as an object class
○ i.e. practically never need to instantiate a JOptionPane
○ the class contains static methods that throw up appropriate
windows with appropriate messages

JOptionPane static methods
Method name
Description
showMessageDialog
Tell user about something that has happened
showConfirmDialog
Ask a confirming question like yes/no/cancel
showInputDialog
Prompt for some input
showOptionDialog
The grand unification of the above three

Showing a message dialogue pane
● Tell the user about something that has happened
● JOptionPane.showMessageDialog(Component, “message”, “title”, JOptionPane.MESSAGE_TYPE);
● 4 parameters
○ the window to which the message is attached ■ Usually this or null
○ the message to be displayed
○ the title to go in the title bar
○ the type of message (MESSAGE_TYPE)
■ determines the icon to be displayed in the window
○ ERROR_MESSAGE INFORMATION_MESSAGE
WARNING_MESSAGE QUESTION_MESSAGE
As usual, look and feel depends on OS used (Windows/Mac)

Showing a confirm dialogue pane
● Lets the user choose yes/no/cancel or close the window
● int result = JOptionPane.showConfirmDialog(Component, “message”);
● Possible values of result: ○ JOptionPane.YES_OPTION
■ User clicks on yes
○ JOptionPane.NO_OPTION
■ User clicks on no
○ JOptionPane.CANCEL_OPTION
■ User clicks on cancel
○ JOptionPane.CLOSED_OPTION
■ User closes dialog box

Showing an input dialogue pane
● Lets the user input a string
● String result = JOptionPane.showInputDialog(Component, “message”);
● result is null if user cancels or closes the dialog box
● Add System.exit(0)to the main method of any program that uses JOptionPane

Demo program
● See JOptionPaneTester.java in the folder containing programs for this week’s lectures

● We have covered a lot of material in this lecture.
● Event handling within Swing
○ Different GUI components generate ActionEvent objects.
○ ActionListeners need to be registered with the GUI components to react to these events.
○ The ActionListener interface requires an actionPerformed method to be implemented to tell the system what what should be done when particular events occur. Different events can be routed to different listeners so it may need to handle more than one event type.
● We have also looked at how to display different types of dialogues to the user when you want to tell them about messages or ask questions.

程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com