Graphical User Interfaces CSCI 136: Fundamentals CSCI 136: Fundamentals of Computer of Science Computer II Science Keith II Vertanen Keith Vertanen Copyright 2011
Overview Command line versus GUI apps Java GUI applica;ons JFrame Layout managers Popular widgets Events Ac;on listeners Inner listener classes Drawing things (without StdDraw) JPanel 2
User interfaces Command Line Interface (CLI) Good for experts Automa;ng thing via scripts (e.g. DOS batch files) Easy to use remotely (e.g. over SSH) Low resource consump;on Graphical User Interface (GUI) Good for novices Difficult to automate (e.g. macros in Office) Good for presen;ng mul;ple views, graphical data Remote access difficult (e.g. VNC, Remote Desktop) High resource consump;on 3
Thus far: StdDraw Good for drawing But no GUI widgets: BuVons Combo boxes Text fields Dialog boxes Java GUIs Today: doing it ourselves Use the Java API to create a GUI Crea;ng: common widgets, area to draw on In prac;ce, owen done using a GUI builder 4
JFrame Top- level container Container that holds all the GUI elements Created by main() method 5
JFrame example GUI with a single giant buvon BuVon doesn't do anything (yet) import javax.swing.*; public class SimpleButton public static void main(string [] args) JFrame frame = new JFrame(); JButton button = new JButton("click me!"); frame.getcontentpane().add(button); Create the frame and a buvon. Add the buvon to the content por;on of the frame. frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(300, 300); frame.setvisible(true); Make a reasonable size and actually display. Makes the X box close everything. SimpleButton.java 6
Layout manager Adding mul;ple things Handles arranging mul;ple things in the frame BorderLayout 5 regions: NORTH, SOUTH, EAST, WEST, CENTER Default type for a frame MultiButtons.java MultiButtonsFlow.java FlowLayout LeW to right Creates mul;ple rows if needed Default type for a panel (more on panels in a bit) 7
Adding mul;ple things BoxLayout Ver;cal stack of components BoxLayout.Y_AXIS Horizontal row BoxLayout.X_AXIS Won't rearrange if you resize window MultiButtonsBox.java 8
Handy JFrame methods Some JFrame methods: Method JFrame() JFrame(String title) setlayout(layoutmanager mgr) setdefaultcloseoperation(int op) setsize(int width, int height) setvisible(boolean b) getcontentpane() settitle(string s) Descrip.on Default constructor, a window with no name Constructor, give the window a ;tle Change the layout manager for the frame What to do when the frame is closed Sets to the given width and height Show or hide depending on value of b Returns the content pane where we add things Change the ;tle of the window 9
Handy JBuVon methods Some JBuVon methods: Method JButton(String s) settext(string s) setenabled(boolean b) setpreferredsize(dimension d) Descrip.on Constructor a new buvon with the given label Change the buvon s label Enables or disables the buvon Tell layout manager how big you would like the buvon to be 10
Widget'o'rama JButton JLabel JTextField JCheckBox JTextArea JSlider JRadioButton ButtonGroup JSeparator Widgets.java JComboBox 11
Events Something triggers Usually the user Examples: User clicks buvon Moves the mouse Changing selec;on in a combo box list GUI events 12
Event listener Event listeners and sources Code called when an event occurs Done by implemen;ng a Java interface Which one depends on what you care about Register listener with the object Event source The object that generated the event e.g. the JBuVon object Normally you'll be handling events Not genera;ng them 13
BuVon counter example Single buvon window Every ;me buvon is pushed, increment counter Display counter as label of the buvon 14
import javax.swing.*; import java.awt.event.*; public class ButtonCount implements ActionListener private int count = 0; private JButton button; public void actionperformed(actionevent event) count++; button.settext("count = " + count); public void go() JFrame frame = new JFrame(); button = new JButton("count = " + count); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.getcontentpane().add(button); frame.setsize(300,300); frame.setvisible(true); button.addactionlistener(this); public static void main(string [] args) ButtonCount gui = new ButtonCount(); gui.go(); ButtonCount.java 15
Mul;ple listeners Listening for mul;ple buvons Op;on 1: Single actionperformed()method Use the passed in event object Test which buvon object triggered the method Op;on 2: Mul;ple inner classes Each classes implements actionlistener Each has its own actionperformed() method NOTE: can use private instance vars of parent 16
Op;on 1: Single listener approach public class FarmListener implements ActionListener private JButton buttoncow; private JButton buttondog; private JButton buttoncat; public void actionperformed(actionevent event) if (event.getsource() == buttoncow) StdAudio.play("cow.wav"); else if (event.getsource() == buttondog) StdAudio.play("dog.wav"); else if (event.getsource() == buttoncat) StdAudio.play("cat.wav"); public void go()... buttoncow.addactionlistener(this); buttondog.addactionlistener(this); buttoncat.addactionlistener(this);... FarmListener.java 17
Op;on 2: Inner listener approach public class FarmInner private JButton buttoncow; private JButton buttondog; private JButton buttoncat; class CowListener implements ActionListener public void actionperformed(actionevent event) StdAudio.play("cow.wav"); class DogListener implements ActionListener public void actionperformed(actionevent event) StdAudio.play("dog.wav"); class CatListener implements ActionListener public void actionperformed(actionevent event) StdAudio.play("cat.wav"); public void go()... buttoncow.addactionlistener(new CowListener()); buttondog.addactionlistener(new DogListener()); buttoncat.addactionlistener(new CatListener());... FarmInner.java 18
Building Java GUIs JFrame basis for GUI Summary Choice of layout manager We looked at just three: BorderLayout, FlowLayout, BoxLayout Handles where widgets such as buvons appear Variety of widgets Event handling Widgets trigger events No;fy registered listeners Single listener that handles mul;ple widget Separate inner class for each widget 19