Using A Frame for Output



Similar documents
CS 335 Lecture 06 Java Programming GUI and Swing

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

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

Programming with Java GUI components

Homework/Program #5 Solutions

GUI Components: Part 2

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

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

Mouse Event Handling (cont.)

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

Graphical User Interfaces

Remote Method Invocation

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

How to Convert an Application into an Applet.

JiST Graphical User Interface Event Viewer. Mark Fong

Skills and Topics for TeenCoder: Java Programming

core 2 Handling Mouse and Keyboard Events

How Scala Improved Our Java

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

Tema: Encriptación por Transposición


Advanced Network Programming Lab using Java. Angelos Stavrou

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

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

GUI Event-Driven Programming

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

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

Extending Desktop Applications to the Web

The Basic Java Applet and JApplet

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

Java Appletek II. Applet GUI

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

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

Assignment # 2: Design Patterns and GUIs

Event-Driven Programming

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

Java Mouse and Keyboard Methods

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

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

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

Essentials of the Java Programming Language

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

Artificial Intelligence. Class: 3 rd

Tutorial Reference Manual. Java WireFusion 4.1

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

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

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

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

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

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

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

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

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

Developing GUI Applications: Architectural Patterns Revisited

Konzepte objektorientierter Programmierung

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

Lösningsförslag till tentamen

Syllabus for CS 134 Java Programming

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

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

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

CODE WIDTH HEIGHT ARCHIVE ALIGN VSPACE, HSPACE ALT APPLET APPLET ALIGN IMG

Analysis Of Source Lines Of Code(SLOC) Metric

Model-View-Controller (MVC) Design Pattern

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

Karsten Lentzsch JGoodies SWING WITH STYLE

public class demo1swing extends JFrame implements ActionListener{

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

CS506 Web Design and Development Solved Online Quiz No. 01

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

There are some important differences between an applet and a standalone Java application, including the following:

Part IV: Java Database Programming

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

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

Object-Oriented Programming and Data Structures

Software Design: Figures

HTML Form Widgets. Review: HTML Forms. Review: CGI Programs

Event processing in Java: what happens when you click?

OBJECT ORIENTED PROGRAMMING IN JAVA EXERCISES

Introduction to the Java Programming Language

JIDE Action Framework Developer Guide

Altas, Bajas y Modificaciones de Registros en tabla MYSQL

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

Summer Internship 2013

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

Java GUI Programming

TATJA: A Test Automation Tool for Java Applets

Lab 7 Keyboard Event Handling Mouse Event Handling

An Overview of Java. overview-1

Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months

Transcription:

Eventos Roteiro Frames Formatting Output Event Handling Entering Data Using Fields in a Frame Creating a Data Entry Field Using a Field Reading Data in an Event Handler Handling Multiple Button Events

Using A Frame for Output Import classes and declare fields Instantiate frame objects and specify some properties Put display objects into the frame Make the frame visible on the screen Import Classes & Declare Fields Import package containing the JFrame class import javax.swing.*; Declare a variable of class JFrame JFrame outframe; Declare a variable of the class Container Container outpane;

Instantiate Frame Object and Specify Properties Instantiate a JFrame object outframe = new JFrame(); Get a content pane object and assign its address to Container variable outpane = outframe.getcontentpane(); Specify action on window closing outframe.setdefaultcloseoperation( JFrame.EXIT_ON_CLOSE); Specify size of JFrame object in terms of pixels (the individual dots that make up an image on the screen) outframe.setsize(300,200);

Specify layout manager outpane.setlayout(new FlowLayout()); Layout manager A class that manages the placement of display elements within a content pane Add Output to Content Pane Container class A class into which you can add other elements A content pane is a container class Add a label to content pane outpane.add(new JLabel( Hi ));

Make Frame Visible outframe.setvisible(true); What happens if you call setvisible with false as the argument? Formatting output GridLayout is another layout manager GirdLayout allows you to specify how the objects are arranged in the pane outpane.setlayout(new GridLayout(5,2)); pane method layout rows columns object mgr.

Aligning of Text datapane.add(new Label( Name, JLabel.LEFT); datapane.add(new Label( Date, JLabel.CENTER); datapane.add(new Label( Time, JLabel.RIGHT); What are LEFT, RIGHT, and CENTER? Event-Driven Programming Event-driven programming The user s interaction with a GUI component is an event that can be processed by the program A GUI component (such as a button) is told where the event-handling method is defined that will be called when an event involving that component occurs Components are told by a method such as addactionlistener that takes the method name as an argument

Event Definitions Event An action, such as a mouse click, that takes place asynchronously with respect to the execution of the application Event handling The process of responding to events Event listener An object that contains event handler methods Event source An object that generates an event Event Definitions Continued Event handler A method that responds to an event; part of the event listener that is invoked by the event source object Firing an event An event source generates an event Registering a listener Adding an event listener to an event source s list of interested listeners Button A component that can be added to a frame that fires an event when the user clicks it

Processing an Action Event Button objects generate action events that can be processed by any ActionListener object Any class that implements interface ActionListener must provide a definition of method actionperformed Once an ActionListener object is registered to handle a button s action event, its method actionperformed is called automatically whenever that button s action event occurs Delegation Event Model Means the use of event listeners in event handling. The handling of an event is delegated to a particular object in the program When there are several buttons in an application, they can all have the same event handler, or they can have different event handlers If several buttons have the same event handler, you can use a selection statement in method actionperformed to determine which button fired an event

Button, Button, Who has the Button... Declare a variable of the JButton class JButton done; Instantiate a JButton object and assign its address to the variable done = new JButton( Enter ); // Word Enter appears on the button Add the object to the frame s content pane outpane.add(done); Button Event Listeners A listener is a class that implements the ActionListener interface private static class Handler implements ActionListener The class must contain a method with this heading public void actionperformed(actionevent event) { // code to handle the event only thing that can change is the parameter name

Registering the Listener Registering the Listener Letting the event source (the button) know that the code to handle the event is in the listener Declare a variable of the listener class Handler buttonhandler; Instantiate an object of the listener class buttonhandler = new Handler(); Register the listener with the button done.addactionlistener(buttonhandler); Tasks of a Listener Listeners are invoked automatically when the event for which they are listening occurs A button is pressed and the listener for the button jumps into action Possible tasks completed in the listener input data update data report on some internal action

Entering Data Field A component of a frame in which the user can type a value; the user must first place the cursor in the field by clicking inside the field Dialog Technique where the user enters data in a field and lets the program know the data is ready to be read by a separate action such as clicking a button Creating a Data Entry Field Declare a variable of the appropriate field class JTextField infield; Instantiate an object of the class infield = new JTextField(6); or infield = new JTextField( Hello!, 6) Add the objet to the content pane outpane.add(infield);

Reading in a Listener // When the Enter button is pressed this listener // jumps into action private static class Handler implements ActionListener { public void actionperformed(actionevent anevent) { String inline; inline = infield.gettext(); System.out.println(inLine); What Enter button? Where is infield declared? Organization of Event Application public class CopyString { public static class Handler { public void actionperformed( ){ private static JTextField infield; public static void main(string[] args) { JButton done;... application class listener class declare and instantiate other components handler method declare components used in Handler

Exemplo 1 - ActionListner Prof. Aruquia Entradas de dados Botoes Check-box Radio import javax.swing.*; import java.awt.event.*; import java.awt.dimension; import java.awt.container; public class AppletActionListener extends JApplet implements ActionListener { JButton botao1, botao2; JPanel grupobotao12; JComboBox botaodeselecao; String[] botaodeselecaostring={"primeiro","segundo","terceiro"; JRadioButton opcao1, opcao2, opcao3, opcao4; ButtonGroup grupobotao; JPanel grupobotaopanel; JLabel titulo; JTextField campodetexto; JTextArea areadetexto; JPanel grupotexto; Panel p; Container cp;

public void init() { //botoes botao1 = new JButton("botao 1"); botao1.addactionlistener(this); botao2 = new JButton("botao 2"); botao2.addactionlistener(this); grupobotao12 = new JPanel(); grupobotao12.add(botao1); grupobotao12.add(botao2); //botao de selecao botaodeselecao = new JComboBox(botaoDeSelecaoString); botaodeselecao.addactionlistener(this); //botao de opcao grupobotao = new ButtonGroup(); grupobotaopanel = new JPanel(); opcao1 = new JRadioButton("Opcao 1"); opcao2 = new JRadioButton("Opcao 2"); opcao3 = new JRadioButton("Opcao 3"); opcao4 = new JRadioButton("Opcao 4"); grupobotao.add(opcao1); grupobotao.add(opcao2); grupobotao.add(opcao3); grupobotao.add(opcao4); opcao1.addactionlistener(this); opcao2.addactionlistener(this); opcao3.addactionlistener(this); opcao4.addactionlistener(this); grupobotaopanel.add(opcao1); grupobotaopanel.add(opcao2); grupobotaopanel.add(opcao3); grupobotaopanel.add(opcao4);

//Cria um painel agrupando um Label e um Campo de Texto titulo = new JLabel(" Entre com um texto "); campodetexto = new JTextField(20); grupotexto = new JPanel(); campodetexto.addactionlistener(this); grupotexto.add(titulo); grupotexto.add(campodetexto); //Content Pane cp = getcontentpane(); p = new Panel (); areadetexto = new JTextArea(); areadetexto.seteditable(false); JScrollPane scrollpane = new JScrollPane(areaDeTexto, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_S CROLLBAR_AS_NEEDED); scrollpane.setpreferredsize(new Dimension(300, 150)); p.add(grupobotao12); p.add(botaodeselecao); p.add(grupobotaopanel); p.add(grupotexto); p.add(scrollpane); cp.add(p); //Este metodo responde as acoes dos componentes public void actionperformed(actionevent e) { if(e.getsource() instanceof JButton) { areadetexto.append("um botao foi apertado \n"); if(e.getsource()==botao1) { areadetexto.append("o botao 1 foi apertado \n"); else { areadetexto.append("o botao 2 foi apertado \n"); if(e.getsource() instanceof JTextField) { areadetexto.append("o texto digitado foi " + campodetexto.gettext() + " \n"); class Panel extends JPanel { public void paintcomponent (java.awt.graphics g) { super.paintcomponent(g);

if(e.getsource() instanceof JComboBox) { areadetexto.append("o botao de selecao escolhido foi o " + botaodeselecao.getselecteditem() + " \n"); if(e.getsource() instanceof JRadioButton) { if(opcao1.isselected()) { areadetexto.append("o botao de opcao foi acionado \n"); areadetexto.append("a opcao escolhida foi a opcao1 \n"); if(opcao2.isselected()) { areadetexto.append("o botao de opcao foi acionado \n"); areadetexto.append("a opcao escolhida foi a opcao2 \n"); if(opcao3.isselected()) { areadetexto.append("o botao de opcao foi acionado \n"); areadetexto.append("a opcao escolhida foi a opcao3 \n"); if(opcao4.isselected()) { areadetexto.append("o botao de opcao foi acionado \n"); areadetexto.append("a opcao escolhida foi a opcao4 \n"); Exemplo 2 (prof. Aruquia) Prof. Aruquia Ações de mouse Clic Arrasto Movimento

import javax.swing.*; import java.awt.color; import java.awt.dimension; import java.awt.insets; import java.awt.gridbaglayout; import java.awt.gridbagconstraints; import java.awt.event.mousemotionlistener; import java.awt.event.mouselistener; import java.awt.event.mouseevent; public class MouseMotionEventDemoV2 extends JApplet implements MouseMotionListener, MouseListener { BlankArea areamouse; JTextArea areatexto; public void init() { JPanel contentpane = new JPanel(); GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(); contentpane.setlayout(gridbag); //Define como redimensionar c.fill = GridBagConstraints.BOTH; c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 1.0; c.weighty = 1.0; //Espaco entre a areamouse e as bordas do applet e da areatexto c.insets = new Insets(0, 0, 0, 0); areamouse = new BlankArea(new Color(0.98f, 0.97f, 0.85f)); gridbag.setconstraints(areamouse, c); contentpane.add(areamouse); //Espaco entre a areatexto e as bordas do applet e da areamouse c.insets = new Insets(3, 6, 9, 12); areatexto = new JTextArea(); areatexto.seteditable(false); JScrollPane scrollpane = new JScrollPane(areaTexto, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); scrollpane.setpreferredsize(new Dimension(200, 75)); gridbag.setconstraints(scrollpane, c); contentpane.add(scrollpane);

//Registro para eventos do mouse na areamouse. areamouse.addmousemotionlistener(this); areamouse.addmouselistener(this); addmousemotionlistener(this); addmouselistener(this); setcontentpane(contentpane); //interface MouseListener public void mouseentered(mouseevent e) { escreve("mouse entrou", e); //interface MouseListener public void mouseexited(mouseevent e) { escreve("mouse saiu", e); //interface MouseListener public void mouseclicked(mouseevent e) { escreve("mouse clicado", e); //interface MouseListener public void mousepressed(mouseevent e) { escreve("mouse pressinado", e); //interface MouseListener public void mousereleased(mouseevent e) { escreve("mouse solto", e); //interface MouseMotionListener public void mousedragged(mouseevent e) { escreve("mouse arrastado", e); //interface MouseMotionListener public void mousemoved(mouseevent e) { escreve("mouse movido", e); void escreve(string eventdescription, MouseEvent e) { areatexto.append(eventdescription + " (" + e.getx() + "," + e.gety() + ")" + " detected on " + e.getcomponent().getclass().getname() + "\n");

What happens next? After a value has been input from a JTextField, the application waits for another value to be input and waits for another value to be input Creating an event loop The application is halted by closing the window adding another button to signal the end Review of GUI Components JFrame A kind of window in which components can be placed Container A pane in the frame into which objects can be placed JLabel A component where text can be displayed JButton A component that generates an event when the user clicks on it with the mouse JTextField A component in which the user can type a value; the user must first place the cursor in the field by clicking inside the field

Graphical User Interfaces GUIs are built from GUI components (also called widgets for window gadgets) GUI component classes are part of java.awt (Abstract Windowing Toolkit package) and javax.swing GUIs are event-driven; they generate events when the user interacts with the GUI An event is an action such as clicking the mouse, clicking a button, that takes place asynchronously (not at a particular time) with respect to the execution of the program 2 Steps for processing an event Register an event listener object to listen for specific types of events Implement event handler method(s) within listener to be called automatically in response to a particular type of event A class that implements an event listener interface must provide a definition for every method of that interface