Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

Similar documents
Graphical Interfaces

Graphical Interfaces

Chapter 1 GUI Applications

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Introduction. Introduction

Java - Applets. public class Buttons extends Applet implements ActionListener

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

The AWT Event Model 9

CHAPTER 2. Java Overview

Programming Languages and Techniques (CIS120e)

A Simple Text Editor Application

Java. GUI building with the AWT

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

BM214E Object Oriented Programming Lecture 13

GUI in Java TalentHome Solutions

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

University of Cape Town ~ Department of Computer Science. Computer Science 1016S / 1011H ~ November Exam

Java Applets / Flash

OBJECT ORIENTED PROGRAMMING. Java GUI part 1 Loredana STANCIU Room B616

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

Java Help Files. by Peter Lavin. May 22, 2004

JAVA NOTES GRAPHICAL USER INTERFACES

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Packages: Putting Classes Together

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Window Interfaces Using Swing Objects

FORMAS DE IMPLEMENTAR LOS OYENTES. A).- El oyente en una clase independiente con el constructor con un argumento y usando el método getactioncommand.

IT101. File Input and Output

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

JAVA NOTES GRAPHICAL USER INTERFACES

MIT AITI Swing Event Model Lecture 17

Which of the following syntax used to attach an input stream to console?

Programming Language Concepts: Lecture 8

1 of :32:42

User interfaces and Swing

กล ม API ท ใช. Programming Graphical User Interface (GUI) Containers and Components 22/05/60

Window Interfaces Using Swing Objects

Class 16: The Swing Event Model

GUI Programming: Swing and Event Handling

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

Part 3: Graphical User Interface (GUI) & Java Applets

The AWT Component Library 10

What Is an Event? Some event handler. ActionEvent. actionperformed(actionevent e) { }

Frames, GUI and events. Introduction to Swing Structure of Frame based applications Graphical User Interface (GUI) Events and event handling

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Swing from A to Z Some Simple Components. Preface

Part I: Learn Common Graphics Components

G51PRG: Introduction to Programming Second semester Applets and graphics

10/11/18. Introduction Panel Class Window Class Dialog class FileDialog class Menu, MenuItem class

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

The Java Programming Language Basics. Identifiers, Keywords, and Types. Expressions and Flow Control. Object-Oriented Programming. Objects and Classes

Computer Programming Java AWT Lab 18

Graphic User Interfaces. - GUI concepts - Swing - AWT

Introduction to the JAVA UI classes Advanced HCI IAT351

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

Java Programming Lecture 6

Introduction. Overview of the Course on Java. Overview of Part 1 of the Course

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

DEMYSTIFYING PROGRAMMING: CHAPTER SIX METHODS (TOC DETAILED) CHAPTER SIX: METHODS 1

Starting Out with Java: From Control Structures Through Objects Sixth Edition

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

Overloading Example. Overloading. When to Overload. Overloading Example (cont'd) (class Point continued.)

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

(Incomplete) History of GUIs

Java Swing. based on slides by: Walter Milner. Java Swing Walter Milner 2005: Slide 1

Input from Files. Buffered Reader

Functors - Objects That Act Like Functions

Question 1. Show the steps that are involved in sorting the string SORTME using the quicksort algorithm given below.

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

COMP-202: Foundations of Programming. Lecture 22: File I/O Jackie Cheung, Winter 2015

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

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

Contents Chapter 1 Introduction to Programming and the Java Language

Midterm assessment - MAKEUP Fall 2010

COMP-202: Foundations of Programming. Lecture 12: Linked List, and File I/O Sandeep Manjanna, Summer 2015

Agenda. Container and Component

Chapter 12 Advanced GUIs and Graphics

GUI Design. Overview of Part 1 of the Course. Overview of Java GUI Programming

EVENTS, EVENT SOURCES AND LISTENERS

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Come & Join Us at VUSTUDENTS.net

The Final One. Case Study: Adding a GUI to the Student Data Base. Graphical Use Interfaces: the student database example. Assignments.

The Abstract Window Toolkit

Graphical User Interfaces in Java - SWING

Java.net - the Source for Java(tm) Technology Collaboration

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

PART1: Choose the correct answer and write it on the answer sheet:

RAIK 183H Examination 2 Solution. November 11, 2013

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Interacción con GUIs

AP CS Unit 11: Graphics and Events

URL Kullanımı Get URL

Decisions: Logic Java Programming 2 Lesson 7

DEMYSTIFYING PROGRAMMING: CHAPTER FOUR

Handout 14 Graphical User Interface (GUI) with Swing, Event Handling

Sri Vidya College of Engineering & Technology

Transcription:

Java - Applications C&G Criteria: 5.3.2, 5.5.2, 5.5.3 Java applets require a web browser to run independently of the Java IDE. The Dos based console applications will run outside the IDE but have no access to the Java awt controls. Java can produce Windows applications. The code required is very similar to that for applets. There are the following key differences No access to the Applet Class, removing some methods such as getcodebase and getimage. Code has to be written to close the application window - clicking the little 'x' is not enough. Applications allow menus, applets do not. The default layout is Borderlayout for an application and FlowLayout for an applet The dreaded public static void main(string[] args) is back. The following code sets up an application with a drop down menu, as yet the menu does not do anything. import java.awt.*; import java.awt.event.*; //can't import applet public class Paste extends Frame implements WindowListener, ActionListener //WindowListener is used to respond to window events private MenuItem copy, cut, paste; public static void main(string [] args) //main is inside the Class - the Class is created as a new Frame Object Frame f = new Paste(); f.setsize(200,200); f.setvisible(true); //create somewhere to show the class, size 200, 200 public Paste() //the constructor class holds the data that would be in init() //of an applet settitle("textareas"); //caption of the application setlayout(new FlowLayout()); //the default layout is BorderLayout this.addwindowlistener(this); //need to register window actions //compare to mouse actions MenuBar menubar = new MenuBar(); //menu heading Menu edit = new Menu("Edit"); // a single drop down copy = new MenuItem("Copy");//add individual menu items edit.add(copy); copy.addactionlistener(this); //add a cut and a paste item as well 1

menubar.add(edit); //add edit to the MenuBar setmenubar(menubar); //set up the MenuBar public void actionperformed(actionevent event) //event handling code to put here public void windowclosing(windowevent event) //allow closing of window System.exit(0); //like the mouse actions these are required for Java events that might not be used public void windowiconified(windowevent event) public void windowopened(windowevent event) public void windowclosed(windowevent event) public void windowdeiconified(windowevent event) public void windowactivated(windowevent event) public void windowdeactivated(windowevent event) Enhancements 1. Add a TextArea to the application, this will hold text to try out the copy and pasting code. The new code will be in the actionperformed events for the menus. Although a TextArea is set up with a number of columns and rows for the text Java allows any text entered to scroll off the viewing area. The editing will depend on some of the methods of the TextArea, getselectedtext(), getselectionstart(), getselectionend(),replacerange(). The string to be cut, copied or pasted will have to be remembered between menu clicks so will be declared at the top of the class with the awt controls. 2. The colour of the text could be changed from another menu drop down. This requires a similar line to Menu edit = new Menu("Edit"); that will add the new menu header. New MenuItems are added to that Menu. Their ActionEvents will change the font colour in the TextArea through - setforeground(). 2

3. Handling font styles and sizes from a menu is less than ideal as the user would prefer to pick from a range of font styles and sizes. This will be achieved with the drop down control that Java calls Choice. At this stage the Choice controls will be set up but they will not do anything. Adding the Choice controls is the same as adding a Button, declare then create an object with new. The application will have 2 Choices and a Label for the size Choice. It will soon be evident that the style Choice is not going to need a Label. To tidy up the application the layout will use flow and BorderLayout with the TextArea in Center and the Choices in North with the Label. So the new controls will be part of a new Panel that is destined to be at the BorderLayout position North. Panel p = new Panel(); //create new Panel p.setlayout(new FlowLayout()); //the new controls flow on the Panel styles = new Choice(); //create new controls p.add(styles); //add the new controls to the panel add(p, BorderLayout.NORTH); //add panel to top add(input, BorderLayout.CENTER); // add TextArea to centre The new Choice controls will be populated using for loops. The font size is straightforward as any suitable range of numbers can be used. Have the loop generate a range of integers, convert these to Strings and add to the Choice: mychoice.add(mystringfontsize); There is a cunning trick for the font style as Java knows what fonts it has access to and we can tell it go and get them. This requires use of Toolkit object, this is accessed in the following fashion: Toolkit tk = Toolkit.getDefaultToolkit(); The resulting font names can then be assigned to a String array String[] fontlist = tk.getfontlist(); 3

A for loop will add these Strings to a Choice control, fontlist.length can be used to stop the loop without going out of bounds of the array. 4. Next the fancy new controls need to act on the TextArea. The Choice controls do not use actionperformed(actionevent event) but itemstatechanged(itemevent e). This requires an additional implements for the class, ItemListener and the associated listener for the controls such as sizes.additemlistener(this). As the selection of either Choice will have the same effect, a change in font a single if statement can cover both e.getsource() possibilities. The aim is to get the font name and size from both Choices. The font name is a String as is the text in both Choices. For the font size the String selected will have to be changed to an integer. When declaring a font the weight (bold, normal) is also required; use Font.PLAIN to fill in the specification. 5. Allow the user to set up font weights with another Choice control. The value used to set a font weight is an integer, plain is 0, bold is 1 and italic is 2. Take advantage of this by setting up the Strings in the weight Choice in that order. The font weight can then be found from: int itype=chweight.getselectedindex(); File I/O The TextArea can be used to display the contents of a text file or the data in the TextArea could be saved to a file. To trigger these events the application will need another Menu (file) with MenuItems for opening and saving files. Java has an awt component called the FileDialog that is just dandy for inputting file names for later use. The FileDialog has to be declared like any other component: private FileDialog getname; 4

It can then be created and used in the appropriate actionperformed event. At this stage the file name is passed to a String getname for future use. if(event.getsource()==open) getname=new FileDialog(this,"File Name",FileDialog.LOAD); // FileDialog.SAVE for saving a file name getname.setvisible(true); //no drop downs for these but code works filename=getname.getfile(); Unfortunately the getfile method only returns the name of the file. As long as the file is in the same directory as the java program is running from this does not matter. For more useful file browsing the directory will have to be found and appended to the file name. String dir = getname.getdirectory(); filename=dir + getname.getfile(); To work with files requires importing java.io above the class header: import java.io.*; As messing with files is a useful operation all the file handling can be part of a method that accepts a String containing the file name and path and returns a String with the file contents. public String openfile(string name) BufferedReader inputfile;//for file i/o String result="";//must initialise try //FileReader reads the file into BufferedReader so 2 new objects 5

inputfile=new BufferedReader(new FileReader(name)); String linein; linein= inputfile.readline(); //the BufferedReader method to read the file line by line while(linein!=null) //while linein still reads data result= result + linein + "\n"; //add a new line to the string linein= inputfile.readline(); //read the next line inputfile.close(); //close BufferedReader catch(ioexception e) //catch cock ups, such as file as not found //print error result="error " + name + e.tostring(); //System.exit(1); //use to quit program return result; It is worth implementing this code and opening a text file that has been created in Notepad before creating code to save files. Saving files should also be set up as a method. This will involve less code as writing to disk does not have to move down line by line. It chucks the lot in and picks up the \n symbols as it goes along. There are some key differences. Instead of BufferedReader, use PrintWriter PrintWriter Reader outputfile=new PrintWriter(new FileWriter(fileName),true); FileWriter is created with the file name and the option true to flush the system buffer. A single line will assign all the required text to the PrintWriter object. outputfile.print(text); The method to save files will have to accept the name of the file to be saved and the data to be saved. These are both Strings. The method need not return anything but it would be useful if it returned any error messages generated by failed write operations. The following is a suitable file saving method title: public String savefile(string filename, String text) Go Objects Create a new Class to save or open files. The 2 methods created above can be cut and pasted into the Class. The return String result, the BufferedReader and PrintWriter objects can all be private, java.io.*; will move to the new Class. Create an object of the new Class in the original application and use its public methods to save and open files. 6