Java GUI Programming



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

Swing. A Quick Tutorial on Programming Swing Applications

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

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

GUI Components: Part 2

Mouse Event Handling (cont.)

CS 335 Lecture 06 Java Programming GUI and Swing

Graphical User Interfaces

Programming with Java GUI components

JIDE Action Framework Developer Guide

JIDE Common Layer Developer Guide (Open Source Project)

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

Software Design: Figures

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

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

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

Using A Frame for Output

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

How to Convert an Application into an Applet.

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

Mapping to the Windows Presentation Framework

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

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

Skills and Topics for TeenCoder: Java Programming

Karsten Lentzsch JGoodies SWING WITH STYLE

How to create buttons and navigation bars

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

Simple Line Drawing. Description of the Simple Line Drawing program

Interactive Programs and Graphics in Java


Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

How to create pop-up menus

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

Advanced Network Programming Lab using Java. Angelos Stavrou

If you know exactly how you want your business forms to look and don t mind detail

DIA Creating Charts and Diagrams

Create a Poster Using Publisher

If you know exactly how you want your business forms to look and don t mind

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

Artificial Intelligence. Class: 3 rd

Joomla Article Advanced Topics: Table Layouts

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

In this session, we will explain some of the basics of word processing. 1. Start Microsoft Word 11. Edit the Document cut & move

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

Instructions for Creating a Poster for Arts and Humanities Research Day Using PowerPoint

Assignment # 2: Design Patterns and GUIs

Lession: 2 Animation Tool: Synfig Card or Page based Icon and Event based Time based Pencil: Synfig Studio: Getting Started: Toolbox Canvas Panels

Homework/Program #5 Solutions

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

JIDE Docking Framework Developer Guide

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

Tutorials. If you have any questions, comments, or suggestions about these lessons, don't hesitate to contact us at

Ad Hoc Reporting. Usage and Customization

Microsoft Word defaults to left justified (aligned) paragraphs. This means that new lines automatically line up with the left margin.

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

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

Tutorial Reference Manual. Java WireFusion 4.1

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

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

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

Creating Fill-able Forms using Acrobat 8.0: Part 1

CaptainCasa. CaptainCasa Enterprise Client. CaptainCasa Enterprise Client. Feature Overview

Using Adobe Dreamweaver CS4 (10.0)

Essentials of the Java Programming Language

Using Microsoft Word. Working With Objects

Google Sites: Site Creation and Home Page Design

Introduction to Microsoft Word 2008

Welcome to CorelDRAW, a comprehensive vector-based drawing and graphic-design program for the graphics professional.

How to Use the Drawing Toolbar in Microsoft Word

The Basic Java Applet and JApplet

How Scala Improved Our Java

Creating Web Pages with Microsoft FrontPage

Tips for optimizing your publications for commercial printing

Create Charts in Excel

BHARATHIAR UNIVERSITY COIMBATORE SCHOOL OF DISTANCE EDUCATION

Inserting Graphics into Grant Applications & Other Word Documents

PDF Web Form. Projects 1

Microsoft Office 2010: Introductory Q&As PowerPoint Chapter 1

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

KaleidaGraph Quick Start Guide

Adobe InDesign Creative Cloud

Excel basics. Before you begin. What you'll learn. Requirements. Estimated time to complete:

Creating Interactive PDF Forms

ClarisWorks 5.0. Graphics

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

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

After you complete the survey, compare what you saw on the survey to the actual questions listed below:

Making Visio Diagrams Come Alive with Data

Data Visualization. Prepared by Francisco Olivera, Ph.D., Srikanth Koka Department of Civil Engineering Texas A&M University February 2004

Table of Contents. I. Banner Design Studio Overview II. Banner Creation Methods III. User Interface... 8

Excel 2007: Basics Learning Guide

Digital Signage with Apps

PowerPoint 2007 Basics Website:

A Guide to Microsoft Paint (Windows XP)

How To Change Your Site On Drupal Cloud On A Pcode On A Microsoft Powerstone On A Macbook Or Ipad (For Free) On A Freebie (For A Free Download) On An Ipad Or Ipa (For

Green = 0,255,0 (Target Color for E.L. Gray Construction) CIELAB RGB Simulation Result for E.L. Gray Match (43,215,35) Equal Luminance Gray for Green

Transcription:

Java GUI Programming Sean P. Strout (sps@cs.rit.edu) Robert Duncan (rwd@cs.rit.edu) 10/24/2005 Java GUI Programming 1 Java has standard packages for creating custom Graphical User Interfaces What is a GUI? Some of the fundamental GUI components: Button Label Text Field Check Box Radio Buttons Combo Box 10/24/2005 Java GUI Programming 2 1

import javax.swing.*; import java.awt.*; public class ShowComponents extends JFrame { public ShowComponents () { Container container = getcontentpane(); container.setlayout(new FlowLayout (FlowLayout.LEFT, 10, 20)); container.add(new JButton("OK")); container.add(new JLabel("Enter your name: ")); container.add(new JTextField("Type name here...")); container.add(new JCheckBox("Bold")); container.add(new JRadioButton("Red", true)); container.add(new JRadioButton("Green")); container.add(new JRadioButton("Blue")); container.add(new JComboBox(new String[]{"High", "Med", "Low"})); } // ShowComponents ShowComponents frame = new ShowComponents(); frame.settitle("gui Components"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setsize(650, 100); frame.setlocation(100, 100); frame.setvisible(true); } // ShowComponents ShowComponents.java 10/24/2005 Java GUI Programming 3 What is AWT? The Abstract Window Toolkit was a part of Java from the beginning import java.awt.*; All AWT components must be mapped to platform specific components using peers The look and feel of these components is tied to the native components of the window manager AWT components are considered to be very error prone and should not be used in modern Java applications 10/24/2005 Java GUI Programming 4 2

The same application using only AWT components, running on X-Windows: What is AWT? 10/24/2005 Java GUI Programming 5 import java.awt.*; public class AWTComponents extends Frame { public AWTComponents () { /* set up the window layout */ setlayout(new FlowLayout (FlowLayout.LEFT, 10, 20)); setlocation(100, 100); settitle("awt components"); resize(600, 125); AWTComponents.java /* button */ add(new Button("OK")); /* label */ add(new Label("Enter your name: ")); /* text field */ add(new TextField("Type name here...")); /* check box group */ CheckboxGroup cbg = new CheckboxGroup(); add(new Checkbox("Bold", cbg, false)); add(new Checkbox("Red", null, true)); add(new Checkbox("Green")); add(new Checkbox("Blue")); 10/24/2005 Java GUI Programming 6 3

/* Must put priorities in a menu bar */ MenuBar mb = new MenuBar(); Menu fileb = new Menu("Priority"); mb.add(fileb); MenuItem highb = new MenuItem("High"); MenuItem medb = new MenuItem("Medium"); MenuItem lowb = new MenuItem("Low"); fileb.add(highb); fileb.add(medb); fileb.add(lowb); setmenubar(mb); AWTComponents.java - continued /* show the window */ setvisible(true); } // AWTComponents new AWTComponents(); } // AWTComponents 10/24/2005 Java GUI Programming 7 With the release of Java 2, the AWT user interface components were replaced with Swing What is Swing? Swing is built on top of AWT to give a more flexible, robust library Lightweight components don t rely on the native GUI Heavyweight components do depend on the target platform because they extend AWT components Swing components are directly painted onto the canvas using Java code 10/24/2005 Java GUI Programming 8 4

Java GUI API Dimension AWT: java.awt Font FontMetrics Heavweight Object Color Graphics LayoutManager Panel Applet JApplet Component Container Window Frame JFrame Dialog JDialog JComponent Swing: javax.swing Lightweight 10/24/2005 Java GUI Programming 9 Java GUI API AbstractButton JMenuItem JButton JCheckBoxMenuItem JMenu JComponent JToggleButton JRadioButtonMenuItem JTextComponent JEditorPane JTextField JTextArea JCheckBox JRadioButton JPasswordField JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip JTree JTable JTableHeader JInternalFrame JProgressBar JSpinner 10/24/2005 Java GUI Programming 10 5

Container Classes Container classes are GUI components that are used as containers to contain other GUI components For Swing use: Component, Container, JFrame, JDialog, JApplet, Jpanel JFrame is a window not contained inside another window JDialog is a temporary popup window or message box JApplet is an applet that can run in a web browser JPanel is an invisible, nest-able container used to hold UI components or canvases to draw graphics A layout manager is used to position and place components in a container 10/24/2005 Java GUI Programming 11 You need a frame to hold the UI components (100, 100) Title bar Frames Content pane 300 pixels high 400 pixels wide 10/24/2005 Java GUI Programming 12 6

MyFrame.java import javax.swing.*; public class MyFrame { // Create frame with the title "MyFrame" JFrame frame = new JFrame("MyFrame"); // Set the size of the frame to width=400, height=300. // If this is not set, it will just be the size of the title bar frame.setsize(400, 300); // The frame is not displayed until this statement frame.setvisible(true); // The location of the frame on the screen. The upper-left corner is 0,0 frame.setlocation(100, 100); // Tell the program to terminate when the frame is closed. // If this is not used, the program does not terminate and // it must be stopped manually (CTRL-Z then 'kill %' ) frame.setdefaultcloseoperation(jframe.exit_on_close); } // MyFrame 10/24/2005 Java GUI Programming 13 Content Pane Layered pane Glass pane Menu bar Content pane The content pane is the part of the frame where the UI components will be placed It is a java.awt.container object 10/24/2005 Java GUI Programming 14 7

Adding Components to a Frame UI components can be add ed to the content pane after they are created Here, the OK button is centered in the frame and occupies the whole frame, no matter how it is resized 10/24/2005 Java GUI Programming 15 import javax.swing.*; // JFrame import java.awt.*; // Container public class MyFrameWithButton { JFrame frame = new JFrame("Frame with components"); // Get the content pane, which was made when the // frame was created. Container container = frame.getcontentpane(); // Create an "OK" button JButton okbutton = new JButton("OK"); // Add the button into the frame via the content pane container.add(okbutton); // Set up the frame behavior frame.setsize(400, 300); frame.setlocation(100, 100); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); } // MyFrameWithButton MyFrameWithButton.java 10/24/2005 Java GUI Programming 16 8

Layout Managers There are three basic layout managers which control how UI components are organized on the frame FlowLayout GridLayout BorderLayout Once created, the layout can be set in the content pane using setlayout As the window is resized, the UI components reorganize themselves based on the rules of the layout 10/24/2005 Java GUI Programming 17 Extending JFrame public class GUIMain extends JFrame { // construct GUI interface with components public GUIMain() { // set the layout manager Container container = getcontentpane(); container.setlayout( ); // create UI components and add container.add( ) } // GUIMain // create instance of GUIMain and set // frame behaviors GUIMain frame = new GUIMain(); frame.settitle( ); } // GUIMain 10/24/2005 Java GUI Programming 18 9

FlowLayout With flow layout, the components arrange themselves from left to right in the order they were added Rows/buttons are left aligned using FlowLayout.LEFT Horizontal gap of 10 pixels Vertical gap of 20 pixels 10/24/2005 Java GUI Programming 19 ShowFlowLayout.java public class ShowFlowLayout extends JFrame { // Constructor places components in the frame public ShowFlowLayout() { // Get the content pane from the frame Container container = getcontentpane(); // Set FlowLayout, aligned left with a horizontal // gap 10 and vertical gap 20 between components container.setlayout(new FlowLayout(FlowLayout.LEFT, 10, 20)); // Add 10 buttons into the frame for (int i=0; i<10; i++) { container.add(new JButton("Component " + i)); } } // ShowFlowLayout ShowFlowLayout frame = new ShowFlowLayout(); frame.settitle("showflowlayout"); frame.setsize(600, 200); frame.setlocation(100, 100); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); } // ShowFlowLayout 10/24/2005 Java GUI Programming 20 10

GridLayout With grid layout, the components arrange themselves in a matrix formation (rows, columns) Either the row or column must be non-zero The non-zero dimension is fixed and the zero dimension is determined dynamically The dominating parameter is the rows 10/24/2005 Java GUI Programming 21 2,4 GridLayout 0,4 10, 10 4,4 10/24/2005 Java GUI Programming 22 11

ShowGridLayout.java public class ShowGridLayout extends JFrame { public ShowGridLayout(int rows, int cols) { // Get the content pane of the frame Container container = getcontentpane(); // Set the grid layout based on user input for // the rows and columns. The gaps are 5 pixels container.setlayout(new GridLayout(rows, cols, 5, 5)); // Add 10 buttons to the frame for (int i=0; i<10; i++) { container.add(new JButton("Component " + i)); } } // ShowGridLayout if (args.length!= 2) { System.err.println("Usage: java ShowGridLayout rows cols"); System.exit(-1); } int rows = Integer.parseInt(args[0]); int cols = Integer.parseInt(args[1]); ShowGridLayout frame = new ShowGridLayout(rows, cols); frame.settitle("showgridlayout"); frame.setsize(600, 200); frame.setlocation(100, 100); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); } // ShowGridLayout 10/24/2005 Java GUI Programming 23 BorderLayout With border layout, the window is divided into five areas: BorderLayout.NORTH BorderLayout.WEST BorderLayout.CENTER BorderLayout.EAST BorderLayout.SOUTH Components are added to the frame using a specified index: container.add(new JButton( East ), BorderLayout.EAST); 10/24/2005 Java GUI Programming 24 12

BorderLayout 10/24/2005 Java GUI Programming 25 ShowBorderLayout.java public class ShowBorderLayout extends JFrame { public ShowBorderLayout() { // Get the content pane of the frame Container container = getcontentpane(); // Set the border layout with horizontal gap 5 // and vertical gap 10 container.setlayout(new BorderLayout(5, 10)); // Add buttons to the frame container.add(new JButton("East"), BorderLayout.EAST); container.add(new JButton("South"), BorderLayout.SOUTH); container.add(new JButton("West"), BorderLayout.WEST); container.add(new JButton("North"), BorderLayout.NORTH); container.add(new JButton("Center"), BorderLayout.CENTER); } // ShowBorderLayout ShowBorderLayout frame = new ShowBorderLayout(); frame.settitle("showborderlayout"); frame.setsize(600, 200); frame.setlocation(100, 100); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); } // ShowBorderLayout 10/24/2005 Java GUI Programming 26 13

BorderLayout The window stretches for each component: North and South stretch horizontally East and West stretch vertically Center can stretch in both directions to fill space The default location for a component is BorderLayout.CENTER If you add two components to the same location, only the last one will be displayed It is unnecessary to place components to occupy all areas 10/24/2005 Java GUI Programming 27 The color of GUI components can be set using the java.awt.color class Color Colors are made of red, green and blue components which range from 0 (darkest shade) to 255 (lightest shade) Each UI component has a background and foreground: Color color = new Color(128, 0, 0); JButton button = new JButton(); button.setbackground(color); // red button.setforeground(new Color(0, 0, 128)); // blue 10/24/2005 Java GUI Programming 28 14

There are 13 constant colors defined in Color: BLACK, BLUE, CYAN, DARK_GRAY, GRAY, GREEN, LIGHT_GRAY, MAGENTA, ORANGE, PINK, RED, WHITE, YELLOW Color 10/24/2005 Java GUI Programming 29 public class ColorButtons extends JFrame { // Constructor places components in the frame public ColorButtons() { // Get the content pane from the frame Container container = getcontentpane(); // Set FlowLayout, aligned left with a horizontal // gap 10 and vertical gap 20 between components container.setlayout(new FlowLayout(FlowLayout.LEFT, 10, 20)); ColorButtons.java Color colors[] = new Color [10]; colors[0] = Color.RED; colors[1] = Color.BLUE; colors[2] = Color.CYAN; colors[3] = Color.GRAY; colors[4] = Color.GREEN; colors[5] = Color.MAGENTA; colors[6] = Color.ORANGE; colors[7] = Color.PINK; colors[8] = Color.YELLOW; colors[9] = Color.DARK_GRAY; 10/24/2005 Java GUI Programming 30 15

// Add 10 buttons into the frame for (int i=0; i<10; i++) { JButton button = new JButton("Component " + i); button.setforeground(colors[i]); button.setbackground(colors[9-i]); container.add(button); } } // ColorButtons ColorButtons.java ColorButtons frame = new ColorButtons(); frame.settitle("colorbuttons"); frame.setsize(600, 200); frame.setlocation(100, 100); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); } // ColorButtons 10/24/2005 Java GUI Programming 31 Write a program to organize the components for a microwave oven: Panels text field button 12 buttons The problem is we want to use different layouts for different components 10/24/2005 Java GUI Programming 32 16

The window can be subdivided into different panels Panels The panels act as sub-containers for grouping UI components The content pane uses a border layout: Panel2: East Button: Center button text field 12 buttons Panel 2 uses a border layout: text: North Panel 1: Center Panel 1 uses a grid layout 10/24/2005 Java GUI Programming 33 import java.awt.*; import javax.swing.*; public class MicrowaveUI extends JFrame { public MicrowaveUI() { // Get the content pane of the frame Container container = getcontentpane(); // Set the border layout for the frame container.setlayout(new BorderLayout()); // Create panel1 for the button and // use a grid layout JPanel panel1 = new JPanel(); panel1.setlayout(new GridLayout(4, 3)); // Add buttons to the panel for (int i=1; i<10; i++) { JButton button = new JButton("" + i); button.setforeground(color.white); button.setbackground(color.black); panel1.add(button); } MicrowaveUI.java 10/24/2005 Java GUI Programming 34 17

MicrowaveUI.java JButton button = new JButton("0"); button.setforeground(color.white); button.setbackground(color.black); panel1.add(button); button = new JButton("Start"); button.setforeground(color.white); button.setbackground(color.black); panel1.add(button); button = new JButton("Stop"); button.setforeground(color.white); button.setbackground(color.black); panel1.add(button); // Create panel2 to hold a text field and panel1 JPanel panel2 = new JPanel(new BorderLayout()); JTextField textfield = new JTextField("Time to be displayed here..."); textfield.setforeground(color.white); textfield.setbackground(color.black); panel2.add(textfield,borderlayout.north); panel2.add(panel1, BorderLayout.CENTER); // Add panel2 and a button to the frame container.add(panel2, BorderLayout.EAST); button = new JButton("Food to be placed here"); button.setforeground(color.red); button.setbackground(color.black); container.add(button, BorderLayout.CENTER); } // MicrowaveUI 10/24/2005 Java GUI Programming 35 MicrowaveUI frame = new MicrowaveUI(); frame.settitle("zap It!"); frame.setsize(400, 250); frame.setlocation(100, 100); frame.setvisible(true); frame.setdefaultcloseoperation(jframe.exit_on_close); } // MicrowaveUI MicrowaveUI.java 10/24/2005 Java GUI Programming 36 18

Graphics can be drawn using a class which extends JPanel Graphics Swing will call the paintcomponent method to draw: protected void paintcomponent(graphics g); There are a variety of drawing methods: drawline(int x1, int y1, int x2, int y2); drawrect(int x, int y, int w, int h); drawoval(int x, int y, int w, int h); drawpolygon(int[] xpoints, int[] ypoints, int npoints); 10/24/2005 Java GUI Programming 37 Graphics line filled oval filled arc filled rectangle unfilled rectangle filled polygon unfilled oval unfilled arc 10/24/2005 Java GUI Programming 38 19