Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University 2013. *Ref:

Slides:



Advertisements
Similar presentations
1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and a Simple Demo Program l Layout Managers l Buttons and Action Listeners l Container.
Advertisements

Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
1 lecture 12Lecture 13 Event Handling (cont.) Overview  Handling Window Events.  Event Adapters Revisited.  Introduction to Components and Containers.
Java Swing 4 th April 2008 CS 180 Department of Computer Science, Purdue University.
1 Class 8. 2 Chapter Objectives Use Swing components to build the GUI for a Swing program Implement an ActionListener to handle events Add interface components.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
1 TCSS 143, Autumn 2004 Lecture Notes Graphical User Interfaces Koffman/Wolfgang Appendix C, pp
Java Programming Chapter 10 Graphical User Interfaces.
Programming With Java ICS201 University Of Ha’il1 Chapter 17 Graphical User Interfaces Swing I.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Graphical User Interface CSI 1101 N. El Kadri. Plan - agenda Graphical components Model-View-Controller Observer/Observable.
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
Java GUI CSCE 190 – Java Instructor: Joel Gompert Mon, July 26, 2004.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
GUI Chapter 10 Graphics context and objects Creating a window based application JFrame, JTextField, JButton Containers and Controls Graphics commands Layout.
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.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
FEN IntroJava2006 AAU1 GUI: Graphical User Interface AWT/SWING: Components Drag and Drop in NetBeans Events Listeners.
1 Graphical User Interfaces AWT and Swing packages Frames and Panels Components Nested Panels Images Reading for this Lecture: L&L, 3.9 – 3.11.
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.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
For (int i = 1; i
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Event-Driven Programming and GUIs l Swing Basics and.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
Graphical User Interfaces. Graphical input and output with JOptionPane.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Java the UML Way versjon Only to be used in connection with the book "Java the UML Way", by Else Lervik and.
Basics of GUI Programming Chapter 11 and Chapter 22.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Event-Driven Programming CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Computer Science [3] Java Programming II - Laboratory Course Lab 4 -1 : Introduction to Graphical user interface GUI Components Faculty of Engineering.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
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.
Lesson 28: More on the GUI button, frame and actions.
1 Lecture 8: User Interface Components with Swing.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Java Swing. Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: – Events:
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.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
A Quick Java Swing Tutorial
Lecture 15 Basic GUI programming
CSC 205 Programming II Lecture 5 AWT - I.
CompSci 230 S Programming Techniques
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Introduction to Event Handling
A Quick Java Swing Tutorial
Advanced Programming in Java
GUI and Event-Handling Programming
Programming Graphical User Interface (GUI)
Graphical User Interface
Presentation transcript:

Introduction to GUI Programming with Java Graphical User Interfaces With AWT and Swing Towson University *Ref:

Graphical User Interface

3 - Users interact with application programs using graphical components such as buttons, text boxes, and menus as well as console. - Hard to write a GUI application, but most of functions are provided by a set of classes called Swing Swing –A large package –Composed of graphical components: Windows Buttons Menus Text fields –Built on the fundamental classes of the Abstract Windowing Toolkit (AWT) –Come with recent Java releases GUI

4 - Users controls the application by interacting with the graphical components, generating events. GUI Events –Mouse clicking on a button –Making a choice from a menu –Entering text in a text box –Dragging a scroll bar Event-driven programming –Users cause events on the GUI components and the program responds to these events. –Programming by organizing the GUI components contained in the Swing package. Events

5 ●GUI Program –Graphical Components: Swing objects or extended one –Listener methods: Java methods the interface GUI components with the application tasks by calling application methods –Application methods: Java methods performing specific functional tasks GUI Program

GUI Component

7 Container Classes ●Window –A fundamental container –Includes other GUI components –Ex) Browser is a window (container) containing buttons, menus, slides, icons, and other GUI components. Container –A container can contain another container. –Ex) Main window contains frames which contain other components.

8 Java Classes ●AWT and Swing –Inherited from Java Object class AWT –Contains the fundamental classes used for constructing GUIs. –Component class is defined as the base abstract class. –AWT classes: Button, Canvas, and Container inherited from Component class Swing classes –Swing JComponent( derived rom AWT Container class) one of the base class of Swing –Swing JFrame( from AWT Frame class ) Usually the main container for a GUI application

9 Swing component hierarchy Graphical components in Java form an inheritance hierarchy: java.lang.Object +--java.awt.Component +--java.awt.Container | +--javax.swing.JComponent | +--javax.swing.JButton | +--javax.swing.JLabel | +--javax.swing.JMenuBar | +--javax.swing.JOptionPane | +--javax.swing.JPanel | +--javax.swing.JTextArea | +--javax.swing.JTextField | +--java.awt.Window +--java.awt.Frame +--javax.swing.JFrame When doing GUI programming, always import these packages: import java.awt.*; import javax.swing.*;

10 Java Programming: Program Design Including Data Structures10 Inheritance Hierarchy

11 Java GUI : AWT and Swing Sun's initial idea: create a set of classes/methods that can be used to write a multi-platform GUI (Abstract Windowing Toolkit, or AWT) –problem: not powerful enough; limited; a bit clunky to use Second edition (JDK v1.2): Swing –a newer library written from the ground up that allows much more powerful graphics and GUI construction Drawback: Both exist in Java now; easy to get them mixed up; still have to use both sometimes!

12 JComponent Classes ●Container family –Can contain components –Can be placed inside containers –Can be displayed on the monitor –Can generate events –Can register event listeners Swing classes –All Swing classes are descendants of Container class. –In addition to JComponent, JLabel, JPanel, JSlider, JTextComponent, JButton, …

13 JFrame class ●JFrame –Represents the window of a GUI application program –Can hold the components and methods of your application Methods –setSize() –setBounds() –setVisible() –setDefaultCloseOperation() ●Frame in Java –A window containing borders, buttons, and other features.

14 JFrame example 1 A simple program that creates and shows a JFrame : import javax.swing.*; public class SimpleFrame { public static void main(String[] args) { JFrame frame = new JFrame(“SimpleFrame”); frame.setSize(300,200); frame.setVisible(true); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); } Graphical output:

15 JFrame example 2 import java.awt.*; import javax.swing.*; public class SimpleFrame2 { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setForeground(Color.WHITE); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLocation(new Point(100, 50)); frame.setSize(new Dimension(300, 120)); frame.setTitle("A frame"); frame.setVisible(true); } Graphical output:

16 A frame is a graphical window that can be used to hold other components public JFrame() public JFrame(String title) Creates a frame with an optional title. public void setTitle(String text) Puts the given text in the frame’s title bar. public void setDefaultCloseOperation(int op) Makes the frame perform the given action when it closes. Common value: JFrame.EXIT_ON_CLOSE public void add(Component comp) Places the given component or container inside the frame. –How would we add more than one component to the frame? NOTE: Call setVisible(true) to make a frame appear on screen after creating it. JFrame

17 JButton class ●JButton –Inherited from AbstractButton which is inherited from JComponent –Can contain other components –ButtonFrame and ButtonDemo

18 Components example This program attempts to show 2 buttons: import java.awt.*; import javax.swing.*; public class ComponentsExample1 { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(300, 100)); frame.setTitle("A frame"); JButton button1 = new JButton(); button1.setText("I'm a button."); button1.setBackground(Color.BLUE); frame.add(button1); JButton button2 = new JButton(); button2.setText("Click me!"); button2.setBackground(Color.RED); frame.add(button2); frame.setVisible(true); }

19 Changing layouts We can correct the program's appearance by changing the frame's layout manager. Change the layout by calling the setLayout method on the frame and passing a layout manager object. –We will see several layout managers later. –We'll use one called a FlowLayout, which sizes each component to its preferred size and positions them in left-to-right rows. –If the following line is added to the preceding program just before calling setVisible(true), its appearance will be: frame.setLayout(new FlowLayout());

Action events with ActionListener

21 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)

22 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.*;

23 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.

24 Listening for events attach a listener to the component listener’s appropriate method will be called when event occurs (e.g. when the button is clicked) for Action events, use ActionListener ActionListeners are event handlers to define what should be done when an user performs certain operation.

25 Writing Action Listener Declare an event handler class by specifying that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. public class MyHandler implements ActionListener { … } Register an instance of the event handler class as a listener on one or more components someComponent.addActionListener(instanceOfMyHandler); ActionListener interface is special, enforcing the inclusion of the method, actionPerformed(). Public void actionPerformed(ActionEvent e) { … }

26 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 MyActionHandler implements ActionListener { public void actionPerformed(ActionEvent event){ JButton.showMessageDialog(null, "An event occurred!"); }

27 Attaching an ActionListener import java.awt.*; import java.awt.event.*; public class MyAH extends Frame implements WindowListener,ActionListener { TextField text = new TextField(20); Button b; private int numClicks = 0; public static void main(String[] args) { MyAH myWindow = new MyAH("My first window"); myWindow.setSize(350,100); myWindow.setVisible(true); } public MyAH(String title) { super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click me"); add(b); add(text); b.addActionListener(this); } public void actionPerformed(ActionEvent e) { numClicks++; text.setText("Button Clicked " + numClicks + " times"); } public void windowClosing(WindowEvent e) { dispose(); System.exit(0); }... } // end of class MyAH

28 Text Field Example Capturing user input from a text field public void actionPerformed(ActionEvent e) { String textFieldValue = text.getText(); text.setText(textFieldValue + " PASSED....."); }

29 JTextField methods getText() setText()

30 import java.awt.*; import java.awt.event.*; import javax.swing.JTextField; import javax.swing.JTextArea; import javax.swing.JButton; import javax.swing.JLabel; public class MyAH extends Frame implements WindowListener,ActionListener { JTextField text = new JTextField(20); JLabel label1 = new JLabel("AWT Button Example"); Button b; private int numClicks = 0; JLabel label2 = new JLabel("Please type numeric expression"); JTextField input = new JTextField(20); JButton bSubmit; //ButtonFrame frm = new ButtonFrame("Button Demo"); JTextArea output = new JTextArea(20, 20); public static void main(String[] args) { MyAH myWindow = new MyAH("My first window"); myWindow.setSize(350,250); myWindow.setLayout(new FlowLayout()); myWindow.setVisible(true); }

31 public MyAH(String title) { super(title); setLayout(new FlowLayout()); addWindowListener(this); b = new Button("Click Me!"); bSubmit = new JButton("Submit"); // construct a JButton add(label1); add(b); add(text); add(label2); add(input); add(bSubmit); //input.setText("Type numeric expression. "); add(output); b.addActionListener(this); MyActionHandler calcHandler = new MyActionHandler(); bSubmit.addActionListener(calcHandler); }

32 public void actionPerformed(ActionEvent e) { numClicks++; String textFieldValue = text.getText(); text.setText("Button has been pressed " + numClicks + " times."); /* String inputTextFieldValue = inputTextFieldValue = input.getText(); Double outputValue = calculate(inputTextFieldValue); input.setText(inputTextFieldValue); //output.setText("Result equals" + i*100); output.setText("Result equals " + inputTextFieldValue); //output.setText("Result equals" + outputValue); */ } public double calculate(String exp) { return 100; } public void windowClosing(WindowEvent e) { dispose(); System.exit(0); }

33 public void windowOpened(WindowEvent e) {} public void windowActivated(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public class MyActionHandler implements ActionListener { public void actionPerformed(ActionEvent e) { String inputTextFieldValue = input.getText(); Double outputValue = calculate(inputTextFieldValue); input.setText(inputTextFieldValue); output.setText("Result equals " + inputTextFieldValue); } } // end of class MyActionHandler } // end of class MyAH