Presentation is loading. Please wait.

Presentation is loading. Please wait.

Graphical User Interface Programming

Similar presentations


Presentation on theme: "Graphical User Interface Programming"— Presentation transcript:

1 Graphical User Interface Programming

2 GUI Graphical User Interface Java GUI programming
event driven programming Java GUI programming AWT (Abstract Window Toolkit) Swing

3 Event driven programming
Uses a signal-and-response approach Events and event handlers Asynchronous Event = object that act as a signal to another object Listener = event receiver One event might have zero or more listeners. Listeners can receive events from different objects.

4 Event driven programming
One event might have zero or more listeners. Listerner A Button X Listerner B Listerner C

5 Event driven programming
Listeners can receive events from different objects. Button X Listerner A Button Y Button Z Listerner B

6 Typical events User moves the mouse. User clicks the mouse button.
User clicks the mouse button in a button in a window. User presses a key on the keyboard. Timer event occurs.

7 Typical programming and event driven programming
Up to now your programs consisted of lists of statements executed in order. In event-drive programming, you create objects that can fire events, and you create listener objects that react to the events. You don’t know the order ahead of time. Typically, your code never directly calls the listener methods.

8 Exception Objects An exception object is an event
The throwing of an exception is an example of firing an event The listener for an exception object is the catch block that catches the event

9 Event Handlers A listener object has methods that specify what will happen when events of various kinds are received by it These methods are called event handlers

10 Event Firing and an Event Listener

11 Windows via Swing’s JFrame

12 Creating a window in Swing
import javax.swing.JFrame; JFrame f = new JFrame( “My Simple Frame” ); f.setSize( 300, 200 ); //w, h f.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); f.setVisible( true );

13 Adding a button to a window (JFrame)
import javax.swing.JButton; //create the button JButton b1 = new JButton( “Click to end program” ); //associate the listener with this button (next slide) MyButtonListener listener = new MyButtonListener(); b1.addActionListener( listener ); f.add( b1 ); //add the button to our frame

14 Our button listener import java.awt.event.ActionListener;
import java.awt.event.ActionEvent; public class MyButtonListener implements ActionListener { public void actionPerformed ( ActionEvent e ) { System.exit( 0 ); }

15 (Typical) Steps Create the frame. Create the button.
Create the action listener for the button. Add the action listener to the button (register the action listener with the button). Add the button to the frame. Show the frame. Demo

16 Pixels and the Relationship between Resolution and Size
A pixel is the smallest unit of space on a screen Both the size and position of Swing objects are measured in pixels The more pixels on a screen, the greater the screen resolution A high-resolution screen of fixed size has many pixels Therefore, each one is very small A low-resolution screen of fixed size has fewer pixels Therefore, each one is much larger Therefore, a two-pixel figure on a low-resolution screen will look larger than a two-pixel figure on a high-resolution screen

17 Useful JFrame methods public JFrame ( ) public JFrame ( String title )
public void setDefaultCloseOperation ( int operation ) JFrame.DO_NOTHING_ON_CLOSE JFrame.HIDE_ON_CLOSE JFrame.DISPOSE_ON_CLOSE JFrame.EXIT_ON_CLOSE Note: The close-window-button is part of the JFrame (not a JButton) public void setSize ( int width, int height )

18 More useful JFrame methods
public void setTitle ( String title ) public void add ( Component componentAdded ) public void setLayout ( LayoutManager manager ) public void setJMenuBar ( JMenuBar menubar ) public void dispose ( ) public void setVisible ( boolean makeVisible )

19 Buttons via Swing’s JButton

20 Buttons (JButton) Different kinds of components require different kinds of listener classes to handle the events they fire. A button fires events known as action events, which are handled by listeners know as action listeners.

21 Back to creating a window in Swing
import javax.swing.JFrame; JFrame f = new JFrame( “My Simple Frame” ); f.setSize( 300, 200 ); //w, h f.setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); f.setVisible( true ); This is not a very OO approach!

22 A more OO approach to creating a window in Swing
import javax.swing.JFrame; public MyFrame extends JFrame { public static final int sWidth = 300; public static final int sHeight = 200; MyFrame ( ) { super( “My More OO Simple Frame” ); setSize( sWidth, sHeight ); setDefaultCloseOperation( JFrame.DO_NOTHING_ON_CLOSE ); setVisible( true ); } Demo

23 JLabel – a line of text Simply a line of text appearing in a window.
import javax.swing.JLabel; JLabel label = new JLabel( “hello there.” ); add( label );

24 Programming in Color import java.awt.Color; … Color.BLACK Also
Color.BLUE, Color.CYAN, Color.DARK_GRAY, … Or you can specify/create your own colors by specifying the argb or rgb values in the Color ctor. Use getContentPane().setBackground( Color.BLUE ); to change the background color of your JFrame.

25 Programming in color Colors are represented by their RGB value. R=red
G=green B=blue When R is the largest value, the color has more red than the other components. What happens when r=g=b? Sometimes ARGB is used where A=alpha (opacity)

26 Layout Managers

27 Controlling the placement of components in a container (our frame)
So far, we simply add components to a container and accept whatever default layout is presented. Layout manager – describes how the components are arranged. Java provides many layout managers. Border (in book) Box (not in book) Card (not in book) Flow (in book) Grid (in book) Grid bag (not in book) Group (not in book) Spring (not in book)

28 BorderLayout Places the components in five areas:
North South East West Center You specify the area in the add method. add( new JLabel(“me”), BorderLayout.NORTH );

29 Using the BorderLayout
import java.awt.BorderLayout; import javax.swing.JFrame; import javax.swing.JLabel; public class MyFrame extends JFrame { public MyFrame ( ) { super( “My frame w/ border layout.” ); setSize( 300, 200 ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new BorderLayout() ); add( new JLabel( “first” ), BorderLayout.NORTH ); add( new JLabel( “second” ), BorderLayout.SOUTH ); setVisible( true ); }

30 FlowLayout Simplest. Arranges components one after another from left to right and top to bottom in the order in which one adds them.

31 Using the FlowLayout import java.awt.FlowLayout;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class MyFrame extends JFrame { public MyFrame ( ) { super( “My frame w/ flow layout.” ); setSize( 300, 200 ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new FlowLayout() ); add( new JLabel( “first” ) ); add( new JButton( “second” ) ); setVisible( true ); }

32 GridLayout Arranges components on a 2D grid of given size (i.e., rows and cols specified via the GridLayout ctor). Each entry in the grid will be stretched to the same size.

33 GridLayout Placement rules are more complicated.
Say we have a 2 x 3 (2 rows x 3 cols): new GridLayout( 2, 3 ) If we subsequently add six things, they will appear in a 2x3 grid of equally sized elements. What happens if we add more or less?

34 GridLayout X Placement rules are more complicated.
Say we have a 2 x 3 (2 rows x 3 cols). Adding 7 or 8 items causes a col to be added. Adding fewer than 6 items causes a col(s) to be deleted. X

35 GridLayout Placement rules are more complicated.
Say we have a 2 x 3 (2 rows x 3 cols). To only honor the number of rows, specify a 0 for the cols. To honor only the number of cols, specify a 0 for the rows.

36 Using the GridLayout import java.awt.GridLayout;
import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; public class MyFrame extends JFrame { public MyFrame ( ) { super( “My frame w/ flow layout.” ); setSize( 300, 200 ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setLayout( new GridLayout(0,1) ); //always a single col add( new JLabel( “first” ) ); add( new JButton( “second” ) ); setVisible( true ); }

37 Summary of Layout Managers
FlowLayout Displays components from left to right in the order in which they are added to the container. BorderLayout Displays the components in five areas: N, S, E, W, and Center. You specify the area in the add method. GridLayout Lays out components in a grid with each component stretched to fill its box in the grid.

38 Additional Layout Managers
Box (not in book) Card (not in book) Tabbed pane (not in book; not strictly a layout manager) Grid bag (not in book) Group (not in book) Spring (not in book)

39 BoxLayout “either stacks its components on top of each other or places them in a row - your choice” from

40 CardLayout Typically used to switch between different panels.
Poor man’s version of tabbed pane. choice here causes change here

41 JTabbedPane Not strictly a layout manager.
Typically preferred over CardLayout.

42 GridBagLayout “… if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager” from

43 GroupLayout “… if you want to code by hand and do not want to use GroupLayout, then GridBagLayout is recommended as the next most flexible and powerful layout manager” from Intended to be used by GUI builder.

44 SpringLayout Intended to be used by GUI builder.

45 a general purpose window-like container
JPanel a general purpose window-like container

46 Panels A GUI is often organized in a hierarchical fashion, with containers called panels inside other containers A panel is an object of the JPanel class that serves as a simple container It is used to group smaller objects into a larger component (the panel) One of the main functions of a JPanel object is to subdivide a JFrame or other container

47 Panels The content pane of a JFrame and each panel in a JFrame can use different layout managers Additional panels can be added to each panel, and each panel can have its own layout manager This enables almost any kind of overall layout to be used in a GUI

48

49

50

51

52 JPanel Example contentPane (JFrame w/ BorderLayout)
biggerPanel (w/ GridLayout of 1 row & 3 cols) added at center redPanel whitePanel bluePanel buttonPanel (w/ FlowLayout) added at south redButton whiteButton blueButton

53

54

55 The Container class Can have components added to it
JFrame & JPanel are descendents of Container Container class = any descendent of Container Component = any descendent of JComponent You may add any component to any container JComponent is derived from Container so you may add a JComponent to a JComponent

56 MVC = Model+View+Controller
The MVC Pattern MVC = Model+View+Controller

57 Model-View-Controller
The domain-specific representation of the information on which the application operates. Domain logic adds meaning to raw data (e.g., calculating whether today is the user's birthday, or the totals, taxes, and shipping charges for shopping cart items). The Model part of the pattern performs the heart of the application.

58 Model-View-Controller
Renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. The View part is the output part; it displays a picture of the Model’s state.

59 Model-View-Controller
Processes and responds to events, typically user actions, and may invoke changes on the model. The Controller is the input part; it relays commands from the user to the model.

60 Basic MVC Model data1 data2 . manipulate notify View … update()
Controller

61 Model-View-Controller (from wikipedia.org)
Though MVC comes in different flavors, control flow generally works as follows: The user interacts with the user interface in some way (e.g., presses a button). A controller handles the input event from the user interface, often via a registered handler or callback. The controller accesses the model, possibly updating it in a way appropriate to the user's action (e.g., controller updates user's shopping cart). A view uses the model (indirectly) to generate an appropriate user interface (e.g., the view produces a screen listing the shopping cart contents). The view gets its own data from the model. The model has no direct knowledge of the view. The user interface waits for further user interactions, which begins the cycle anew. By decoupling models and views, MVC helps to reduce the complexity in architectural design, and to increase flexibility and reuse.

62 Model-View-Controller (from wikipedia.org)
A simple diagram depicting the relationship between the Model, View, and Controller. Note: the solid lines indicate a direct association, and the dashed lines indicate an indirect association (e.g., observer pattern).

63 Observer pattern “The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. It is mainly used to implement distributed event handling systems.” from

64 Controller (input events) MyController
Model (data) ConnectFour | V MyConnectFour Main View (output) MyView Controller (input events) MyController A diagram depicting the relationship between the Model, View, and Controller for the ConnectFour game. Note: the solid lines indicate a direct association, and the dashed lines indicate an indirect association (e.g., observer pattern).

65 Note Some designers combine/simply the M-V-C to D-V where…
D is the document, data, or model, V is the View, and the controller is typically part of the view.

66 Menus and buttons

67 Menu bars, menus, and menu items
JMenuBar, JMenu, and JMenuItem import: javax.swing.JMenuBar ex. the menu bar in an app javax.swing.JMenu ex. File ex. Edit ex. Help javax.swing.JMenuItem ex. Open in the File menu ex. Cut in the Edit menu implement ActionListener for events

68 Example menu bar menu menu item

69 Example: creating a menu bar
public class MenuDemo extends JFrame implements ActionListener { public MenuDemo ( ) { JMenu colorMenu = new JMenu( “Add colors” ); JMenuItem greenChoice = new JMenuItem( “Green” ); greenChoice.addActionListener( this ); colorMenu.add( greenChoice ); JMenuBar bar = new JMenuBar(); bar.add( colorMenu ); setJMenuBar( bar ); }

70 Handling menu events When we create a button or menu item, we specify a string. By default, that string becomes the action command for that button. The action command is provided to the actionPerformed method. The action command can be changed via setActionCommand (there is also a getActionCommand method as well).

71 Example: handle menu events
public class MenuDemo extends JFrame implements ActionListener { public void actionPerformed ( ActionEvent e ) { String action = e.getActionCommand(); if (action.equals( “Green” )) greenPanel.setBackground( Color.GREEN ); else if (action.equals( “White” ) whitePanel.setBackground( Color.WHITE ); else System.out.println( “Unexpected action” ); }

72

73 A GUI with a Menu

74

75

76

77

78 Advanced topic: sub/nested menus
submenu

79 submenus Similarly to adding menu items to a menu, we may also add menus to menus. (Note that JMenuItem is a superclass of JMenu below.)

80 Text fields and text areas

81 Text field (JTextField)
A field that allows the user to enter a single line of text. Ex. JTextField name = new JTextField( 30 ); String inputString = name.getText(); name.setText( “fred” ); JTextField f2 = new JTextField( “ethel”, 30 ); //default value 30 is the minimum number of visible characters (more may be entered)

82 Text area (JTextArea) Same as text field except it allows multiple lines. Ex. JTextArea theText = new JTextArea( 5, 20 ); JTextArea t2 = new JTextArea( “hello\nthere”, 5, 20 ); 5 is the minimum number of visible lines. 20 is the minimum number of visible characters.

83 Some useful JTextComponent methods
public String getText() public boolean isEditable() public void setBackground ( Color theColor ) public void setEditable ( boolean argument ) public void setText ( String text )

84

85

86

87


Download ppt "Graphical User Interface Programming"

Similar presentations


Ads by Google