CS 335 Lecture 06 Java Programming GUI and Swing



Similar documents
5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

The class JOptionPane (javax.swing) allows you to display a dialog box containing info. showmessagedialog(), showinputdialog()

Providing Information (Accessors)

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Using A Frame for Output

GUI Event-Driven Programming

Swing. A Quick Tutorial on Programming Swing Applications

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

Programming with Java GUI components

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

Graphical User Interfaces

GUI Components: Part 2

Advanced Network Programming Lab using Java. Angelos Stavrou

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Extending Desktop Applications to the Web

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

How to Convert an Application into an Applet.

Homework/Program #5 Solutions


Mouse Event Handling (cont.)

Essentials of the Java(TM) Programming Language, Part 1

core 2 Handling Mouse and Keyboard Events

How Scala Improved Our Java

Developing GUI Applications: Architectural Patterns Revisited

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

Artificial Intelligence. Class: 3 rd

Tutorial Reference Manual. Java WireFusion 4.1

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

Java Mouse and Keyboard Methods

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Event-Driven Programming

The Basic Java Applet and JApplet

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

public class demo1swing extends JFrame implements ActionListener{

Fachbereich Informatik und Elektrotechnik Java Swing. Advanced Java. Java Swing Programming. Programming in Java, Helmut Dispert

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT COURSE CURRICULUM COURSE TITLE: ADVANCE JAVA PROGRAMMING (COURSE CODE: )

Skills and Topics for TeenCoder: Java Programming

Essentials of the Java Programming Language

Schueler-Organisiertes Lernen am Beispiel von Grafischen Benutzer-Schnittstellen in Java Tag der Offenen Tür - GTS 2008

Lecture VII JAVA SWING GUI TUTORIAL

Java is commonly used for deploying applications across a network. Compiled Java code

@ - Internal # - Online TH PR OR TW TOTAL HOURS # @ 175

JiST Graphical User Interface Event Viewer. Mark Fong

Software Design: Figures

How To Write A Program For The Web In Java (Java)

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

During the process of creating ColorSwitch, you will learn how to do these tasks:

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

Remote Method Invocation

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

Informatik II. // ActionListener hinzufügen btnconvert.addactionlistener(this); super.setdefaultcloseoperation(jframe.

Dev Articles 05/25/07 11:07:33

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

Karsten Lentzsch JGoodies SWING WITH STYLE

Assignment # 2: Design Patterns and GUIs

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Model-View-Controller (MVC) Design Pattern

Tema: Encriptación por Transposición

Here's the code for our first Applet which will display 'I love Java' as a message in a Web page

Programação Orientada a Objetos. Programando Interfaces Gráficas Orientadas a Objeto Parte 2

Syllabus. Java programs for creating applets for display of images, text and animation. Input output and random files programs in java

Syllabus for CS 134 Java Programming

Event processing in Java: what happens when you click?

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

Java Appletek II. Applet GUI

Analysis Of Source Lines Of Code(SLOC) Metric

JIDE Action Framework Developer Guide

Twin A Design Pattern for Modeling Multiple Inheritance

Lab 1A. Create a simple Java application using JBuilder. Part 1: make the simplest Java application Hello World 1. Start Jbuilder. 2.

Automated Data Collection for Usability Evaluation in Early Stages of Application Development

Course/Year W080/807 Expected Solution Subject: Software Development to Question No: 1

Handout 3 cs180 - Programming Fundamentals Spring 15 Page 1 of 6. Handout 3. Strings and String Class. Input/Output with JOptionPane.

Platform-Specific Event Handling

Eclipse with Mac OSX Getting Started Selecting Your Workspace. Creating a Project.

Example 1: Creating Jframe. Example 2: CenterFrame. Jaeki Song, Ph.D. Box Lubbock, TX, PH:

Lab 9. Spam, Spam, Spam. Handout 11 CSCI 134: Spring, To gain experience with Strings. Objective

public class Application extends JFrame implements ChangeListener, WindowListener, MouseListener, MouseMotionListener {

Chapter 2 Introduction to Java programming

Summer Internship 2013

Tutorial : Getting started with the Java TM Media Framework

11. Applets, normal window applications, packaging and sharing your work

Introduction to the Java Programming Language

Illustration 1: An applet showing constructed responses in an intuitive mode. Note the misprint!

GOPAL RAMALINGAM MEMORIAL ENGINEERING COLLEGE. Rajeshwari nagar, Panapakkam, Near Padappai, Chennai

Konzepte objektorientierter Programmierung

Object Oriented Programming with Java. School of Computer Science University of KwaZulu-Natal

Demo: Embedding Windows Presentation Foundation elements inside a Java GUI application. Version 7.3

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

Introduction to Object-Oriented Programming

16.1 DataFlavor DataFlavor Methods. Variables

VAASAN AMMATTIKORKEAKOULU UNIVERSITY OF APPLIED SCIENCES. Xiaoling Yu IMPLEMENTATION OF A SECURE SHELL FILE TRANSFER PROGRAM IN JAVA

1 Hour, Closed Notes, Browser open to Java API docs is OK

How To Use The Command Pattern In Java.Com (Programming) To Create A Program That Is Atomic And Is Not A Command Pattern (Programmer)

Lösningsförslag till tentamen

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

java.applet Reference

The following four software tools are needed to learn to program in Java:

Transcription:

CS 335 Lecture 06 Java Programming GUI and Swing

Java: Basic GUI Components Swing component overview Event handling Inner classes and anonymous inner classes Examples and various components Layouts Panels

Alternatives AWT (almost obsolete now) SWT (The Standard Widget Toolkit) Open source from IBM Using native window calls fast response Very much like MFC

Swing Components Lightweight vs. heavyweight components: Lightweight: platform independent Heavyweight: tied to platform; windowing system Peer object: object responsible for interactions between heavyweight object and local system Swing components are lightweight

A Java Screen Layout Frame JFrame Menu Bar (optional) Content Pane

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class FrameDemo public static void main(string s[]) JFrame frame = new JFrame("FrameDemo"); frame.addwindowlistener(new WindowAdapter() public void windowclosing(windowevent e) System.exit(0); ); JLabel mylabel = new JLabel( Hello World"); mylabel.setpreferredsize(new Dimension(175, 100)); frame.getcontentpane().add(mylabel, BorderLayout.CENTER); frame.pack(); frame.setvisible(true); // show() is deprecated

Choose Look and Feel Only available under Swing try UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName()); catch (Exception e) Always give me the java look! Ref: available look and feel at http://java.sun.com/docs/books/tutorial/uiswing/misc/plaf.html

The Event Handing Model GUI components are event-driven Programmer must register events implement event handlers Event registration: add listeners Event implementation: define listener methods

3 Steps for an Event Handler 1. either implements a listener interface or extends a class that implements a listener interface public class MyClass implements ActionListener 2. Register your listener somecomponent. addactionlistener(instanceofmyclass); 3. Implement user action public void actionperformed(actionevent e)...//code that reacts to the action...

Example: Registering Events public class TextFieldTest extends JFrame private JTextField text1, text2, text3; private JPasswordField password; public TextFieldTest() super( "Testing JTextField and JPasswordField" ); Container c = getcontentpane(); c.setlayout( new FlowLayout() ); // construct textfield with default sizing text1 = new JTextField( 10 ); c.add( text1 ); // construct textfield with default text text2 = new JTextField( "Enter text here" ); c.add( text2 );

// construct textfield with default text and // 20 visible elements and no event handler text3 = new JTextField( "Uneditable text field", 20 ); text3.seteditable( false ); c.add( text3 ); // construct textfield with default text password = new JPasswordField( "Hidden text" ); c.add( password ); TextFieldHandler handler = new TextFieldHandler(); text1.addactionlistener( handler ); text2.addactionlistener( handler ); text3.addactionlistener( handler ); password.addactionlistener( handler ); setsize( 325, 100 ); show();

Event Registration

Listeners for Event Types ActionListener MouseListener MouseMotionListener KeyListener ButtonChangeListener AncestorListener PropertyChangeListener...

Example: Handling Events // inner class for event handling private class TextFieldHandler implements ActionListener public void actionperformed( ActionEvent e ) String s = ""; if ( e.getsource() == text1 ) s = "text1: " + e.getactioncommand(); else if ( e.getsource() == text2 ) s = "text2: " + e.getactioncommand(); else if ( e.getsource() == text3 ) s = "text3: " + e.getactioncommand(); else if ( e.getsource() == password ) JPasswordField pwd = (JPasswordField) e.getsource(); s = "password: " + new String( pwd.getpassword() ); JOptionPane.showMessageDialog( null, s );

Driver for Example public static void main( String args[] ) TextFieldTest app = new TextFieldTest(); app.addwindowlistener( new WindowAdapter() public void windowclosing( WindowEvent e ) System.exit( 0 ); );

Event Handling and Inner Classes Event handler classes are usually private Often event handlers are anonymous inner classes defined purely to implement the handing method: app.addwindowlistener( new WindowAdapter() public void windowclosing( WindowEvent e ) System.exit( 0 ); );

GUI Components http://java.sun.com/docs/books/tutorial/uiswing/components/components.html For example JTextField and JPasswordField JButton JCheckBox and JRadioButton JComboBox JList and Multiple Selection Lists

JTextField and JPasswordField

JButton public class ButtonTest extends JFrame private JButton plainbutton, fancybutton; public ButtonTest() super( "Testing Buttons" ); Container c = getcontentpane(); c.setlayout( new FlowLayout() ); // create buttons plainbutton = new JButton( "Plain Button" ); c.add( plainbutton );

Icon bug1 = new ImageIcon( "bug1.gif" ); Icon bug2 = new ImageIcon( "bug2.gif" ); fancybutton = new JButton( "Fancy Button", bug1 ); fancybutton.setrollovericon( bug2 ); c.add( fancybutton ); // create an instance of inner class ButtonHandler // to use for button event handling ButtonHandler handler = new ButtonHandler(); fancybutton.addactionlistener( handler ); plainbutton.addactionlistener( handler ); setsize( 275, 100 ); show();

public static void main( String args[] ) ButtonTest app = new ButtonTest(); app.addwindowlistener( new WindowAdapter() public void windowclosing( WindowEvent e ) System.exit( 0 ); ); // or NEW for ver 1.3 of java 2 // frame.setdefaultcloseoperation(jframe.exit_on_close); // inner class for button event handling private class ButtonHandler implements ActionListener public void actionperformed( ActionEvent e ) JOptionPane.showMessageDialog( null, "You pressed: " + e.getactioncommand() );

Event Handling: The Mouse mousepressed mouseclicked mousereleased mouseentered, mouseexited mousedragged mousemoved

// Fig. 12.17: MouseTracker.java // Demonstrating mouse events. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MouseTracker extends JFrame implements MouseListener, MouseMotionListener private JLabel statusbar; public MouseTracker() super( "Demonstrating Mouse Events" ); statusbar = new JLabel(); getcontentpane().add( statusbar, BorderLayout.SOUTH ); // application listens to its own mouse events addmouselistener( this ); addmousemotionlistener( this ); setsize( 275, 100 ); show();

// MouseListener event handlers public void mouseclicked( MouseEvent e ) statusbar.settext( "Clicked at [" + e.getx() + ", " + e.gety() + "]" ); public void mousepressed( MouseEvent e ) statusbar.settext( "Pressed at [" + e.getx() + ", " + e.gety() + "]" ); public void mousereleased( MouseEvent e ) statusbar.settext( "Released at [" + e.getx() + ", " + e.gety() + "]" ); public void mouseentered( MouseEvent e ) statusbar.settext( "Mouse in window" ); public void mouseexited( MouseEvent e ) statusbar.settext( "Mouse outside window" );

// MouseMotionListener event handlers public void mousedragged( MouseEvent e ) statusbar.settext( "Dragged at [" + e.getx() + ", " + e.gety() + "]" ); public void mousemoved( MouseEvent e ) statusbar.settext( "Moved at [" + e.getx() + ", " + e.gety() + "]" ); public static void main( String args[] ) MouseTracker app = new MouseTracker(); app.addwindowlistener( new WindowAdapter() public void windowclosing( WindowEvent e ) System.exit( 0 ); );

Adapter Classes Interfaces with many methods to implement can be cumbersome The adapter class provides a default implementation of all interface methods Application can over-ride interface methods that are of interest

// Fig. 12.19: Painter.java // Using class MouseMotionAdapter. import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Painter extends JFrame private int xvalue = -10, yvalue = -10; public Painter() super( "A simple paint program" ); getcontentpane().add( new Label( "Drag the mouse to draw" ), BorderLayout.SOUTH ); addmousemotionlistener( new MouseMotionAdapter() public void mousedragged( MouseEvent e ) xvalue = e.getx(); yvalue = e.gety(); repaint(); ); setsize( 300, 150 ); show(); Inner Class

public void paint( Graphics g ) g.filloval( xvalue, yvalue, 4, 4 ); public static void main( String args[] ) Painter app = new Painter(); app.addwindowlistener( new WindowAdapter() public void windowclosing( WindowEvent e ) System.exit( 0 ); );