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.

Slides:



Advertisements
Similar presentations
Event handling and listeners What is an event? user actions and context event sources and listeners Why should my programs be event- driven? User interaction.
Advertisements

Graphic User Interfaces Layout Managers Event Handling.
Introduction to JFC Swing Written by Adam Carmi. Agenda About JFC and Swing Pluggable Look and Feel Swing Components Borders Layout Management Events.
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.
Event Handling. In this class we will cover: Basics of event handling The AWT event hierarchy Semantic and low-level events in the AWT.
Event Handling Events and Listeners Timers and Animation.
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.
1 Event Driven Programming with Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Unit 111 Java GUI Components and Events  Learning Outcomes oDistinguish between GUI components and containers. oIdentify and distinguish top-level containers.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Graphical User Interfaces
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Lesson 35: Review of the Java GUI. The JFrame, Container and JButton.
PROGRAMMING REVIEW Lab 2 EECS 448 Dr Fengjun Li and Meenakshi Mishra.
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,
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.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
GUI programming Graphical user interface-based programming.
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,
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 343 Davis Hall
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
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.
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.
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.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
UID – Event Handling and Listeners Boriana Koleva
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
COSC 3461: Module 2 Control Flow Paradigms: Reacting to the User.
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Object Oriented Programming.  Interface  Event Handling.
Ch13 Creating windows and applets. Short overview AWT (Abstract Windowing Toolkit) Early Java development used graphic classesEarly Java development used.
CIS Intro to JAVA Lecture Notes Set 8 9-June-05.
Graphical User Interfaces A Graphical User Interface (GUI) in Java is created with at least three kinds of objects: –components, events, and listeners.
CS 151: Object-Oriented Design October 1 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Event Driven Programs with a Graphical User Interface Rick Mercer.
Event-Driven Programming F Procedural programming is executed in procedural order. F In event-driven programming, code is executed upon activation of events.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
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.
Jozef Goetz Credits: Copyright  Pearson Education, Inc. All rights reserved. expanded by J. Goetz, 2016.
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:
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.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 7 Event-Driven Programming and Basic GUI Objects.
GUI 1: JFC and Swing Basics OOP tirgul No
Module 13: Swing API Object Oriented Programming(Java)
Multiple buttons and action calls
CSC 205 Programming II Lecture 5 AWT - I.
Events and Event Handling
CompSci 230 S Programming Techniques
A First Look at GUI Applications
A Quick Java Swing Tutorial
Ellen Walker Hiram College
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
Advanced Programming in Java
Constructors, GUI’s(Using Swing) and ActionListner
Presentation transcript:

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 (GUIs) Swing –Components for GUIs –to use Swing, you have to import javax.swing package.

What are the objects in an application? Frame – the top-level container class Menu Bar -- optional Content Pane – contains the visible components in the top-level container’s GUI

How to make frames (main windows)? A frame, an instance of the JFrame, is a window that typically has decorations such as a border, a title, and a buttons for closing and iconifying the window. Every GUI components must be put into a container. Each GUI components can be contained only once. A frame has a content pane that contains the visible components An optional menu bar can be added to a top-level container

import java.awt.*; import javax.swing.*; public class App1 { public static void main(String[] args) { // 1. Optional: Specify who draws the window // decorations. (default: native window system) JFrame.setDefaultLookAndFeelDecorated(true); // 2. Create a top-level frame JFrame frame = new JFrame("Application 1"); // 3. Optional: What happens when the frame closes? frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 4. Optional: How the components are put in the // frame? Container cp = frame.getContentPane(); cp.setLayout(new FlowLayout());

// 5. Create GUI/Swing components JButton button1 = new JButton("A JButton"); JButton exitButton = new JButton(" Exit "); JTextField text = new JTextField("This is a text field.", 20); // 6. Put the components in the frame cp.add(button1, BorderLayout.WEST); cp.add(text, BorderLayout.CENTER); cp.add(exitButton, BorderLayout.EAST); // 7. Set frame size // frame.setSize(int width, int hieght); frame.pack(); // 8. Show it frame.setVisible(true); }

- without JFrame.setDefaultLookAndFeelDecorated(true); - with JFrame.setDefaultLookAndFeelDecorated(true); frame.pack();

frame.setSize(450, 200); frame.setSize(250, 200);

Run the application When you click on a button, or type in a text field and press enter, an event is generated. Nothing happen, why? To make the program response to an action, you need to create a listener object that waits for a particular event to handle and modified the correspondence method.

Example of actions Act that results in the eventListener Type User clicks a button, presses Return while typing in a text field, or chooses a menu item ActionListener User closes a frame (main window)WindowListener User presses a mouse button while the cursor is over a component MouseListener User moves the mouse over a componentMouseMotionListener

How to implement an event handler ? 1.Define a new class that either implements a listener interface or extends a class that implements a listener interface (adapter class) public class MyListener implements ActionListener {. }

How to implement an event handler ? 2.Register an instance of the event handler class as a listener upon one or more components someComponent.addActionListener(anInstanceOfMyListener);

How to implement an event handler ? 3.Implement all methods in the listener interface. public void actionPerformed(ActionEvent e) { // code that reacts to the action... }

Example // Program App3 with event handling public class App3 { public static JTextField text; public static void main(String[] args) {... // 6.1. Register an event handler exitButton.addActionListener( new MyExitButtonListener()); button1.addActionListener(new MyButtonListener());... }

// New classes that implement ActionListener class MyExitButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } class MyButtonListener implements ActionListener { static int count = 0; public void actionPerformed(ActionEvent e) { App2.text.setText("A JButton has been pressed " + ++count + " times."); } click 2 times

Using inner class A class defined inside any class. Advantages: –Be able to access instance variables from the enclosing class. –Keep the event-handling code close to where event occurs. –Your event-handling class can inherit from other class. Disadvantages: –lengthy class –longer loading time –increase memory requirements

// Example // Program App4 with event handling using inner class public class App4 { public static void main(String[] args) {... class MyExitButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } class MyButtonListener implements ActionListener { // code for event handling } // 6.1. Register an event handler exitButton.addActionListener( new MyExitButtonListener()); button1.addActionListener(new MyButtonListener());... }

// Example // Program App5 with event handling using // anonymous inner class public class App5 { public static void main(String[] args) {... // 6.1. Register an event handler exitButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); }); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // code for event handling });... }

Writing Event Listeners The event-listener methods should execute quickly. Because all event-handling and drawing methods are executed in the same thread. If the action that need to be performed will take a long time, initialize as required and perform the rest in a new thread (will cover later).

Getting Event Info.: Event Objects EventObject – the root class of all event state objects Useful methods: getSource public Object getSource()Object Returns: The object on which the Event initially occurred. toString public String toString()String Overrides: toStringtoString in class ObjectObject Returns: A a String representation of this EventObject.

Listeners supported by Swing Component listener – changes in the component’s size, position, or visibility. Focus listener – whether the component gained or list the ability to receive keyboard input. Key listener – keypresses; key events are fired only by the component that has the current keyboard focus. Mouse events – mouse clicks and movement into or out of the component’s drawing area. Mouse-motion events – changes in the cursor’s position over the component

Common Event-Handling Problem A component does not generate the events it should. –Did you register the right kind of listener to detect the events? –Did you register the listener to the right object? –Did you implement the event handler correctly?

Exercise 1.Create a calculator application that has buttons for 0 – 9, +, , and = signs. It should have a display are that shows the result. 2.Modify the program from (1) to have more functions such as, *, /, %, or handle real number.

มาดูการวาดรูปกัน หลักๆคือ สร้าง component object แล้วเติม มันลงไปในเฟรม เพราะฉะนั้น สิ่งที่ทำได้ง่ายๆ คือ – เขียนคลาสซึ่ง extends จาก JComponent

public class RectangleComponent extends Jcomponent{ //override ของเก่าตรงเมธอดนี้ // เมธอดนี้ถูกเรียกเมื่อ component ถูกใช้ครั้ง แรก ถูก //resize หรือถูกแสดงหลังจาก hidden public void paintComponent(Graphics g){ } State ของการวาด เช่น สี ฟ้อนต์

public void paintComponent(Graphics g){ // เวลาใช้จริง ต้องเป็น Graphics2D // ใช้ casting เข้ามาช่วย Graphics2D g2 = (Graphics2D) g; Rectangle box = new Rectangle(5,10,20,30); g2.draw(box); box.translate(15,25); g2.draw(box); }

โค้ดในการใช้งาน main จะเป็น ดังนี้ JFrame frame = new JFrame(); frame.setSize(300,400); frame.setDefaultCloseOperation(Jframe.EXI T_ON_CLOSE); RectangleComponent component = newRectangleComponent(); frame.add(component); frame.setVisible(true);