1 / 48

UFCE3T-15-M Object-oriented Design and Programming Block 3 GUI Programming Jin Sa

UFCE3T-15-M Object-oriented Design and Programming Block 3 GUI Programming Jin Sa. Objectives. GUI components To distinguish simple GUI components. To create user interfaces using frames, panels, and some simple UI components To use JPanel as subcontainers Layout Managers

sera
Download Presentation

UFCE3T-15-M Object-oriented Design and Programming Block 3 GUI Programming Jin Sa

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. UFCE3T-15-M Object-oriented Design and Programming Block 3 GUI ProgrammingJin Sa

  2. Objectives • GUI components • To distinguish simple GUI components. • To create user interfaces using frames, panels, and some simple UI components • To use JPanel as subcontainers • Layout Managers • To understand the role of layout managers • To use the FlowLayout, GridLayout, and BorderLayout managers to layout components in a container

  3. Objectives • Event-driven programming • To explain the concept of event-driven programming • To understand event, event source, and event classes • To register listener objects in the source object; to declare listener classes and write the code to handle events • To understand how an event is handled

  4. Objectives • Graphics • To specify colors using the Color class • To paint graphics using the paintComponent method on a panel • To draw strings, lines, rectangles and ovals using the drawing methods in the Graphics class

  5. Graphical User Interface • A Graphical User Interface (GUI) presents a number of graphical elements to the user to interact with the program. Examples: windows, menus, buttons, text areas. • AWT and Swing: standard sets of classes in Java for building GUIs. • In Java, to write a GUI program, we can derive new classes from those provided in AWT or Swing.

  6. Examples of GUI Objects Radio Button Label Text field Check Box Button Combo Box

  7. Swing vs. AWT • When Java was introduced, the GUI classes were bundled in a library known as the Abstract Windows Toolkit (AWT). • With the release of Java 2, the AWT user-interface components were replaced by a more robust, versatile, and flexible library known as Swing components.

  8. Frames • Frame is a window that is not contained inside another window. Frame is the basis to contain other user interface components in Java GUI applications. • The Frame class can be used to create windows. • For Swing GUI programs, use JFrame class to create widows.

  9. Creating Frames • import javax.swing.JFrame; import javax.swing.JButton; import java.awt.*; public class MyFrame extends JFrame { MyFrame(String title) { setTitle(title); setSize(400,300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { MyFrame frame = new MyFrame("MyFrame"); } } See MyFrame.java in CodeBlock3

  10. JButton Some of the JButton constructors: JButton() JButton(String text)

  11. JTextField A text field is an input area where the user can type in characters. Text fields are useful in that they enable the user to enter in variable data (such as a name or a description). • JTextField(int columns) Creates an empty text field with the specified number of columns. • JTextField(String text) Creates a text field initialized with the specified text. • JTextField(String text, int columns) Creates a text field initialized with the specified text and the column size. • getText() Returns the string from the text field. • setText(String text) Puts the given string in the text field.

  12. JLabel A label is a display area for a short text. • JLabel() • JLabel(String text)

  13. Container • Some GUI components are called containers because they can contain a number of components. • Examples: windows, frames, panels. • Often we need to display a number of components on the screen. By putting these components into a number of containers makes it easier to manage their presentation on the screen.

  14. Adding Components into a Frame // Add a button into the frame getContentPane().add(new JButton("OK")); Title bar Content pane See MyFrame.java in CodeBlock3

  15. Content Pane The content pane is a subclass of Container. The statement in the previous example can be replaced by the following lines: Container container = getContentPane(); container.add(new JButton("OK")); The content pane container is automatically created when a JFrame object is created. A JFrame object uses the content pane to hold components in the frame.

  16. Using Panels as Sub-Containers • Panels act as sub-containers for grouping user interface components. • It is recommended that you place the user interface components in panels and place the panels in a frame. You can also place panels in a panel. • To add a component to JFrame, you actually add it to the content pane of JFrame. To add a component to a panel, you add it directly to the panel using the add method.

  17. Creating a JPanel You can use new JPanel() to create a panel with a default FlowLayout manager or new JPanel(LayoutManager) to create a panel with the specified layout manager. Use the add(Component) method to add a component to the panel. For example, JPanel p = new JPanel(); p.add(new JButton("OK"));

  18. Layout Managers • The GUI components are placed in containers. Each container has a layout manager to tell us how the GUI components within the container can be arranged. • Layout managers are set in containers using the setLayout(LayoutManager) method in a container.

  19. Kinds of Layout Managers • FlowLayout • GridLayout • BorderLayout

  20. The FlowLayout Manager The components are arranged in the container from left to right in the order in which they were added. When one row becomes filled, a new row is started. ShowFlowLayout

  21. FlowLayout Constructors • public FlowLayout(int alignment) Constructs a new FlowLayout with a specified alignment and a default gap of five pixels for both horizontal and vertical. • public FlowLayout() Constructs a new FlowLayout with a defaultcenter alignment and a default gap of five pixelsfor both horizontal and vertical.

  22. Example of the FlowLayout Manager Write a program that adds three labels and text fields into the content pane of a frame with a FlowLayout manager. (Not ideal, see GridLayout later.) ShowFlowLayoutName

  23. The GridLayout Manager The GridLayout manager arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor. The components are placed in the grid from left to right starting with the first row, then the second, and so on.

  24. A GridLayout Constructor • public GridLayout(int rows,int columns) Constructs a new GridLayout with the specified number of rows and columns.

  25. Example of the GridLayout Manager Rewrite the program in the preceding example using a GridLayout manager instead of a FlowLayout manager to display the labels and text fields. ShowGridLayout

  26. The BorderLayout Manager The BorderLayout manager divides the container into five areas: East, South, West, North, and Center. Components are added to a BorderLayout by using the add method. add(Component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER.

  27. Example of the BorderLayout ShowBorderLayout

  28. Example This example uses panels to organize components. The program creates a user interface for a Microwave oven. TestPanels

  29. Event-driven Programming • GUI components allow users to interact with them, which generate events. Actions can be taken to respond to the events. • Event-driven programming is a technique for constructing programs that operate in response to events as they occur. • See the effect of ShowActionEvent.java and TestActionEvent.java

  30. Event-driven Programming • The object in which an event is generated is called the source object; the object in which corresponding actions are performed is called the listening object (or the listener). • Sources: button1 and button2 in ShowActionsEvent • Listening object: this object in ShowActionEvent;

  31. Event-driven Programming • The programmer must explicitly register the listener object with the source object. jbtOk.addActionListener(btListener); button1.addActionListener(this);

  32. Events • An event can be defined as a type of signal to the program that something has happened. • The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, such as a timer.

  33. Selected User Actions Source Event TypeUser Action Object Generated Click a button JButtonActionEvent Press return on a text field JTextFieldActionEvent Window opened, closed, etc. WindowWindowEvent Mouse pressed, released, etc. ComponentMouseEvent Key released, pressed, etc. ComponentKeyEvent

  34. Event Classes • There are different kinds of events, e.g. press buttons, select items, closing windows. Java has pre-defined classes to represent different kinds of events. Each kind of event is defined as a class. • ActionEvent defines events such as pressing a button. • WindowEvent defines events such as closing a window and opening a window. • ItemEvent defines events such as select an item.

  35. Event Information An event object contains whatever properties are pertinent to the event. You can identify the source object of the event using the getSource() instance method

  36. Listener Interfaces • For each event class, Java also has a corresponding action (method) class or interface, e.g. • For ActionEvent, the ActionListener interface specifies a method to deal with the events in ActionEvent. • For WindowEvent, the WindonListener interface specifies a set of methods such as windowClosing and windowOpened. • For ItemEvent, the ItemListener interface specifies a set of methods such as itemStateChanged.

  37. Handling Events • If an object is registered to listen to a particular class of events, that object needs to implement the corresponding interface and the listening object must implement all the methods specified in the interface.

  38. Selected Event Handlers Event Class Listener Interface Listener Methods (Handlers)ActionEvent ActionListener actionPerformed(ActionEvent) ItemEvent ItemListener itemStateChanged(ItemEvent) WindowEvent WindowListener windowClosing(WindowEvent) windowOpened(WindowEvent) windowIconified(WindowEvent) windowDeiconified(WindowEvent) windowClosed(WindowEvent) windowActivated(WindowEvent) windowDeactivated(WindowEvent) MouseEvent MouseListener mousePressed(MouseEvent) mouseReleased(MouseEvent) mouseClicked(MouseEvent) mouseExited(MouseEvent) mouseEntered(MouseEvent)

  39. Example • showActionEvent.java • showActionListener.java

  40. Example with more than one listener A source event may be registered with more than one listener. See ShowActionListner.java

  41. The Color Class You can set colors for GUI components by using the java.awt.Color class. Thirteen standard colors (black, blue, cyan, darkGray, gray, green, lightGray, magenta, orange, pink, red, white, yellow) are defined as constants in java.awt.Color.

  42. Setting Colors You can use the following methods to set the component’s background and foreground colors: setBackground(Color c) setForeground(Color c) Example: see myFrame.java

  43. Drawing in Swing • JPanel can be used to draw graphics (including text) and enable user interaction. • To draw in a panel, you usually create a new class that extends JPanel and override the paintComponent method to tell the panel how to draw things. You can then display strings, draw geometric shapes, and view images on the panel. void paintCompnenet(Graphics g)

  44. Graphics The Graphics object g is created automatically by the JVM for every visible GUI component. This object controls how information is drawn. You can use various drawing methods defined in the Graphics class to draw strings and geometric figures.

  45. Java Coordinate System

  46. paintComponent • The paintComponent method is automatically invoked to paint the graphics context when the component is first displayed or whenever the component needs to be redisplayed. • Invoking super.paintComponent(g) is necessary to ensure that the viewing area is cleared before a new drawing is displayed. • If the user wishes to invoke the paintComponent method, the user uses the repaint() method, which causes the paintComponent to be invoked by the system. • The user should never invoke the paintComponent method directly.

  47. Drawing Geometric Figures and Strings • Drawing Lines, e.g.drawLine(50,50,100,200) • Drawing Rectangles, e.g. drawRect(20,20,100,50) • Drawing Ovals, e.g. drawOval(30,30,50,50); • Drawing Strings, e.g. drawString(Hello”, 50,50);

  48. Example • Concept: extends JFrame, uses container to arrange components, uses the Graphics object, event driven prog. • See MyDrawing.java

More Related