Swing. A Quick Tutorial on Programming Swing Applications



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

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

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

CS 335 Lecture 06 Java Programming GUI and Swing

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


Using A Frame for Output

GUI Event-Driven Programming

Artificial Intelligence. Class: 3 rd

Programming with Java GUI components

Extending Desktop Applications to the Web

Developing GUI Applications: Architectural Patterns Revisited

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Homework/Program #5 Solutions

JIDE Common Layer Developer Guide (Open Source Project)

Java GUI Programming

Assignment # 2: Design Patterns and GUIs

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

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

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

JiST Graphical User Interface Event Viewer. Mark Fong

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

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

GUI Components: Part 2

Tutorial Reference Manual. Java WireFusion 4.1

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

Mapping to the Windows Presentation Framework

Karsten Lentzsch JGoodies SWING WITH STYLE

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

Advanced Network Programming Lab using Java. Angelos Stavrou

Skills and Topics for TeenCoder: Java Programming

JIDE Action Framework Developer Guide

How to Develop Accessible Linux Applications

LAYOUT MANAGERS. Layout Managers Page 1. java.lang.object. java.awt.component. java.awt.container. java.awt.window. java.awt.panel

Graphical User Interfaces

core 2 Handling Mouse and Keyboard Events

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

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

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

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

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

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

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

Design. in NetBeans 6.0

For Introduction to Java Programming, 5E By Y. Daniel Liang

Event processing in Java: what happens when you click?

How Scala Improved Our Java

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

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

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

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

Swing Data Validation. Karsten Lentzsch

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

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

Model-View-Controller (MVC) Design Pattern

Mouse Event Handling (cont.)

java.applet Reference

Editors Comparison (NetBeans IDE, Eclipse, IntelliJ IDEA)

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

BHARATHIAR UNIVERSITY COIMBATORE SCHOOL OF DISTANCE EDUCATION

TATJA: A Test Automation Tool for Java Applets

How to Convert an Application into an Applet.

An Overview of Java. overview-1

Creating Carbon Menus. (Legacy)

Software Application & Operating Systems Checklist

Acrobat X Pro Accessible Forms and Interactive Documents

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

How To Program In Java (Ipt) With A Bean And An Animated Object In A Powerpoint (For A Powerbook)

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

A TOOL FOR DATA STRUCTURE VISUALIZATION AND USER-DEFINED ALGORITHM ANIMATION

JIDE Docking Framework Developer Guide

8 CREATING FORM WITH FORM WIZARD AND FORM DESIGNER

File Management With Windows Explorer

Generating Automated Test Scripts for AltioLive using QF Test

Macros in Word & Excel

Essentials of the Java Programming Language

NASA Workflow Tool. User Guide. September 29, 2010

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

Application Development, Java / JEE

Konzepte objektorientierter Programmierung

Mobile App Design and Development

Adobe Acrobat: Creating Interactive Forms

NovaBACKUP Network User s Guide

Study of Development of Java Applications in Eclipse Environment and Development of Java Based Calendar Application with Notifications

Using Eclipse to Run Java Programs

Acrobat 9: Forms. 56 Pages. Acrobat 9: Forms v Windows

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

Database Forms and Reports Tutorial

SPSS: Getting Started. For Windows

Yosemite Server Backup User s Guide

Summer Internship 2013

Syllabus for CS 134 Java Programming

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

Module One: Getting Started Opening Outlook Setting Up Outlook for the First Time Understanding the Interface...

JustClust User Manual

Demo: Controlling.NET Windows Forms from a Java Application. Version 7.3

Transcription:

Swing A Quick Tutorial on Programming Swing Applications 1

MVC Model View Controller Swing is based on this design pattern It means separating the implementation of an application into layers or components: The Model - the data structure that represents something (like a customer info rec) The Controller - the user interface logic for manipulating it The View - the display of that data structure to the user. 2

What is Swing? A set of classes (part of JFC) that support platform independent GUI (Graphical User Interface) Successor to the original Java GUI classes (AWT) which didn t work very well (they had platform dependencies that really made it a difficult API to use) AWT wasn t very sexy 3

Swing Visible widgets - windows, buttons, combo boxes, trees, tables, checkboxes, text fields, menus, Containers of components applets, dialogs, windows and frames Supporting classes and utility methods 4

Some important Swing visible component classes JApplet ** JButton JCheckBox JColorChooser JComboBox JDialog ** JFileChooser JFormattedTextField JFrame ** JLabel JList JMenu JMenuBar JMenuItem JPanel JPasswordField JPopupMenu JProgressBar JRadioButton JScrollBar JSlider JSpinner JTable JTextArea JTextField JToggleButton JToolBar JTree JWindow ** ** means a top level containers 5

Using netbeans to create a JDialog 6

adding fields 7

8

my empty CustomerInfoDialog:JDialog 9

code created 10

To kill a zombie or running process in netbeans right click and choose: terminate 11

executing the class displays: 12

Editing a dialog 1 St select a layout manager for the dialog 13

select component edit properties 14

changing the layout manager 15

what layout manager should I use? Start with the absolute and then experiment when you feel comfortable (or hire a graphic artist and let them worry about it ;-). 16

Adding other components to the view - JTextFields 17

execute the class 18

Adding a combo box 19

edit the model property for the combo box type in state abbreviations separated by commas 20

21

preferred size property hor, vert 22

MVC Model View Controller Design Pattern 23

Design Patterns A design pattern is a way of designing code that benefits from experience of other developers see GoF (Gang of Four) on Patterns Design patterns are rules of thumb & best practices A GUI is based on many design patterns 3D Pliancy Feedback Icons Menus Pointing Mnemonics & Accelerators Many more A pattern usually has a name (and several aliases), a context, a problem it addresses, a description of the solution, hints of when to use it and when not to. See http://www.csc.calpoly.edu/~dbutler/tutorials/winter96/patterns/, http://choices.cs.uiuc.edu/sane/dpatterns.html#dp and http://www.stanford.edu/~borchers/hcipatterns 24

MVC Model View Controller pattern Swing components are designed as MVC components Model = data or object that is the to be visually represented View = one or more visual representations of that data/object Controller = code to manage input to the model 25

MVC Sun 2002 26

MVC in Swing Components The Swing component class is the view and controller A separate class is the model Most components come with a default model You can set the model to your own model for a control Several controls could share a model! 27

28

Creating icons using the blank icon to start with 29

Change the properties of the button to use you icon 30

Pushing the buttons changes the displayed prices. 31

A different and better layout 32

JFrame JButton JTree JTable JPasswordField JSlider JProgressBar JFileChooser 33

private javax.swing.jpasswordfield private javax.swing.jtree private javax.swing.jslider private javax.swing.jprogressbar private javax.swing.jtable private javax.swing.jbutton private javax.swing.jbutton private javax.swing.jfilechooser private javax.swing.jlabel jpasswordfield1; jtree1; jslider1; jprogressbar1; jtable1; jbutton2; jbutton1; jfilechooser1; jlabel1; 34

Swing based MenuLookDemo 35

TopLevelWindows.java 36

TopLevelWindows.java package SwingSamples; import javax.swing.*; public class TopLevelWindows { public static void main(string args[]) { JFrame myjframe = new JFrame("The JFrame"); myjframe.setsize(300,300); myjframe.setlocation(100,100); JWindow myjwindow = new JWindow(); myjwindow.setsize(300,300); myjwindow.setlocation(500, 100); myjframe.setvisible(true); myjwindow.setvisible(true); } } 37

Top Level Containers Must have a top level container in Swing You must add components to the associated content pane 38

ContentPaneExample.java package SwingSamples; import java.awt.*; import javax.swing.*; public class ContentPaneExample { public static void main(string args[]) { JFrame myjframe = new JFrame("JFrame"); myjframe.setlocation(100,100); Without the pack() With the pack() Container mycontentpane = myjframe.getcontentpane(); mycontentpane.setlayout(new FlowLayout()); mycontentpane.add(new JLabel("One")); mycontentpane.add(new JLabel("Two")); myjframe.pack(); //reformats the layout to the minimum size to fit everything myjframe.setvisible(true); } } 39

ContentPaneExample2.java package SwingSamples; import java.awt.*; import javax.swing.*; public class ContentPaneExample2 { public static void main(string args[]) { JFrame myjframe = new JFrame("JFrame"); myjframe.setlocation(100,100); Container mycontentpane = new JPanel(); mycontentpane.add(new JLabel("One")); mycontentpane.add(new JLabel("Two")); } } myjframe.setcontentpane(mycontentpane); myjframe.pack(); myjframe.setvisible(true); 40

Events Swing uses them to communicate between swing components. An event is just a method call on the receiving object by the sending object. The method passes the event object. addactionlistener(actionlistener listener); removeactionlistener(actionlistener listener); An object registers to receive events. The method that gets called is: actionperformed(actionevent e); 41

Events In Swing they are multicast 1 to many possible. Manes multiple method calls by the send basically. Order isn t defined, though. Events are immutable to the receiver. Events may be queued as in the keyboard event queue. Multiple events maybe compressed into one as in mouse movements. 42

Event Modifier Flags SHIFT_MASK CTRL_MASK META_MASK ALT_MASK BUTTON1_MASK BUTTON2_MASK BUTTON3_MASK Detect when certain keys are also pressed. int modifierflags = myevent.getmodifiers(); if ((modifierflags & InputEvent.CRTL_MASK)!=0) System.println.out( Pressing the contrl key ); 43

Event Types ComponentEvent //resized,moved, shown, hidden FocusEvent //gained, lost KeyEvent //typed, pressed, released MouseEvent //clicked, pressed, released, //entered, exited ContainerEvent //componentadded componentremoved ActionEvent //fired by: JButton, JChekBox, AdjustmentEvent //fired by: JScrollBar Many more. 44

Event Adapter Classes Map incoming events to a method to invoke on the model to achieve the function. Separates the View & Controller from the Model (MVC) Prebuilt adapter has stubbed out methods for events. You only implement the ones you are interested. You do this by extending the adapter and overiding the methods you need. Follows a general design pattern of called adapter. MouseAdapter, MouseInputAdapter, MouseMotionAdapter, KeyAdapter, ComponentAdapter, ContainerAdapter, DragSourceAdapter, DropTargetAdapter, FocusAdapter, WindowAdapter, 45

AWT Robot! Used to simulate keyboard and mouse programmatically. It places events in the native system queues for the platform you are on (not just the java queue). Used for recording and replaying activities in regression testing and other uses. 46

Multithreading and Swing Swing components always execute on a single thread within your application. Not the main thread of your application, either. Swing components are NOT multithread safe! This is done for speed but influences how you must design for them. We can ignore this for protoyping UIs but not for design of applications. 47

Swing Components 48

Sample dialog with a few controls. MySampleOfSwingControls1.java 49

JButton java.lang.object +--java.awt.component +--java.awt.container +--javax.swing.jcomponent +--javax.swing.abstractbutton +--javax.swing.jbutton 50

JButton Used for a command Push and shows a state change visually (pliancy) Has a name, label text, 51

Adding items to the List 52

Add items to the model for the list 53

Changing the border of a list box 54

A Titled Border for a List Box 55

List Box Selection Modes Single Multiple_Interval Single_Interval 56

Setting the Button group on a radio button 57

Setting the Mnemonics 58

Final Dialog Version 59

JComboBox Two styles in the app non-editable and editable If you use the editable type you should check the input of the user to make sure it is acceptable. You can change the style by changing the editable property. 60

Creating a JavaGUI -> SampleForms -> Application 61

Menu and Menu item hierarchy that defines the menus for the app 62

The default menus 63

64

Copy and paste a menu into the hierarchy 65

This shows 2 Edit menus 66