5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Similar documents
CS 335 Lecture 06 Java Programming GUI and Swing

Swing. A Quick Tutorial on Programming Swing Applications

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

Programming with Java GUI components

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


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

Using A Frame for Output

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

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

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

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

Homework/Program #5 Solutions

How Scala Improved Our Java

The Basic Java Applet and JApplet

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

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

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

Graphical User Interfaces

Extending Desktop Applications to the Web

Artificial Intelligence. Class: 3 rd

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

GUI Event-Driven Programming

How to Convert an Application into an Applet.

Essentials of the Java Programming Language

Advanced Network Programming Lab using Java. Angelos Stavrou

GUI Components: Part 2

Tutorial Reference Manual. Java WireFusion 4.1

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

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

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

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

Assignment # 2: Design Patterns and GUIs

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

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

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

Software Design: Figures

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

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

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

Mouse Event Handling (cont.)

Skills and Topics for TeenCoder: Java Programming

Developing GUI Applications: Architectural Patterns Revisited

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

Karsten Lentzsch JGoodies SWING WITH STYLE

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

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

JIDE Action Framework Developer Guide

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

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

public class demo1swing extends JFrame implements ActionListener{

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

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

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

Event processing in Java: what happens when you click?

Medientechnik. Übung MVC

Konzepte objektorientierter Programmierung

Analysis Of Source Lines Of Code(SLOC) Metric

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

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

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

Tema: Encriptación por Transposición

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

Java GUI Programming

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

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

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

Project Builder for Java. (Legacy)

Syllabus for CS 134 Java Programming

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

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

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

8 CREATING FORM WITH FORM WIZARD AND FORM DESIGNER

Maximizing the Use of Slide Masters to Make Global Changes in PowerPoint

Lecture VII JAVA SWING GUI TUTORIAL

JiST Graphical User Interface Event Viewer. Mark Fong

Model-View-Controller (MVC) Design Pattern

How to Develop Accessible Linux Applications

Java Appletek II. Applet GUI

Microsoft PowerPoint 2010 Computer Jeopardy Tutorial

Visual Basic Programming. An Introduction

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Object-Oriented Programming and Data Structures

Explore Oakville How To Perform a Search and Navigate a Map

Mapping to the Windows Presentation Framework

KaleidaGraph Quick Start Guide

Making Visio Diagrams Come Alive with Data

JIDE Common Layer Developer Guide (Open Source Project)

MATLAB. Creating Graphical User Interfaces Version 6. The Language of Technical Computing. Computation. Visualization. Programming

Lösningsförslag till tentamen

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

your provider for business web solutions Desktop-Feeling garantiert - Wie Ihre Web-Applikation alle Erwartungen erfüllt! Basel,

Windows Basics. Developed by: D. Cook

Fundamentals of Java Programming

Creating Fill-able Forms using Acrobat 8.0: Part 1

Managing Your Desktop with Exposé, Spaces, and Other Tools

Using Kid Pix Deluxe 3 (Windows)

Microsoft Office PowerPoint Identify components of the PowerPoint window. Tutorial 1 Creating a Presentation

Building Applications With DUIM

Microsoft Office PowerPoint Creating a new presentation from a design template. Creating a new presentation from a design template

Transcription:

AWT vs. Swing AWT (Abstract Window Toolkit; Package java.awt) Benutzt Steuerelemente des darunterliegenden Betriebssystems Native Code (direkt für die Maschine geschrieben, keine VM); schnell Aussehen (Look) hängt vom System ab: unterschiedliche Schriften, Portabilität eingeschränkt Swing (Package javax.swing; Teil der Java Foundation Classes) Swing-Klassen beginnen mit J : JButton, JLabel,... Vollständig in Java programmiert, eigener Look Baut auf AWT auf Verwendet ein Minimum an systemspezifischen Komponenten 410

GUI application program shows the user a graphical interface, which consists of graphical components: Windows Buttons Menus Text fields A user interacts with the application by: Clicking on a button to choose a program option Making a choice from a menu Entering text in a text field Dragging a scroll bar Clicking on a window's close button An action such as clicking on a button is called an event 411

Grafische Komponenten: Anzeigen von Text und Symbolen (JLabel) Auslösen von Aktionen (JButton, JMenu) Eingabe von Text (JTextField) Auswahl aus einer festen Menge von Optionen (JCheckBox); gegenseitig ausschließend (JRadioButton) Auswahl aus einer variablen Menge (JList) 412

Event-driven programming: A user interacts with a GUI application by causing events. The application must respond to events in the order they arrive. The picture shows this. Each time the user interacts with a component, an event is sent to the application. Different events are sent to different parts of the application. The application has to work correctly no matter what the user does. 413

Power of AWT/Swing: I just ask for button (or whatever) objects that do what I want. Somebody else (Swing) does all the real work. The buttons are components that can be added with minimum effort. This is similar to going to a hardware store to get components for your home improvement project. Most of the parts you need already exist. You just assemble them. 414

A GUI program consists of three types of software: Graphical components that make up the Graphical User Interface You get graphical components by constructing Swing objects Listener methods that receive the events and respond to them Listener methods and application methods are Java methods that you write Application methods that do useful work for the user Application methods are Java methods that you write 415

The Java AWT contains the fundamental classes used for constructing GUIs The JComponent class is derived from Container and is one of the base classes of Swing. The JFrame class is derived from the AWT Frame class. It is usually the main container for a GUI application. The JApplet class (derived from the AWT Applet class) is sometimes used for Web programming, but the Applet class is more frequently used. 416

There are more Swing classes than those shown. For example there are several button types derived from AbstractButton. 417

Swing Frames: Most GUI programs are created by extending the class JFrame which holds the basic GUI functionality. You extend this class by adding the functions your application needs. Graphical components must be placed inside a container. Visually, a container is a rectangular area of the monitor screen and its components are smaller areas within it. Our first GUI program does not have a listener nor any application code You can click on the frame and drag it around, you can minimize it, you can grab a border and resize it, and so on. All of this is built into the JFrame class (inherited from its ancestors). All you have to do is ask for a JFrame object in your program and you get all this. 418

import java.awt.*; import javax.swing.*; public class GUIDemo1 extends JFrame { GUIDemo1() { Container pane = getcontentpane(); JLabel label = new JLabel("Press [X] at top right corner to exit"); pane.add(label); public static void main (String[] args) { GUIDemo1 frm = new GUIDemo1(); frm.setsize(300, 100); frm.setvisible(true); 419

Buttons: Use new to construct a JButton object. Then, add the button to the frame's content pane (a container that represents the main rectangle of the frame). The add method of a content pane puts a JButton into the frame. To get a reference to the content pane, use the getcontentpane() method of the frame The JButton now will be displayed when the frame is displayed. Clicking on the button generates events, but so far the program does not respond to those events. 420

import java.awt.*; import javax.swing.*; public class ButtonDemo extends JFrame { JButton bchange; ButtonDemo() { Container pane = getcontentpane(); bchange = new JButton("Click Me!"); pane.add( bchange ); public static void main (String[] args) { ButtonDemo frm = new ButtonDemo(); frm.setsize(300, 100); frm.setvisible(true); 421

Layout manager: When you add() buttons (and other components) to a content pane, a layout manager automatically decides what size they will be and where they will go. This is convenient, because you can add components without worrying about the details. The layout manager is like a little artist inside the computer. You say what components you want and the layout manager lays them out in the picture. There are several kinds of layout managers. Each layout manager has a different style of positioning components. Usually there is a layout manager that will do the job you want. 422

Beispiel: GridLayout import java.awt.*; import javax.swing.*; public class LayoutManagerDemo extends JFrame { LayoutManagerDemo() { Container pane = getcontentpane(); setlayout(new GridLayout(3,2)); add(new JButton("1")); add(new JLabel("2")); add(new JButton("3")); add(new JLabel("4")); add(new JButton("5")); add(new JLabel("6")); public static void main (String[] args) { LayoutManagerDemo frm = new LayoutManagerDemo(); frm.setsize(200, 400); frm.setvisible(true); 423

Event listeners: When a GUI program is running, the user generates an event by interacting with a GUI component. For a program to respond to an event there must be an event listener object for it. When an event is generated by the GUI component, a method in the listener object is invoked to respond to the event. In order to respond to events, your program must: create an event listener object for the type of event register the listener object with the GUI component that generates the event 424

A WindowAdapter object is an event listener for window events. The class has listener methods for every frame event. Create a listener object: Extend WindowAdapter to create a child class For each type of event you need to respond to, override the corresponding method in WindowAdapter Use new to construct a listener object Register the listener with the frame object: Construct the frame object Use addwindowlistener() to register the listener with the frame Registering a listener with a frame means connecting the two objects so that events from one object (the frame) are sent to the other (the listener) 425

Class WindowAdapter 426

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ListenerDemo extends JFrame { JButton bchange; ListenerDemo() { Container pane = getcontentpane(); bchange = new JButton("Click Me!"); pane.add(bchange); public static void main (String[] args) { ListenerDemo frm = new ListenerDemo(); WindowQuitter wquit = new WindowQuitter(); frm.addwindowlistener(wquit); frm.setsize(300, 100); frm.setvisible(true); class WindowQuitter extends WindowAdapter { public void windowclosing(windowevent e) { System.exit(0); 427

Button listeners: Different from window events, there is no ButtonAdapter class used as a base class for button listener objects. You need to define the complete class of a button listener from scratch. A button listener class must implement the ActionListener interface, that contains the single method: public void actionperformed(actionevent evt); The ActionEvent parameter is an Event object that represents an event (a button click). It contains information that can be used in responding to the event. Since ActionListener is an interface, you use it with a class that will implement the actionperformed() method. 428

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ButtonDemo2 extends JFrame implements ActionListener { JButton bchange; public ButtonDemo2() { Container pane = getcontentpane(); pane.setlayout(new FlowLayout()); bchange = new JButton("Click Me!"); bchange.addactionlistener(this); pane.add(bchange); public void actionperformed(actionevent evt) { getcontentpane().setbackground(color.blue); repaint(); 429

public static void main (String[] args) { ButtonDemo2 frm = new ButtonDemo2(); WindowQuitter wquit = new WindowQuitter(); frm.addwindowlistener( wquit ); frm.setsize( 200, 150 ); frm.setvisible( true ); class WindowQuitter extends WindowAdapter { public void windowclosing( WindowEvent e ) { System.exit( 0 ); 430

Interface ActionListener 431

Two Buttons in one frame: A frame will hold two buttons, one labeled "Red" and the other "Green". The FlowLayout layout manager will be used so the buttons will be nicely positioned in the frame. When the button marked "Red" is clicked, the background will turn red When the button marked "Green" is clicked, the background will turn green 432

Problem: Event objects from both buttons are delivered to the same method We like the ActionEvent that is delivered to actionperformed() to say what should be done. Associate a different command with each button using setactioncommand(string command) Now each button sends its command (a String) as part of the ActionEvent when it is clicked. The actionperformed() method uses it to see what to do. 433

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class TwoButtons extends JFrame implements ActionListener { JButtonredButton; JButtongrnButton; public TwoButtons() { redbutton = new JButton("Red"); grnbutton = new JButton("Green"); redbutton.setactioncommand( "red" ); grnbutton.setactioncommand( "green" ); getcontentpane().setlayout( new FlowLayout() ); getcontentpane().add( redbutton ); getcontentpane().add( grnbutton ); redbutton.addactionlistener( this ); grnbutton.addactionlistener( this ); 434

public void actionperformed(actionevent evt) { if ( evt.getactioncommand().equals( "red" ) ) getcontentpane().setbackground( Color.red ); else getcontentpane().setbackground( Color.green ); repaint(); public static void main (String[] args) { TwoButtons demo = new TwoButtons() ; WindowQuitter wquit = new WindowQuitter(); demo.addwindowlistener( wquit ); demo.setsize( 200, 150 ); demo.setvisible( true ); class WindowQuitter extends WindowAdapter { public void windowclosing( WindowEvent e ) { System.exit( 0 ); 435

Bradley Kjell s Java interactive Tutorial http://www.gailer-net.de/tutorials/java/cs151java.html#64 A JTextField is a box that contains text. The user can type text into the box and the program can get it and then use it as data. The program can write the results of a calculation to a JTextField. Application: Fat calculator. Class JSlider Radio buttons 436