Chapter 14: Windows and applets ● Java provides cross-platform window facilities ● In Java 1, this has been done by AWT package ● However AWT had some.

Slides:



Advertisements
Similar presentations
Chapter 14 Advanced GUI ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display.
Advertisements

Fondamenti di Java Introduzione alla costruzione di GUI (graphic user interface)
1 Event Listeners Some Events and Their Associated Event Listeners Act that Results in the EventListener Type User clicks a button, presses Enter while.
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Chapter 16 GUI Programming Basics GUI Overview Event-Driven Programming Basics GUI Classes and Packages A Simple Window Program JFrame Class Java Components.
User Interfaces II GUI – Awt, Swing, Web
15 Copyright © 2005, Oracle. All rights reserved. Adding User Interface Components and Event Handling.
Java GUI building with the AWT. AWT (Abstract Window Toolkit) Present in all Java implementations Described in (almost) every Java textbook Adequate for.
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 program.
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.
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Java Graphical User Interface (GUI) using Visual Editor in eclipse CSI 1390 – Java Programming Instructor: Saeid Nourian University.
Graphical User Interfaces
Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
Web Design & Development Lecture 19. Java Graphics 2.
CSE 1341 Honors Professor Mark Fontenot Southern Methodist University Note Set 21.
Advance Java Technology Java’s Role::MVC Architecture :: Swing Prof.Chintan Dave.
Graphics and event-driven programs Learning objectives By the end of this lecture you should be able to: identify and use some of the common components.
Basic Java – Interface design. Understand: How to use TextPad for Java How to define classes and objects How to create a GUI interface How event-driven.
Graphical User Interfaces Java’s AWT and Swing APIs.
Graphical User Interfaces (Part IV)
Java Software Development Paradigm Lecture # 12. Basics of GUI.
Examples. // A simple Frame with Rectangle Inside import java.awt.*; import javax.swing.*; import java.awt.geom.*; // For Shapes class rectComponent extends.
Drawing in a frame – Java GUI
CS18000: Problem Solving and Object-Oriented Programming.
Unit 3 Graphical User Interface (GUI) Dr. Magdi AMER.
Graphic User Interfaces Layout Managers Event Handling.
F27SB2 Programming Languages
Problem Solving 6 GUIs and Event Handling ICS-201 Introduction to Computing II Semester 071.
Graphical User Interfaces, 2D Graphics & Game Programming.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Graphical User Interface Bonus slides Interaction Between Components & Drawing.
Bar Graph Design. Left-side/Right-side mechanical processing creative, abstract reasoning.
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.
Java Applets- Using SwingWorker Dave Price and Chris Loftus Computer Science Department University of Wales, Aberystwyth.
Things to mention public static void main(String [] args) –The starting point for a free-standing Java application (i.e. one not run from the DrJava interactions.
Introduction to Java Classes, events, GUI’s. Understand: How to use TextPad How to define a class or object How to create a GUI interface How event-driven.
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Graphical User Interfaces (GUIs) GUI: An application that uses graphical objects to interact with users GUI applications consist of: –Events: A user or.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
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.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
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.
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,
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.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc..
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.
Java Programming Applets. Topics Write an HTML document to host an applet Understand simple applets Use Labels with simple AWT applets Write a simple.
Introduction to Java Chapter 9 - Graphical User Interfaces and Applets1 Chapter 9 Graphical User Interfaces and Applets.
Review_6 AWT, Swing, ActionListener, and Graphics.
Basics of GUI Programming Chapter 11 and Chapter 22.
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.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Graphical User Interface (GUI)
Applets. 9/04/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L12: Applets Slide 2 Applets Usually.
CIS 270—Application Development II Chapter 11—GUI Components: Part I.
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
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
A First Look at GUI Applications
Graphical User Interface (pronounced "gooey")
Chapter 13: Advanced GUIs and Graphics
Advanced GUIs and Graphics
Graphical User Interface
Presentation transcript:

Chapter 14: Windows and applets ● Java provides cross-platform window facilities ● In Java 1, this has been done by AWT package ● However AWT had some problems – Main problem was the different look&feel with other windows in the hosting OS ● Java 2 introduced swing which creates more compatible look & feel with the hosting OS ● In java we can define two type of GUI – Applets which run inside a web browser – Applications which run as a stadnalone window ● The model for applets and normal windows application is different, but with some efforts we can make applications that can be run as both

Applets ● Programs that run inside a browser ● When a browser loads a page that includes an applet, browser downloads the applet and starts it ● Because normally an applet comes from another machine, java runtime environment enforce some restrictions on them: – An applet can’t touch the local disk. Java offers digital signing for applets. Many applet restrictions are relaxed when you choose to allow signed applets – Applets can take longer to display, since you must download the whole thing every time, including a separate server hit for each different class.

Application framework for applets ● There is a JApplet class that all applets inherit from ● An applet overrides some of the methods to do some usefull work

A simple applet //: c14:Applet1.java // Very simple applet. import javax.swing.*; import java.awt.*; public class Applet1 extends JApplet { public void init() { getContentPane().add(new JLabel("Applet!")); }

Running inside a browser Basic taggs (old way!) in a web page: Things not as simple as above now, but we can use HTMLConverter to convert above to a form acceptable by current browsers: Internet explorer display:

Running applet as an application //: c14:Applet1c.java // An application and an applet. // import javax.swing.*; import java.awt.*; public class Applet1c extends JApplet { public void init() { getContentPane().add(new JLabel("Applet!")); } // A main() for the application: public static void main(String[] args) { JApplet applet = new Applet1c(); JFrame frame = new JFrame("Applet1c"); // To close the application: frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(applet); frame.setSize(100,50); applet.init(); applet.start(); frame.setVisible(true); }

A display framework In the book a display framework is implemented that eases creation of applets and window applications: public static void run(JFrame frame, int width, int height) {...} public static void run(JApplet applet, int width, int height){...} public static void run(JPanel panel, int width, int height) {...}

Putting buttons //: c14:Button1.java // Putting buttons on an applet. // import javax.swing.*; import java.awt.*; import com.bruceeckel.swing.*; public class Button1 extends JApplet { private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(b1); cp.add(b2); } public static void main(String[] args) { Console.run(new Button1(), 200, 50); }

Capturing an event ● When we run previous program if we click on buttons nothing will happen! ● For any control (e.g. a button) to do something usefull we need to write event handler code ● To do this we first register for an event on a control. For example using addActionListener() on Jbutton to register for pressing button actions ● addActionListener needs a class that implements ActionListener interface. This interface has a actionPerformed() method.

Example of event capturing public class Button2 extends JApplet { private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); private JTextField txt = new JTextField(10); class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { String name = ((JButton)e.getSource()).getText(); txt.setText(name); } private ButtonListener bl = new ButtonListener(); public void init() { b1.addActionListener(bl); b2.addActionListener(bl); Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(b1); cp.add(b2); cp.add(txt); } public static void main(String[] args) { Console.run(new Button2(), 200, 75); }

Runnin the example Pressing Button1

Controlling layout (layout manager) BorderLayout public class BorderLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.add(BorderLayout.NORTH, new JButton("North")); cp.add(BorderLayout.SOUTH, new JButton("South")); cp.add(BorderLayout.EAST, new JButton("East")); cp.add(BorderLayout.WEST, new JButton("West")); cp.add(BorderLayout.CENTER, new JButton("Center")); } public static void main(String[] args) { Console.run(new BorderLayout1(), 300, 250); }

Controlling layout (layout manager) FlowLayout public class FlowLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); for(int i = 0; i < 20; i++) cp.add(new JButton("Button " + i)); } public static void main(String[] args) { Console.run(new FlowLayout1(), 300, 250); }

Controlling layout (layout manager) GridLayout public class GridLayout1 extends JApplet { public void init() { Container cp = getContentPane(); cp.setLayout(new GridLayout(7,3)); for(int i = 0; i < 20; i++) cp.add(new JButton("Button " + i)); } public static void main(String[] args) { Console.run(new GridLayout1(), 300, 250); }

Events and listener types

Swing components - Buttons public class Buttons extends JApplet { private JButton jb = new JButton("JButton"); private BasicArrowButton up = new BasicArrowButton(BasicArrowButton.NORTH), down = new BasicArrowButton(BasicArrowButton.SOUTH), right = new BasicArrowButton(BasicArrowButton.EAST), left = new BasicArrowButton(BasicArrowButton.WEST); public void init() { Container cp = getContentPane(); cp.setLayout(new FlowLayout()); cp.add(jb); cp.add(new JToggleButton("JToggleButton")); cp.add(new JCheckBox("JCheckBox")); cp.add(new JRadioButton("JRadioButton")); JPanel jp = new JPanel(); jp.setBorder(new TitledBorder("Directions")); jp.add(up); jp.add(down); jp.add(left); jp.add(right); cp.add(jp); } public static void main(String[] args) { Console.run(new Buttons(), 350, 100); }

Icons and tooltips-changing Jbutton and other components look and feel faces = new Icon[] { new ImageIcon(getClass().getResource("Face0.gif")), new ImageIcon(getClass().getResource("Face1.gif")), new ImageIcon(getClass().getResource("Face2.gif")), new ImageIcon(getClass().getResource("Face3.gif")), new ImageIcon(getClass().getResource("Face4.gif")), }; jb = new JButton("JButton", faces[3]);... jb.setRolloverIcon(faces[1]); jb.setPressedIcon(faces[2]); jb.setDisabledIcon(faces[4]); jb.setToolTipText("Yow!");

Diffent looks

Other components ● TextFields – For one line text entry ● Borders – For adding a border to a component ● JscrollPane – Provides a scrollable view for a component:

Other components (cont.) ● JtextPane – A mini editor ● Check Boxes ● Radio buttons ● Combo boxes (drop-down list) ● List boxes – allows multiple selection ● JoptionPane – Message boxes ● Menus ● etc.

Drawing class SineDraw extends JPanel {... public void paintComponent(Graphics g) { super.paintComponent(g); int maxWidth = getWidth(); double hstep = (double)maxWidth/(double)points; int maxHeight = getHeight(); pts = new int[points]; for(int i = 0; i < points; i++) pts[i] = (int)(sines[i] * maxHeight/2 *.95 + maxHeight/2); g.setColor(Color.RED); for(int i = 1; i < points; i++) { int x1 = (int)((i - 1) * hstep); int x2 = (int)(i * hstep); int y1 = pts[i-1]; int y2 = pts[i]; g.drawLine(x1, y1, x2, y2); }....

Result

Other components (cont.) ● Dialog boxes - A dialog box is a window that pops up out of another window ● Sliders and progrss bars ● Trees ● Tables

Selecting look and feel Try { UIManager.setLookAndFeel(UIManager. getSystemLookAndFeelClassName()); } catch(Exception e) { throw new RuntimeException(e); }

Binding events dynamically It is possible to attache more than one listener to each Button: b1.addActionListener(new B()); b1.addActionListener(new B1()); During the execution of the program, it is possible to dynamically adde and remove listeners: txt.append("Button2 pressed\n"); int end = list.size() - 1; if(end >= 0) { b2.removeActionListener( (ActionListener) list.get(end)); list.remove(end); }

Separating business logic from UI logic class BusinessLogic { private int modifier; public BusinessLogic(int mod) { modifier = mod; } public void setModifier(int mod) { modifier = mod; } public int getModifier() { return modifier; } // Some business operations: public int calculation1(int arg){ return arg * modifier;} } public class Separation extends JApplet { private JTextField t = new JTextField(15), mod = new JTextField(15); private Jbutton calc1 = new JButton("Calculation 1"), private BusinessLogic bl = new BusinessLogic(2); public static int getValue(JTextField tf) { try { return Integer.parseInt(tf.getText()); } catch(NumberFormatException e) { return 0; } class Calc1L implements ActionListener { public void actionPerformed(ActionEvent e) { t.setText(Integer.toString( bl.calculation1(getValue(t)))); }

Visual builder tools and JavaBeans ● Starting with Visual Basic, visual builder tools become very famous ● They help in creating visual interfaces more easily and with more speed ● In java, with the use of JavaBeans we can create components that can be handled by Java visual builders ● In a typical visual builder tool you can drag and drop a component into a form and then modify its properties and write handlers for handling events on that component.

What is a JavaBean A bean is a Class with some conventions applied for naming methods: 1. For a property named xxx, you typically create two methods: getXxx( ) and setXxx( ). 2. For a boolean property, you can use the “get” and “set” approach above, but you can also use “is” instead of “get.” 3. Ordinary methods of the Bean don’t conform to the above naming convention, but they’re public. 4. For events, you use the Swing “listener” approach. It’s exactly the same as you’ve been seeing: addActionListener(ActionLister eListener) and removeActionLister(ActionListener) to handle a ActionEvent.

JavaBean example public class BangBean extends JPanel implements Serializable { private int xm, ym; private int cSize = 20; // Circle size private String text = "Bang!"; private int fontSize = 48; private Color tColor = Color.RED; private ActionListener actionListener; public BangBean() { addMouseListener(new ML()); addMouseMotionListener(new MML()); } public int getCircleSize() { return cSize; } public void setCircleSize(int newSize) { cSize = newSize; } public String getBangText() { return text; } public void setBangText(String newText) { text = newText; } public int getFontSize() { return fontSize; } public void setFontSize(int newSize) { fontSize = newSize; }

JavaBean example (cont.) public Color getTextColor() { return tColor; } public void setTextColor(Color newColor) { tColor = newColor; } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.BLACK); g.drawOval(xm - cSize/2, ym - cSize/2, cSize, cSize); } // This is a unicast listener, which is // the simplest form of listener management: public void addActionListener(ActionListener l) throws TooManyListenersException { if(actionListener != null) throw new TooManyListenersException(); actionListener = l; } public void removeActionListener(ActionListener l) { actionListener = null; }...