Graphical User Interfaces (GUIs) CS 144 John Goettsche Computer Science and Computer Engineering 1
GUI Programming • Event-driven programming • GUI event loop • Event listeners • Components can generate events 2 CSCE
Event Driven Programming Event loop Event Listener Event 3 CSCE
Example: Push Counter • Update counter when button is pushed. • Components: JButton, JLabel • Event: button push • Listener: actionListener Initial GUI: After 6 clicks: 4 CSCE
Push Counter Components Frame ( JFrame object) Panel ( JPanel object) Label ( JLabel object) Button ( JButton object) 5 CSCE
Building the GUI: Setting up Components panel.add( button ); panel.add( label ); frame.add( panel ); The panel 6 CSCE
Building the GUI: Event Listeners Code to be executed when event occurs public void actionPerformed(ActionEvent e) { ... } This method is contained in a class. We use objects of this class to serve as "listener" objects. 7 CSCE
Building the GUI: Connecting Events to Event Listeners button.addActionListener( listenerObject ); Object containing code for listener. (The actionPerformed method from the previous slide.) 8 CSCE
Inner Classes Available to both MyGUI and MyInnerClass public class MyGUI { private int x; public MyGUI() { ... } Class within a class. private class MyInnerClass { } } Inner class has access to outer class's fields. 9 CSCE
A GUI Framework Extend JFrame class. public class PushCounter extends JFrame { // The "Push Me" button private JButton pushButton; Connect button click event to listener object. public PushCounter() { ... pushButton = new JButton( "Push Me!"); pushButton.addActionListener(new PushCounterButtonListener()); ... } private class PushCounterButtonListener implements ActionListener { Inner class implements the public void actionPerformed(ActionEvent e) ActionListener interface. { .... } } Code to execute when } event occurs. 10 CSCE
Inheritance • Gain all methods and fields from inherited class. • PushCounter is-a JFrame public class PushCounter extends JFrame { ... } All methods/fields that are in class JFrame are now available in class PushCounter . 11 CSCE
Implementation of Interfaces • Require the creation of certain methods (depending on the interface) • ActionListener requires that the actionPerformed method exist. Interface private class PushCounterButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { .... } } Must create the actionPerformed method or this will not compile. 12 CSCE
Starting Things Up • To start a GUI-based program we need only instantiate a JFrame object. • Remember, PushCounter is-a JFrame . • JVM will automatically enter the event loop. • main method may exist anywhere you like. In GUI programs, the main method is often quite short. public static void main( String[] args ) { PushCounter frame = new PushCounter(); } Instantiate PushCounter , which extends JFrame . 13 CSCE
Code: PushCounter.java 14 CSCE
Example: Math Question 15 CSCE
Recommend
More recommend