GUI Programming using NetBeans. What is a GUI ? GUI – Graphical User Interface The (visual) interface between humans and computers Ranging from command.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming
Advertisements

Graphical User Interfaces (Part IV)
Graphic User Interfaces Layout Managers Event Handling.
Slides prepared by Rose Williams, Binghamton University Chapter 17 Swing I.
© The McGraw-Hill Companies, 2006 Chapter 18 Advanced graphics programming.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
CS102--Object Oriented Programming Lecture 19: – The Swing Package (II) Copyright © 2008 Xiaoyan Li.
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.
More on Creating GUIs in Java using Swing David Meredith Aalborg University.
Java Programming Chapter 10 Graphical User Interfaces.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
Combo Box, Check Boxes, and Radio Buttons. Radio Buttons User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive.
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
Department of Mechanical Engineering, LSUSession VII MATLAB Tutorials Session VIII Graphical User Interface using MATLAB Rajeev Madazhy
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
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.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
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.
Chapter 8: Writing Graphical User Interfaces Visual Basic.NET Programming: From Problem Analysis to Program Design.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Creating Graphical User Interfaces (GUI’s) with MATLAB By Jeffrey A. Webb OSU Gateway Coalition Member.
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 ( 李德成 )
Java Applets: GUI Components, Events, Etc. Ralph Westfall June, 2010.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
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.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 – Graphical User Interfaces Java Foundations: Introduction to Programming.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
GUI Basics. Agenda What GUI How to make in java Creating frames Frequently used GUI components Layout Managers.
Creating User Interfaces Event-Driven Programming.
Ajmer Singh PGT(IP) JAVA IDE Programming - I. Ajmer Singh PGT(IP) GUI (Graphical User Interface) It is an interface that uses a graphic entities along.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Creating a GUI Class An example of class design using inheritance and interfaces.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
Slides prepared by Rose Williams, Binghamton University ICS201 Lecture 15 : Swing III King Fahd University of Petroleum & Minerals College of Computer.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
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.
1 Lecture 8: User Interface Components with Swing.
MATLAB and SimulinkLecture 61 To days Outline Graphical User Interface (GUI) Exercise on this days topics.
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.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
Java Programming Fifth Edition Chapter 13 Introduction to Swing Components.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
GUI Programming using NetBeans
Christopher Budo, Davis Nygren, spencer franks, Luke miller
A First Look at GUI Applications
Advanced User Interfaces
Graphical User Interface (pronounced "gooey")
Ellen Walker Hiram College
Chap 7. Building Java Graphical User Interfaces
Graphical User Interfaces -- Introduction
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

GUI Programming using NetBeans

What is a GUI ? GUI – Graphical User Interface The (visual) interface between humans and computers Ranging from command lines to ”Minority Report” – style GUI Why? Makes interfaces more intuitive – most humans don’t like command lines… SWC

GUI Programming Creating a proper GUI can be as important – and large – a task as creating the logic Quite a lot of topics in GUI programming – Human perception – Task analysis – User analysis – Actual programming SWC

Simple GUI - example SWC Text label Text Field (input) Pushbutton Text Field (output)

Elements in a GUI A GUI is usually composed by controls A control can be a – Text field (enabled, disabled) – Pushbutton (OK, Cancel,…) – List box (multiple items to choose from) – Check box (yes-or-no) – … Many types of GUI controls SWC

Starting simple… For now, we will limit ourselves to just a few GUI controls: – Text label – Text field – List – Check box – Pushbutton – Picture SWC

Text labels Probably the simplest control of all… Usually just used for adding ”static” text – text that does not change – to the GUI Such texts will typically be ”helper text” for other controls No code needed! SWC

Text labels SWC

Text field Two common purposes: – Allow the user to enter data as text – Display text data to the user A text field can be ”enabled” or ”disabled” – Enabled: Data can be entered – Disabled: Data can only be displayed At some point we need to set or extract the text from the text field SWC

Text field SWC

List box Essentially serves the same purpose as a text field – get text input from user However, in some situations we may only allow certain inputs, for instance members of a set of legal input When using a list control, the user can only select an item from the list SWC

List box SWC

Check box In some cases, the set of possible choices is limited to two options Often a case of either/or, or perhaps on/off A Checkbox can only be in two states; checked or unchecked Nice fit for binary choices SWC

Check box SWC

Pushbutton A pushbutton is usually used to start some kind of processing of data The ”input” is simply the user clicking on the pushbutton! Typical use: ”Now my input is ready, do something with it!” We all know the ”OK” button SWC

Pushbutton SWC

Picture Related to text labels – does not really have any functionality, but should be helpful for the user Increases ”recognisability” – the user can see that (s)he is at the right place When programming in NetBeans, a picture is just a special kind of text label… SWC

Picture SWC

GUI construction In general, we have two options when constructing a GUI – Build it ”by hand” using Swing API – Use the NetBeans GUI Builder Using the GUI Builder is usually much easier than hand-coding the GUI Does not give you complete control, however… SWC

GUI construction Swing is a class library for creating GUIs in Java Quite large… API: See package javax.swing in the Java documentation Tutorial: l/uiswing/components/index.htmlhttp://docs.oracle.com/javase/tutoria l/uiswing/components/index.html Most classes begin with ”J”… SWC

GUI construction If you wish to construct a GUI manually using Swing, you usually begin by creating a JFrame A JFrame object is essentially an empty window, into which you can add containers for GUI controls Typically, you add a JPanel to the frame – the JPanel object contains the actual GUI controls SWC

GUI construction public static void main(String[] args) { JFrame theFrame = new JFrame(); theFrame.setBounds(200, 200, 720, 450); theFrame.setVisible(true); JPanel thePanel = new JPanel(); theFrame.add(thePanel); } SWC

GUI construction On the JPanel object, various layout strategies can be used – Flow layout – left to right – Border layout – groups into areas – Grid layout – groups into a grid Border layout is default, and also most commonly used SWC

GUI construction Using border layout, the panel is divided into five areas – Center – North – South – East – West SWC

GUI construction If a control is put into an area, it will expand to fill out the area Good when resizing, but may look weird… If you need a finer level of control, put a panel inside a panel… …or maybe consider a different layout SWC

GUI construction public static void main(String[] args) { JFrame theFrame = new JFrame(); theFrame.setBounds(200, 200, 240, 150); theFrame.setVisible(true); JPanel thePanel = new JPanel(); thePanel.setLayout(new BorderLayout()); thePanel.add(new Button("Center"), BorderLayout.CENTER); theFrame.add(thePanel); } SWC

Exercise time SWC

Text field Two common purposes: – Allow the user to enter data as text – Display text data to the user A text field can be ”enabled” or ”disabled” – Enabled: Data can be entered – Disabled: Data can only be displayed At some point we need to set or extract the text from the text field SWC

Text field JFrame theFrame = new JFrame(); theFrame.setBounds(200, 200, 300, 300); JPanel thePanel = new JPanel(); thePanel.setLayout(new BorderLayout()); JTextField theTextField = new JTextField(); thePanel.add(theTextField, BorderLayout.NORTH); theFrame.add(thePanel); theFrame.setVisible(true); SWC

Text field SWC Text field

Enabling a text field theTextField.setEditable(true); Disabling a text field theTextField.setEditable(false); Setting the text in a text field theTextField.setText("Greeting earthlings!"); Getting the text from a text field String s = theTextField.getText(); SWC

List box / Combo box A list (or combo) box enables the user to choose an option between many alternatives List box: User can only choose between specified alternatives Combo box: User can choose between specified alternatives, or specify choice manually (type it in) SWC

List box / Combo box Object[] choices = {"One", "Two", "Three", "Four"}; JComboBox theBox = new JComboBox(choices); theBox.setEditable(true); thePanel.add(theBox, BorderLayout.NORTH); SWC

List box / Combo box SWC Combo box (editable)

List box / Combo box Enabling a Combo box theBox.setEditable(true); Disabling a Combo box theBox.setEditable(false); Setting the selection in a Combo box theBox.setSelectedItem(”Three"); Getting the selection from a Combo box String s = (String)theBox.getSelectedItem(); SWC

Check boxes In some cases, the set of possible choices is limited to two options Often a case of either/or, or perhaps on/off A Check box can only be in two states; checked or unchecked Nice fit for binary choices SWC

Check boxes JCheckBox theBBox = new JCheckBox("Bold"); JCheckBox theIBox = new JCheckBox("Italic"); JCheckBox theUBox = new JCheckBox("Underline"); thePanel.add(theBBox,BorderLayout.WEST); thePanel.add(theIBox,BorderLayout.NORTH); thePanel.add(theUBox,BorderLayout.EAST); SWC

Check boxes SWC

Check boxes Enabling a Check box theCBox.setEnabled(true); Disabling a Check box theCBox.setEnabled(false); Setting the selection in a Check box theCBox.setSelected(isSelected); Getting the selection from a Check box boolean isSelected = theCBox.isSelected(); SWC

Radio buttons If the number of choices is few, and they are mutually exclusive, use a group of Radio buttons Only one button in a group of Radio buttons can be selected SWC

Radio buttons JRadioButton small = new JRadioButton("Small"); JRadioButton medium = new JRadioButton("Medium"); JRadioButton large = new JRadioButton("Large"); ButtonGroup theGroup = new ButtonGroup(); theGroup.add(small); theGroup.add(medium); theGroup.add(large); JPanel theRadioPanel = new JPanel(); theRadioPanel.setLayout(new FlowLayout()); theRadioPanel.add(small); theRadioPanel.add(medium); theRadioPanel.add(large); thePanel.add(theRadioPanel, BorderLayout.NORTH); SWC

Radio buttons SWC

Radio buttons Enabling a Radio button theRB.setEnabled(true); Disabling a Radio button theRB.setEnabled(false); Setting the selection in a Radio button theRB.setSelected(isSelected); Getting the selection from a Radio button boolean isSelected = theRB.isSelected(); SWC

Radio buttons Note that even though only one Radio button in a group can be selected, we must call isSelected() until we find it… Putting Radio buttons in a group does not make them appear grouped visually SWC

Exercise time SWC

Menus Pull-down menu is a classic choice for choosing between options that have a hierarchical structure – menus form a hierarchy Usually only one main menu in an application; possible choices may vary depending on current circumstances SWC

Menus Swing menu classes: JMenuBar – the actual menu bar, attached to a frame window JMenu – an element in the menu bar, with other menus or menu items in it. JMenuItem – a specific choice, with no sub- choices SWC

Menus ”A menu bar contains menus” ”A menu contains other menus and menu items” ”A menu item just contains itself” SWC

Menus SWC

Menus How to create a menu bar – Create a JMenuBar object JMenuBar theMenuBar = new JMenuBar(); – Add all relevant menus to the menu bar – Attach the menu bar to the main frame of the application frame.setJMenuBar(theMenuBar); SWC

Menus How to add menus to the menu bar – Create relevant menus, like JMenu borrowerMenu = new JMenu(”Borrower”); – Add other menus or menu item to the menu – Add the menu to the menu bar theMenuBar.add(borrowerMenu); SWC

Menus How to add other (sub)menus to a menu – Create relevant menus, like JMenu borrowerManageMenu = new JMenu(”Manage Borrower”); – Add other menus or menu item to the menu – Add the menu to the relevant menu borrowerMenu.add(borrowerManageMenu); SWC

Menus How to add menu items to a menu – Create relevant menu items, like JMenuItem borrowerDeleteMenuItem = new JMenuItem(”Delete Borrower”); – Add the menu item to the relevant menu borrowerManageMenu.add(borrowerDelete MenuItem); SWC

Menus You can do some more ”fun” – and maybe even useful – things with menus: – Add images – Define accelerator keys – Use controls in menus (radio buttons, check boxes,…) Explore the documentation, but only use features that are indeed useful… SWC

Exercise time SWC

The concept of events On the inside (code), GUI code has a very different structure than ”usual” code Usual code is driven by con- ditions and various control structures (if, while,…) GUI code is driven by events SWC

The concept of events Execution of GUI code is much more unpredictable than for usual code We cannot predict – or dictate – what the user does, so we must always handle any possible action the user can do A user action related to the GUI is called an event SWC

The concept of events Almost all actions the user performs will ”trigger” an event for us to handle – Moving the mouse – Clicking on a button – Writing text in a text box – ….and so on There are hundreds of possible events! SWC

The concept of events SWC

The concept of events Fortunately, is it optional to respond to an event We only need to do so, if we want any special action to happen If that is the case, we must write an event handler for that particular event SWC

Relevant events Unless we need more sophisticated behavior, we only need to handle two types of events – Choosing a menu item – Clicking on a push button In both cases, we must create an object which can listen for events from the control in question SWC

Relevant events An event listener class must implement a …Listener interface (there are several) From pushbuttons and menu items, we get ”action events”, so a listener class must implement the ActionListener interface This interface has a single method: actionPerformed SWC

Relevant events public class MyListener implements ActionListener { public void actionPerformed(ActionEvent event) { System.out.println("Button clicked"); } } private ActionListener theListener; theListener = new MyListener();... JButton theButton = new JButton("Click Me!"); theButton.addActionListener(theListener); SWC

Relevant events A very common dialog construction: – Add an ”OK” button – In the event listener for the button Retrieve data from the relevant controls Process the data Close the dialog (maybe) Pressing ”OK” means: ”Now my input is ready, do something with it!” SWC

Exercise time SWC

GUI Development in NetBeans Manual GUI programming is somewhat difficult and tedious Unless you need something special, use the NetBeans GUI Builder! Enables you to ”drag-and-drop” controls into a pane, create event handler methods almost automatically, etc. SWC

GUI Development in NetBeans We will often start out by creating a ”main” frame for the application This frame could be called e.g. AppFrame This frame will only contain a menu, to open other – use-case specific – frames Could e.g. also contain a logo, but should not contain controls as such SWC

GUI Development in NetBeans SWC Choose New | JFrame Form

GUI Development in NetBeans SWC Name, etc as usual…

GUI Development in NetBeans SWC Graphical view of frame Palette of controls Frame properties

GUI Development in NetBeans SWC You can switch between ”Design” view and ”Source” view

GUI Development in NetBeans SWC

GUI Development in NetBeans SWC

GUI Development in NetBeans Looks somewhat confusing at first… Good news is: You can literaly drag controls onto the frame, move them around, adjust their size, alignment, etc. Code that implements your ”design” is automatically generated! SWC

GUI Development in NetBeans Once we add a control, we can – Give the variable representing the control a suitable name – Graphically move, resize, etc. the control – Set various properties for the control – Also, we can add event handlers to a control While all this goes on, Java code is being generated for us

GUI Development in NetBeans SWC Choosing this will generate an (empty) event handler method

GUI Development in NetBeans SWC As said, fill in the code to execute when the button is clicked!

SWC GUI Development in NetBeans Once we add the event handler, it cannot be removed! However, we can always change the code In a sense, the event handler is always there; we just make it visible… In general, we are not allowed to change the automatically generated code

SWC GUI Development in NetBeans Simplistic GUIs often work as follows: – Fill in data in the controls – Press the OK button – Data is ”dealt with” (sent to a handler, etc.) The only code we need to write is the event handler for pressing the OK button In the event handler, data is retrieved from the other controls

SWC GUI Development in NetBeans

SWC GUI Development in NetBeans

RHS – SOC82 GUI Development in NetBeans private void jButtonDoneActionPerformed( java.awt.event.ActionEvent evt) { String name = jTextFieldName.getText(); String job = jListJob.getSelectedValue().toString(); boolean isMale = jCheckBoxMale.isSelected(); String gender; if (isMale) gender = "Male"; else gender = "Female"; String announce = name + ", " + gender + ", " + job; JOptionPane.showMessageDialog(null, announce); }

Exercise time SWC

GUI Development guide No two applications will need the same GUI…..but a typical 1. or 2.semester application will usually follow a certain pattern SWC

GUI Development guide What should the application be able to do…? – Probably some generic tasks (Quit, Help,…) – General data management (Load, Save,…) – Implement use cases! – Uses cases often fall in groups according to their purposes (maybe a Customer-related group, a Boat-related group, etc.) SWC

GUI Development guide The set of tasks can be used to outline a menu structure, like e.g. – File (Load, Save, Quit,…) – Customer (Register, Delete, View All, …) – Boat (Register, Delete, View All) – Rental (Create, Delete, View All,…) SWC

GUI Development guide Create a main frame for the application, and add a menu bar with proper menus Do this using the Net- Beans GUI builder SWC

GUI Development guide Create an event handler for each menu item, create and display the proper frame in the event handler private void jMenuItemRegisterBoatActionPerformed (java.awt.event.ActionEvent evt) { JFrame theRegBoatFrame = new RegisterBoatFrame(); theRegBoatFrame.setVisible(true); } SWC

GUI Development guide Create frames with controls for each of the Use Cases, again using the GUI builder Remember to give the control variables proper names SWC

GUI Development guide In each Use Case – specific frame, retrieve data from controls, do e.g. conversions and validation if needed, and forward data to business logic The above is usually done when the user clicks an ”OK”/”Register”/”Done” button SWC

GUI Development guide Create an event handler for the button, and do data retrieval, conversion, validation and forwarding in the event handler private void jButtonRegisterBoatActionPerformed (java.awt.event.ActionEvent evt) { // Retrieve data from controls, etc.. } SWC

GUI Development guide Remember that even though the code for a frame is auto-generated, you can still e.g. add instance fields to the class and parameters to the constructor SWC

GUI Development guide Typical use: Give a reference to the ”System” class to the frame in its constructor, so it can be used for calling a proper method in the ”System” class with the retrieved data SWC

GUI Development guide // Code in red added manually public class RegisterBoatFrame extends javax.swing.JFrame { private BoatRentalSystem theSystem; public RegisterBoatFrame(BoatRentalSystem theSystem) { this.theSystem = theSystem; initComponents(); }... SWC

GUI Development guide private void jButtonRegisterBoatActionPerformed (java.awt.event.ActionEvent evt) { // Retrieve data from controls, etc.. theSystem.registerBoat(...); } SWC GUI App. System Handler