copyright © 2008-2013 curt hill first windows program guis in eclipse

Post on 04-Jan-2016

216 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Copyright © 2008-2013 Curt Hill

First Windows Program

GUIs in Eclipse

Preliminaries• Goal: Create a Windows program

using Eclipse• The problem to solve is to take the

number of years and convert it into the number of seconds of a persons life

• Simple GUI with:– Two buttons– One input– One output

Copyright © 2008-2013 Curt Hill

Disclaimer• There is a lot to know• Fortunately, there are some

shortcuts• The presentation goes through how

to do this the hard way– In most cases it will be much easier

• These will be shown at the end of the presentation

• The shortcuts will be considered in the demonstration

Copyright © 2008-2013 Curt Hill

Needed Objects• JFrame

– A window and container

• JButton• JTextField

– A field to type in data

• JLabel• LayoutManager

– Organizes GUI objects in a container– Handles the resizing

• ListenersCopyright © 2008-2013 Curt Hill

How does it fit?• Declare and initialize controls

– Such as buttons

• Add them to a layout manager– Controls the display and sizing

• Create listeners for the buttons– Listeners are separate classes

• The listeners call a method in the main class to handle the event

Copyright © 2008-2013 Curt Hill

Procedure• Create an Eclipse project

– We have done this before

• Add a Java class to it– We will use JFrame as ancestral class

• Add the objects:– Two buttons– One textfield– One label

Copyright © 2008-2013 Curt Hill

Create Project

Copyright © 2008-2013 Curt Hill

Add a new Java Class 1

Copyright © 2008-2013 Curt Hill

Name Package and Object

Copyright © 2008-2013 Curt Hill

Browse for a Type

Copyright © 2008-2013 Curt Hill

Choose Object: javax.JFrame

Copyright © 2008-2013 Curt Hill

Things to be Set

Copyright © 2008-2013 Curt Hill

After Finish Clicked

Copyright © 2008-2013 Curt Hill

What goes in main?• Create the constructor

– Constructor is method with same name as class

• Set the size• Make the location• Make it appear

Copyright © 2008-2013 Curt Hill

Constructor• The constructor will look

something like this for now:public Win1(String s){ super(s); init(); }

• It will be called like this from main:Win1 w = new Win1(“Age in Seconds”);

• The call to super is to calling the JFrame constructor

Copyright © 2008-2013 Curt Hill

The Rest of main• We set the size with:w.setSize(300,200);

• We place it on the desktop with:w.setLocation(100,100);

• Show the window:w.setVisible(true);

• The code will then look like the next screen

Copyright © 2008-2013 Curt Hill

The First Amount of Code

Copyright © 2008-2013 Curt Hill

Now What?• The program is just the shell of a

Windows program• Lets run it and see what happens• Try out the buttons on title bar

– Minimize– Maximize/Restore– Kill

Copyright © 2008-2013 Curt Hill

First Run

Copyright © 2008-2013 Curt Hill

Now What?• This program did not have the

things promised– No buttons– No text fields– No nothing

• Here is where we start adding the components

• We will initialize them in the init method that was createdLayout Manager

Copyright © 2008-2013 Curt Hill

Layout Manager• The default layout manager for

JFrame is BorderLayout• This has its uses but overall will

not work well for this application• Instead lets use Flow, which is the

default for Applets• We need two things

– Import – Code

Copyright © 2008-2013 Curt Hill

What do we need?• Need a new import statement:import java.awt.*;– This should follow the other import at

the front

• In the init method add the following code:FlowLayout flow = new FlowLayout();setLayout(flow);

Copyright © 2008-2013 Curt Hill

Adding Widgets• The change of the layout manager

must occur before any other widget or control is added

• To add a simple control there is a four step process:– Declare the control– Instantiate the control with the new

keyword– Set any other values needed– Add it

Copyright © 2008-2013 Curt Hill

Declaration• The declaration right after the

class header• In our case that is this:public class Win1 extends JFrame {

• So add one label after that:JLabel lab1 = null;

Copyright © 2008-2013 Curt Hill

Instantiate• The instantiation will go into the init

method:void init() {lab1 = new JLabel(“Enter age in years:”);

• There is nothing else for a label so add:add(lab1);

• Lets run it

Copyright © 2008-2013 Curt Hill

One More Thing• Each control or widget may need

an import• Java allows wildcards on imports• Change the generated import

from:import javax.swing.JFrame;

• Intoimport javax.swing.*;

• This also gives us JLabel, JButton etc

Copyright © 2008-2013 Curt Hill

Another Run

Copyright © 2008-2013 Curt Hill

Next• The next thing to do is add the

input box• This is the Java JTextField• Similar to the JLabel as far as

addingJTextField text = null;…text = new JTextField(5);add(text);

• The 5 is the number of columnsCopyright © 2008-2013 Curt Hill

Buttons• The hard one is buttons• They have the declaration,

instantiation, adding of Labels and TextAreas

• They also need an event handler• The event handler is triggered by

the Action Listener• Gets somewhat uglier at this point

Copyright © 2008-2013 Curt Hill

Action Listeners• The main program is a class • It starts right after the imports with a

public class declaration and proceeds to end of program– So far

• We now need to create an ActionListener

• This handles the notification that the button has been clicked

• Then calls a method in the Win1 class

Copyright © 2008-2013 Curt Hill

Shape• ActionListeners always have a

characteristic form• Usually about 10-12 lines• A sample is given next• Explanation follows

Copyright © 2008-2013 Curt Hill

Sample Listener

Copyright © 2008-2013 Curt Hill

class LClass implements ActionListener{ MyFrame adapter; LClass(MyFrame a){ adapter = a; } // end of constructor

public void actionPerformed(ActionEvent e){ // Call event handler adapter.eventHandler(); } // end of actionPerformed} // end of LClass

Class Name• The class name in this example

was LClass • It may be any Java name• Should not match any other name

in the program• We will use that when we add the

action listener

Copyright © 2008-2013 Curt Hill

Window Name• The MyFrame class in the previous

screen should be the name of the windows class that you created

• In our example this line was the main program:public class Win1 extends …

• Then we should see: Win1 adapter; LClass(Win1 a){– In the second and third line

Copyright © 2008-2013 Curt Hill

Event Handler• The actionPerformed method

called the eventHandler method of our main windows program

• This method name should match a public void method in the main window class

• Like the class name it does not matter what you make it, except that it matches the actual method name

Copyright © 2008-2013 Curt Hill

More Details• The event handlers need:import java.awt.event.*;

• This is how the system knows what an action performed item is supposed to do

• Next is the modified Lclass

Copyright © 2008-2013 Curt Hill

Inserted ActionListener

Copyright © 2008-2013 Curt Hill

The Button• Now we can insert the button code

into the init method• The usual code and another callbutton1 = new JButton("Calculate");button1.addActionListener( new LClass(this));add(button1);

Copyright © 2008-2013 Curt Hill

Button Picture

Copyright © 2008-2013 Curt Hill

Event Handler• The action listener class called a

method in the windows class• In our example the code was: adapter.eventHandler();

• Now we have to make that method do something

Copyright © 2008-2013 Curt Hill

The Skeleton• Such a method will have the

following outer part:void eventHandler(){ …}

• What do we now want to do?• Many programs have this basic form:// Get data// Do computations// Display results

Copyright © 2008-2013 Curt Hill

Getting Data• The main problem is that a

textfield always has text in it– The type is String

• If we are interested in numerics then we must convert to a number

• This is done with static methods of a wrapper class

• We could use Scanner but that is more console/file based

Copyright © 2008-2013 Curt Hill

TextField to Numerics• To convert an edit box value to a

usable numeric value, we use the wrapper classes– Integer– Double

• Thus code like this:int i = Integer.parseInt(edit1.getText());double d = Double.parseDouble(edit1.getText());

• This causes the value to be obtained from the edit box named edit1 and converted into an int or double

Copyright © 2008-2013 Curt Hill

Back to a String• To display a result in either a

TextField or Label requires the setText method

• This may only take a String• There is no String constructor that

takes a numeric• There is however the valueOf method• Thus:lab1.setText( String.valueOf(d));

Copyright © 2008-2013 Curt Hill

Another Conversion• You may also concatenate a

number to a string painlessly:int a = b*c/2;String s = “Answer: “+a;

• However, you may not assign a number to a string directly without valueOfs = a; // Illegals = String.valueOf(a); // OK

Copyright © 2008-2013 Curt Hill

Static Methods• parseInt, parseDouble, and valueOf

are all static methods• A static method does not need an

instance of the type• We usually use the class name as

if it were an instance:Integer.parseInt(x);Double.parseDouble(y);String.valueOf(u);

Copyright © 2008-2013 Curt Hill

Casts• Why do we not cast these

conversions?• Casts only work on primitive types• A String is not a primitive so it

must use a static method to convert values into it

• Similarly the wrapper methods also use static methods to make a double out of a string

Copyright © 2008-2013 Curt Hill

Get Data• The data is in the text field named text

• The method call:text.getText() will get it

• Then we convert into an integer with:Integer.parseInt(…)

• We use:int years = Integer.parseInt( text.getText());

Copyright © 2008-2013 Curt Hill

Do Computations• The computation is merely a bunch

of multiplications to convert years into seconds

• Multiply by– Days in year– Hours in day– Minutes in an hour– Seconds in a minutedouble sec = years*365.25*24*60*60;

Copyright © 2008-2013 Curt Hill

Display Results• System.out.println is mostly used

for console programs• In a GUI we put the result in a

Label or TextField• In this example the label is named

answer• We use the setText method:

answer.setText(“”+sec);

Copyright © 2008-2013 Curt Hill

Event Handler and Run

Copyright © 2008-2013 Curt Hill

Are we done?• This program is now 61 lines• It still needs some work:

– An exit button– An about button

• However, most of that can wait until we get this part under control

Copyright © 2008-2013 Curt Hill

New Button• Exit button is simple, add a new:

– Button– Listening class– Event handler

• The event handler method should execute:System.exit(0);

• This enlarges the program to 82 lines• The About needs a dialog which will

wait for a future presentation

Copyright © 2008-2013 Curt Hill

With Exit Button

Copyright © 2008-2013 Curt Hill

Shell programming• Eighty or more lines is likely more

than we want to type for each program

• What many programmers do is modify a previous program into their next one

• Lots of this program could be recycled

• How would that work?

Copyright © 2008-2013 Curt Hill

The Windows Shell• Attached to the web site is a shell

program• It is the do-nothing windows

program• It contains instructions on how to

modify it inside comments• The standard Windows shell comes

with one jTextField, several jLabels and three jButtons

Copyright © 2008-2013 Curt Hill

Process• The process is fully described in

the shell itself• Create new project and class• Copy the shell in over everything

except the package statement• Use Replace to change the

WinShell name with the one you created above

• Then customize the program as needed

Copyright © 2008-2013 Curt Hill

Customization• The instructions to customize the

program are coded with /*--

• These can be searched for and modifications made

• If a new button is needed then the instructions to do that are coded with a /*++

Copyright © 2008-2013 Curt Hill

WinShell• Lets walk through the process a

second time with WinShell • This one will be quicker• We will close all previous projects • First create a new project and add

a class• Paste in WinShell• Modify• Run

Copyright © 2008-2013 Curt Hill

Started

Copyright © 2008-2013 Curt Hill

Delete Program

Copyright © 2008-2013 Curt Hill

Paste in WinShell

Copyright © 2008-2013 Curt Hill

Start Replace

Copyright © 2008-2013 Curt Hill

Replace Dialog

Copyright © 2008-2013 Curt Hill

Change About

Copyright © 2008-2013 Curt Hill

Captions

Copyright © 2008-2013 Curt Hill

Main method

Copyright © 2008-2013 Curt Hill

Event Handler

Copyright © 2008-2013 Curt Hill

Run

Copyright © 2008-2013 Curt Hill

Lastly• We will next do the demo• The windows shell from the web

page will be used• There is quite a few things that

need to be changed• Not nearly as many as if typed in

new

Copyright © 2008-2013 Curt Hill

top related