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:

Slides:



Advertisements
Similar presentations
Introduction to JFC Swing Written by Adam Carmi. Agenda About JFC and Swing Pluggable Look and Feel Swing Components Borders Layout Management Events.
Advertisements

Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java GUI Libraries Swing Programming. Swing Components Swing is a collection of libraries that contains primitive widgets or controls used for designing.
Java Swing Toolkit Graphics The key to effectively using graphics in Java is understanding: –the basic components of the graphics library –the patterns.
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.
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.
Creating a GUI with Swing. Introduction Very useful link: Swing – is a part of JFC (Java Foundation.
CPSC150 Week 12 Graphical User Interfaces Chapter 11.
Contructing GUI’s in Java Implemented in the Swing API Imported into your programs by: import javax.swing.*; Most Swing programs also need the AWT packages.
CC1007NI: Further Programming Week 5 Dhruba Sen Module Leader (Islington College)
Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.
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 Chapter 10 Graphical User Interfaces.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Intro to Java 2 By Geb Thomas Based on the Java TutorialJava Tutorial.
Java Programming: From Problem Analysis to Program Design, Second Edition1  Learn about basic GUI components.  Explore how the GUI components JFrame,
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.
Object Oriented Programming Ders 11: Interfaces Mustafa Emre İlal
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.
Java GUIs and Graphics CNS Outline  Introduction  Events  Components  Layout managers  Drawing  Introduction  Events  Components  Layout.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
Introduction to Swing Components Chapter 14.  Part of the Java Foundation Classes (JFC)  Provides a rich set of GUI components  Used to create a Java.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
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.
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.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
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.
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.
CS Fall 2012, Lab 09 Haohan Zhu. Boston University Slideshow Title Goes Here CS Fall 2012, Lab /20/2015 GUI - Graphical User Interface.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Programming with Java’s Swing API February 4, 2003 CMPS Advanced Programming Graphical User Interfaces.
Creating a GUI with JFC/Swing. What are the JFC and Swing? JFC –Java Foundation Classes –a group of features to help people build graphical user interfaces.
CS1054: Lecture 21 - Graphical User Interface. Graphical User Interfaces vs. Text User Interface.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Introduction to GUI in 1 Graphical User Interface 2 Nouf Almunyif.
Swing Components. Introduction Swing – A set of GUI classes – Part of the Java's standard library –Much better than the previous library: AWT Abstract.
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.
Creating a Window. A basic window in Java is represented by an object of the class Window in the package java.awt.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
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.
Graphical User Interface (GUI)
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Getting Started with GUI Programming Chapter 10 CSCI 1302.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
Module 13: Swing API Object Oriented Programming(Java)
A Quick Java Swing Tutorial
CSC 205 Programming II Lecture 5 AWT - I.
Graphical User Interfaces
A First Look at GUI Applications
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Timer class and inner classes
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced Programming in Java
Constructors, GUI’s(Using Swing) and ActionListner
Graphical User Interface
Java Chapter 1 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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: AWT Abstract Window Toolkit Highlights –A rich set of widgets Widget: Any GUI element (also called: components) –Contents and shape are separated (MVC support)‏ –Fine-grained control over the behavior and look and feel –Platform independent Isolates the programmer from the operating system's GUI

3 Swing Components Containers –Contain and manage other components. –Top Level/Internal –Examples: JFrame (Top Level), JScrollPane, JPanel. Basic controls –Atomic components –Used for showing ouput and/or getting some input –Inherits JComponent –Examples: JButton, JLabel, JTextArea, JTable, Jlist Usually every Swing class extends the corresponding AWT class –For backward-compatibility reasons

4 My First Swing Program import javax.swing.*; import java.awt.BorderLayout; public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame"); // operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); }

5 Top Level Containers: JDialog javax.swing.JDialog : –More simple and limited than frames –Typically used for showing a short message on the screen –Also has a border and a title bar –May have an owner If the owner is invisible the dialog will also be invisible –Use the static method of JoptionPane to show standard dialog boxes: JOptionPane.showMessageDialog(null, "4+2=6");

6 Top Level Containers: JFileChooser javax.swing.JFileChooser : –Allows the the user to choose a file –Supports “open” and “save”: showOpenDialog(),showSaveDialog()‏ JFileChooser fc = new JFileChooser(); int returnVal = fc.showOpenDialog(null); if(returnVal == JFileChooser.APPROVE_OPTION) System.out.println("File: " + fc.getSelectedFile());

7 Top Level Containers: JFrame javax.swing.JFrame : –Top-level window with a title and a border. –Usually used as a program's main window

8 More on JFrame Made of several layers Widgets are added to the Content Pane layer. –Use getContentPane() to obtain it Other layers are used for customizing the window's appearence

9 Internal Containers Not Top level containers Can contain other non-top level components Examples: –JScrollPane : Provides a scrollable view of its components –JSplitPane : Separates two components –JTabbedPane : User chooses which component to see

10 Containers - Layout Each container has a layout manager –Determines the size, location of contained widgets. Setting the current layout of a container: void setLayout(LayoutManager lm) LayoutManager implementing classes: –BorderLayout –BoxLayout –FlowLayout –GridLayout

11 Containers - Layout

12 Swing Components

13 Swing Components

14 First Swing Program Revisited import javax.swing.*; import java.awt.BorderLayout; public class First { public static void main(String[] args) { JFrame frame = new JFrame("My First Frame"); // operation to do when the window is closed. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().add(new JLabel("I Love Swing"), BorderLayout.CENTER); frame.pack(); frame.setVisible(true); } Create a frame Create a text label Add the label to the content pane Choose the border layout Specify CENTER as the layout position

15 Input So we now know how to present widgets on the screen A program also needs to react to the user's actions Examples: –When the user presses a button we want to save a file –When the user closes the program we want to ask “are you sure?” –... Swing mechanism: Events and Listeners

16 Events, Listeners Swing defines all sorts of Listener interfaces –E.g.: ActionListener, MouseMotionListener, WindowListener,... public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e); } public interface MouseMotionListener extends EventListener { public void mouseDragged(MouseEvent e); public void mouseMoved(MouseEvent e); } There are default (empty) implementations for many of the listeners –E.g.: MouseMotionAdapter, WindowAdapter

17 Events, Listeners (cont.)‏ A listener is an object that implements a listener interface If we need to react to an event (on a certain widget) we register a listener object with that widget E.g.: addActionListener() registers an action listener with its receiver: JButton button = new JButton(); ActionListener listener =...; button.addActionListener(listener); When an event occurs, all registered listeners are notified –The appropriate listener method (e.g: actionPerformed() ) is invoked –An object describing the event is passed as a parameter

18 Event Handling Demo: GUI

19 Event Handling Demo: Code import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Events implements ActionListener { public Events() { JFrame frame = new JFrame("Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(this); frame.getContentPane().add(b); frame.pack(); frame.setVisible(true); } public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } public static void main(String[] args) { new Events(); } }

20 Inner Classes Nested within another classes Instance specific: –Has access to methods & fields of the object that created it –=> An inner class has TWO this variables Can be static –Can access only static members and methods only –A static method cannot create a non-static inner class

21 Local Classes Same as inner classes but defined inside a method Has access to local variables of the enclosing method –Only if the variable is defined as final Can be anonymous –Doesn’t have a name.

22 Event Handling Demo: Local Class import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Events { public Events() { JFrame frame = new JFrame("Events"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().setLayout(new FlowLayout()); JButton b = new JButton("Click me!"); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Thank you"); } }); frame.getContentPane().add(b); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new Events(); } }

23 Accessing Fields of Enclosing Object public class A { int x = 0; public void f() { B b = new B(); b.g(); System.out.println(x); // Output: 5 } public class B { public void g() { x = 5; } } public static void main(String[] args) { new A().f(); }

24 Using the Second this Variable public class A { public void f() { B b = new B(); System.out.println(b.g()); // Output: 1024 } public int g() { return 512; } public class B { public int g() { return A.this.g() * 2; } } public static void main(String[] args) { new A().f(); }

25 Appendix: Contact Book Program

26 Swing's JTable Each JTable has a TableModel object that holds the data shown by the table. DefaultTableModel is a default implementation of TableModel –By default it makes all the cells editable We can customize its behavior by subclassing –Or we can implement TableModel from scratch TableModelListener - a listener interface –Notified of changes in the model Use TableModel.addTableModelListener() to register a listener object

27 Contacts Book example overview Each contact has a name and a list of attributes –Each attribute has a name and a value. Operations: –Add contact Contact name is immutable –Add attributes Attribute is identified by it’s name, the attribute name is immutable, it’s value can be changed Classes: –Contact : represents a contact and maintains list of attributes –Contact.Attribute : Inner class that represents contact attribute. –ContactTableModel : model class for the table data Doesn’t allow to modify attribute names –ContactBook : represents the contact book widget.

28 Contacts Book example overview