Graphical User Interfaces Comp 152
Procedural programming Execute line of code at a time Allowing for selection and repetition Call one function and then another. Can trace program execution on paper from start to end. User interaction only at specific points.
Object Oriented programming Somewhat more complex. Create objects Objects interact Methods of one object call methods of another object And vice versa Objects passed around as parameters have methods called on them. All but impossible to determine the exact flow of control But still possible to write code that limits user
Event Driven Programming. Different approach Programmer no longer prescribes flow of control of program. Designs interacting set of classes Which are constantly listening for user input Events User input defines what happens at any one time. Set everything up and let it go. Can't predict user input, so can't predict program control at design time.
Window based programming Window based programming is event-driven By nature. Program waits for user event Responds to event and waits for more. Mouse events Keyboard events Specific kinds of each. Only needs to respond to desired events Ignore others. You the programmer will write the event handlers
Swing Window based programming in Java Library of classes provided by SUN Again not MS-windows, but Window-based Built on earlier AWT toolkit Still some AWT used explicitly. Mostly use swing classes though. Package javax.swing Eg import javax.swing.jframe;
Frame Windows Want to make a general purpose window pop up in java The JFrame class JFrame frame = new JFrame(); frame.setsize(300, 400); frame.settitle("an Empty Frame"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); import javax.swing.*;
What it looks like
Useful JFrame Methods void setsize(int width, int height) void setlocation(int x, int y) Swing coordinates. public void setvisible(boolean b) Show hide window Window there but not visible. Container getcontentpane() Needed to put extra windows into this one. Lots more See API docs from resource page of class page
Inheritance to customize Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components as instance fields Initialize them in the constructor of your subclass If initialization code gets complex, simply add some helper methods
JPanel a class for holding other components put panel into JFrame using JFrame add method JFrame frame = new JFrame(); JPanel holder = new JPanel(); frame.add(holder); now put other controls on holder.
JButtons Basic push button class. is-a component decorated with icon or string push to generate action (that you supply) useful constructors JButton() Creates a button with no set text or icon. JButton(Icon icon) Creates a button with an icon. JButton(String text) Creates a button with text.
JButton Methods A few Important methods public void settext(string text) Sets the button's text. public void seticon(icon defaulticon) Sets the button's default icon. public void addactionlistener(actionlistener l) Adds an ActionListener to the button.
JButton Methods A few Important methods public void settext(string text) Sets the button's text. public void seticon(icon defaulticon) Sets the button's default icon. public void addactionlistener(actionlistener l) Adds an ActionListener to the button.
ActionListener ActionListener interface interface for responding to actionevents Something happened You will implement interface one method in the interface action? void actionperformed(actionevent e) Invoked when an action occurs. button press timer events etc
ActionEvent Objects ActionEvent passed as param to your actionperformed method 4 methods String getactioncommand() Returns the command string associated with this action. this is most interesting text on button for buttons int getmodifiers() Returns the modifier keys held down during this action event. long getwhen() Returns the timestamp of when this event occurred. String paramstring() Returns a parameter string identifying this action event.
JLabel JLabel class for putting up label surprise surprise uneditable text
GUI components. Common/basic components from swing library. JButton JCheckbox JComboBox JList
GUI Components Continued JMenu JRadioButton JSlider JTextField JPasswordField JLable
Basic Layout Managers FlowLayout (panel default) BorderLayout(content pane default) GridLayout GridbagLayout
Layouts Up to now, limited control over layout of components When we use a panel, it arranges the components from the left to the right UI components are arranged by placing them inside containers Each container has a layout manager that directs the arrangement of its components Three useful starter layout managers: border layout flow layout grid layout
Default Panel Layout By default, JPanel places components from left to right and starts a new row when needed Panel layout carried out by FlowLayout layout manager Can set other layout managers panel.setlayout(new BorderLayout());
BorderLayout Border Layout handy layout default for JFrames groups container into five areas: center, north, west, south and east When adding a component, specify the position like this: panel.add( BorderLayout.NORTH, component); Expands each component to fill the entire allotted area If that is not desirable, place each component inside a panel
GridLayout gridlayout Arranges components in grid w/ fixed number of rows/ columns Resizes each component so all have same size Expands each component to fill the entire allotted area Add the components, row by row, left to right: JPanel numberpanel = new JPanel(); numberpanel.setlayout(new GridLayout(4, 3)); numberpanel.add(button7); numberpanel.add(button8); numberpanel.add(button9);
Yes!! another opportunity to excel How do you add two buttons to the north area of a frame? How can you stack three buttons on top of each other?
Check Box Two states: checked and unchecked Use one checkbox for a binary choice Use a group of check boxes when one selection does not exclude another Construct by giving the name in the constructor: JCheckBox italiccheckbox = new JCheckBox("Italic"); Don't place into a button group
Combo Boxes or a large set of choices, use a combo box Uses less space than radio buttons "Combo": combination of a list and a text field The text field displays the name of the current selection if combo box is editable, user can type own selection Use seteditable method
Combo Boxes II Add strings with additem method: JComboBox facenamecombo = new JComboBox(); facenamecombo.additem("serif"); facenamecombo.additem("sansserif");... Get user selection with getselecteditem (return type is Object) String selstring = (String) facenamecombo.getselecteditem(); Select an item with setselecteditem
Radio Buttons small set of mutually exclusive choices, use radio buttons or a combo box only one button can be selected at a time When a button is selected, previously selected button in set is automatically turned off suppose, font sizes are mutually exclusive: (see code on next slide)
Example Radio Buttons JRadioButton smallbutton = new JRadioButton("Small"); JRadioButton mediumbutton = new JRadioButton("Medium"); JRadioButton largebutton = new JRadioButton("Large"); // Add radio buttons into a ButtonGroup so that // only one button in group is on at any time ButtonGroup group = new ButtonGroup(); group.add(smallbutton); group.add(mediumbutton); group.add(largebutton);
Event Handling Radio Buttons, Check Boxes, and Combo Boxes generate an ActionEvent whenever the user selects an item
JSlider Used for selection on a scale
JSlider II two simple constructors public JSlider() Creates a horizontal slider with the range 0 to 100 and an initial value of 50 public JSlider(int min, int max, int value) Creates a horizontal slider using the specified min, max, and value.
Slider Events Slider events handled by ChangeListener method in JSlider public void addchangelistener(changelistener l) ChangeListener interface has a single method: void statechanged(changeevent e) What is a ChangeEvent? one really useful method getsource method from superclass EventObject getsource: tells us which component generated this event
JSlider III to find out where the user moved the slider to public int getvalue() Returns the slider's value.
JTextField JTextField Represents a single line of text. In javax.swing package.
JtextField II Constructors JTextField() Constructs a new TextField. JTextField(int columns) Constructs a new empty TextField with the specified number of columns. JTextField(String text) Constructs a new TextField initialized with the specified text. JTextField(String text, int columns) Constructs a new TextField initialized with the specified text and columns.
JTextField Methods of note void addactionlistener(actionlistener l) Adds the specified action listener to receive action events from this textfield. Each character typed in will call actionperformed void settext(string t) Will put the text from t into the textfield String gettext() Returns the text in the text field at the time of the call
End of GUI That's the end of the GUI components for now. enough to do a fairly interesting project you can use these and learn others from tutorials and api docs as needed. Questions? Read chapter 11