Software Constructions LAB 09 Java Programming with SWING GUI Builder-Part III.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
CMSC 341 Building Java GUIs. 09/26/2007 CMSC 341 GUI 2 Why Java GUI Development? Course is about Data Structures, not GUIs. We are giving you the opportunity.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Understanding SWING Architecture CS 4170 UI Design Hrvoje Benko Oct. 9, 2001.
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Swing CS-328 Dick Steflik John Margulies. Swing vs AWT AWT is Java’s original set of classes for building GUIs Uses peer components of the OS; heavyweight.
1 GUI Elements in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
GUI Layout Managers Arkadiusz Edward Komenda. Outline Components and Containers Layout Managers Flow Layout Grid Layout Border Layout Nested Containers.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
1 TCSS 143, Autumn 2004 Lecture Notes Graphical User Interfaces Koffman/Wolfgang Appendix C, pp
Java Programming Chapter 10 Graphical User Interfaces.
OOP (Java): Layout/ OOP Objectives – –describe the basic layout managers for GUIs Semester 2, GUI Layout.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Java Software Solutions Lewis and Loftus Chapter 10 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Graphical User Interfaces --
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
1 TCSS 360, Spring 2005 Lecture Notes Model-View-Controller paradigm; Observer pattern; Creating Graphical User Interfaces in Java/Swing Relevant Reading:
CSE 219 Computer Science III Graphical User Interface.
Introduction to GUI in Java 1. Graphical User Interface Java is equipped with many powerful,easy to use GUI component such as input and output dialog.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
CS Lecture 01 Frames and Components and events Lynda Thomas
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Laying Out Components Interior Design for GUIs. Nov 042 What is Widget Layout? Positioning widgets in their container (typically a JPanel or a JFrame’s.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Timer class and inner classes. Processing timer events Timer is part of javax.swing helps manage activity over time Use it to set up a timer to generate.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Layout Managers Arranges and lays out the GUI components on a container.
Object Oriented Programming Engr. M. Fahad Khan Lecturer, Software Engineering Department University of Engineering & Technology, Taxila.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
GUI Basics. What is GUI? A graphical user interface (GUI) is a type of user interface item that allows people to interact with programs in more ways than.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
University of Limerick1 Software Architecture Java Layout Managers.
3461 Laying Out Components Interior Design for GUIs.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Graphical User Interfaces. Graphical input and output with JOptionPane.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Computer Science 209 GUIs Model/View/Controller Layouts.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
1 Layout Managers Layout managers –Provided for arranging GUI components –Provide basic layout capabilities –Processes layout details –Programmer can concentrate.
1 CSE 331 Composite Layouts; Decorators slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
Event Handler Methods Text field Object Responder JAVA AWT Environment: Messages are sent between JAVA Objects Screen Event Notification Press Button.
Introduction to GUI in 1 Graphical User Interface 3 Nouf Almunyif.
Introduction to GUI Programming in Java: Frames, Simple Components, and Layouts.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
GUIs & Event-Driven Programming Chapter 11 Review.
A Quick Java Swing Tutorial
CompSci 230 S Programming Techniques
Christopher Budo, Davis Nygren, spencer franks, Luke miller
Graphical User Interface (pronounced "gooey")
A Quick Java Swing Tutorial
Chap 7. Building Java Graphical User Interfaces
Chapter 13: Advanced GUIs and Graphics
Graphical User Interfaces -- Introduction
Timer class and inner classes
Containers and Components
Creating Graphical User Interfaces
A Quick Java Swing Tutorial
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Software Constructions LAB 09 Java Programming with SWING GUI Builder-Part III

2 ButtonGroup A logical group of radio buttons that ensures that only one is selected at a time public ButtonGroup() public void add(JRadioButton button) The ButtonGroup is not a graphical component, just a logical group; the RadioButton s themselves are added to the container, not the ButtonGroup

3 JTabbedPane A container that can hold many "tab" subcontainers, each with components in it public JTabbedPane() public JTabbedPane(int tabAlignment) Constructs a new tabbed pane. Defaults to having the tabs on top; can be set to JTabbedPane.BOTTOM, LEFT, RIGHT, etc. public void addTab(String title, Component comp) public void addTab(String title, Icon icon, Component comp) public void addTab(String title, Icon icon, Component comp, String tooltip) Adds the given component as a tab in this tabbed pane. Can optionally use an icon and/or tool tip.

4 JTabbedPane methods public void insertTab(String title, Icon icon, Component comp, String tooltip, int index) public void remove(Component comp) public void remove(int index) public void removeAll() public void setSelectedComponent(Component c) public void setSelectedIndex(int index)

5 JToolBar A movable container to hold common buttons, commands, etc public JToolBar() public JToolBar(int orientation) public JToolBar(String title) public JToolBar( String title, int orientation ) Constructs a new tool bar, optionally with a title and orientation; can be JToolBar.HORIZONTAL or VERTICAL, defaults to horizontal public void add(Component comp) Adds the given component to this tool bar's horizontal/vertical flowing layout.

6 JToolBar : Usage construct toolbar add items (usually buttons) to toolbar add toolbar to edge of BorderLayout of content pane (usually NORTH ) don't put anything in other edges (N/S/E/W)!

7 A list of selectable pre-defined items public JList() Constructs an empty JList. public JList(ListModel model) public JList(Object[] data) public JList(Vector data) Constructs a JList that displays the given data. public void addListSelectionListener( ListSelectionListener lsl) Adds the given listener to be informed when the selected index / indices change for this list. JList

8 JList : more methods public void clearSelection() public int getSelectedIndex() public int[] getSelectedIndices() public Object getSelectedValue() public Object[] getSelectedValues() public void setSelectedIndex(int index) public void setSelectedIndices(int[] indices) Methods for getting / setting the selected item and index in the list.

9 JList : even more methods public ListModel getModel() public void setListData(Object[] data) public void setListData(Vector data) public void setModel(ListModel model) Causes this list to now display the given collection of data. public int getSelectionMode() public void setSelectionMode(int mode) Get / set selection mode for the list. For example, set to ListSelectionModel.SINGLE_SELECTION to only allow one item in the list to be chosen at once.

10 A window that is a child of the overall JFrame; used for popup windows, option/config boxes, etc. public JDialog(Dialog parent, boolean modal) public JDialog(Frame parent, String title, boolean modal) Constructs a new dialog with the given parent and title. If the modal flag is set, this dialog is a child of the parent and the parent will be locked until the dialog is closed. public void show() Shows this dialog on screen. If the dialog is modal, calling show() will lock the parent frame/dialog. JDialog has most all JFrame methods: getContentPane(), setJMenuBar(JMenuBar), setResizable(boolean), setTitle(String),... JDialog

11 Problem: positioning, resizing How does the programmer specify where each component sits in the window, how big each component should be, and what the component should do if the window is resized/moved/maximized/etc? Absolute positioning (C++, C#, others): Specify exact pixel coordinates for every component Layout managers (Java): Have special objects that decide where to position each component based on some criteria What are benefits or drawbacks to each approach?

12 The idea: Place many components into a special component called a container, then add the container to the JFrame Containers with layout

13 Container container: an object that holds components; it also governs their positions, sizes, and resize behavior public void add(Component comp) public void add(Component comp, Object info) Adds a component to the container, possibly giving extra information about where to place it. public void remove(Component comp) Removes the given component from the container. public void setLayout(LayoutManager mgr) Uses the given layout manager to position the components in the container. public void validate() You should call this if you change the contents of a container that is already on the screen, to make it re-do its layout.

14 JPanel A panel is our container of choice; it is a subclass of Container, so it inherits the methods from the previous slide and defines these additional methods (among others): public JPanel() Constructs a panel with a default flow layout. public JPanel(LayoutManager mgr) Constructs a panel that uses the given layout manager.

15 Preferred size of components Swing component objects each have a certain size they would "like" to be--just large enough to fit their contents (text, icons, etc.) This is called the preferred size of the component Some types of layout managers (e.g. FlowLayout ) choose to size the components inside them to the preferred size; others (e.g. BorderLayout, GridLayout ) disregard the preferred size and use some other scheme Buttons at preferred size: Not preferred size:

16 BorderLayout public BorderLayout() divides container into five regions: NORTH, SOUTH, WEST, EAST, CENTER NORTH and SOUTH regions expand to fill region horizontally, and use preferred size vertically WEST and EAST regions expand to fill region vertically, and use preferred size horizontally CENTER uses all space not occupied by others Container panel = new JPanel(new BorderLayout()); panel.add(new JButton("Button 1 (NORTH)", BorderLayout.NORTH);

17 FlowLayout public FlowLayout() treats container as a left-to-right, top-to-bottom "page" or "paragraph" components are given their preferred size both horizontally and vertically components are positioned in order added if too long, components wrap around to next line Container panel = new JPanel(new FlowLayout()); panel.add(new JButton("Button 1"));

18 GridLayout public GridLayout(int rows, int columns) treats container as a grid of equally-sized rows and columns components are given equal horizontal / vertical size, disregarding preferred size can specify 0 rows or columns to indicate expansion in that direction as needed

19 BoxLayout Box.createHorizontalBox() Box.createVerticalBox() aligns components in container in a single row or column components use preferred sizes and align based on their preferred alignment preferred way to construct a container with box layout: Box.createHorizontalBox(); or Box.createVerticalBox();

20 Other layouts CardLayout layers of "cards" stacked on top of each other; one visible at a time GridBagLayout very complicated; my recommendation: never ever use it custom / null layout allows you to define absolute positions using setX/Y and setWidth/Height

21 How would you create a complex window like this, using the layout managers shown? Problem with layout managers

22 create panels within panels each panel has a different layout, and by combining the layouts, more complex / powerful layout can be achieved example: how many panels? what layout in each? Solution: composite layout

23 Some eye candy... making a Java Swing GUI look like the native operating system: try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch Exception e) {} adding borders to components: whateverComponent.setBorder( BorderFactory.createLineBorder(Color.BLUE, 3));

24 GUI is not done yet... What is missing? Why don't the buttons do anything when we click them? How can we fix this problem? Next topic: events (making the GUI responsive to user interaction) allows our own GUIs to be interactive like JOptionPane

25 Event-driven Programming program's execution is indeterminate on-screen components cause events to occur when they are clicked / interacted with events can be handled, causing the program to respond, driving the execution thru events (an "event-driven" program)

26 Java Event Hierarchy java.lang.Object +--java.util.EventObject +--java.awt.AWTEvent +--java.awt.event.ActionEvent +--java.awt.event.TextEvent +--java.awt.event.ComponentEvent +--java.awt.event.FocusEvent +--java.awt.event.WindowEvent +--java.awt.event.InputEvent +--java.awt.event.KeyEvent +--java.awt.event.MouseEvent import java.awt.event.*;

27 Action events ( ActionEvent ) most common / simple event type in Swing represent an action occurring on a GUI component created by: button clicks check box checking / unchecking menu clicks pressing Enter in a text field etc.

28 Listening for events attach listener to component listener ’ s appropriate method will be called when event occurs (e.g. when the button is clicked) for Action events, use ActionListener

29 Writing an ActionListener // part of Java; you don ’ t write this public interface ActionListener { public void actionPerformed(ActionEvent event); } // Prints a message when the button is clicked. public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent event){ System.out.println("Event occurred!"); }

30 Attaching an ActionListener JButton button = new JButton("button 1"); ActionListener listener = new MyActionListener(); button.addActionListener(listener); now button will print "Event occurred!" when clicked addActionListener method exists in many Swing components

31 ActionEvent objects public Object getSource() Returns object that caused this event to occur. public String getActionCommand() Returns a string that represents this event. (for example, text on button that was clicked) Question: Where to put the listener class?

32 Inner class listener public class Outer { private class Inner implements ActionListener { public void actionPerformed( ActionEvent event) {... } public Outer() { JButton myButton = new JButton(); myButton.addActionListener(new Inner()); }

33 public class Outer { public Outer() { JButton myButton = new JButton(); myButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) {... } ); } Anonymous inner listener

34 ActionListener in JFrame public class Outer extends JFrame implements ActionListener { public Outer() { JButton myButton = new JButton(); myButton.addActionListener(this); } public void actionPerformed(ActionEvent event) {... }

35 GUI builder software JBuilder 2005 includes a mature GUI builder

36 Reminder: model and view model: classes in your system that are related to the internal representation of the state of the system often part of the model is connected to file(s) or database(s) examples (card game): Card, Deck, Player examples (bank system): Account, User, UserList view: classes in your system that display the state of the model to the user generally, this is your GUI (could also be a text UI) should not contain crucial application data Different views can represent the same data in different ways Example: Bar chart vs. pie chart examples: PokerPanel, BankApplet

37 Model-view-controller model-view-controller (MVC): common design paradigm for graphical systems controller: classes that connect model and view defines how user interface reacts to user input (events) receives messages from view (where events come from) sends messages to model (tells what data to display) sometimes part of view (see left) Model Controller View data for rendering events updates Model View Component Controller