1. Trang chủ
  2. » Công Nghệ Thông Tin

Java the easy way ebook

59 226 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 59
Dung lượng 3,83 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

• Add the zip file to NetBeans Tools, Java Platforms • You could add the source code here also... Pet CodeElements of our class: • Four class attributes • Three class methods • One cla

Trang 1

Java the easy way

James A Rome Tennessee Governor's Academy

August 2010

Trang 2

Why Java?

Java is the most in-demand

language (= job opportunities)

It is a modern object-oriented

language

It is similar to C and C++

It leaves out pointers, multiple

inheritance, operator overloading

Write once, run anywhere

From supercomputers to cell

phones, Macs, Windows, Linux

It is faster than any language other than Fortran or Assembler

There are oodles of libraries

Free excellent development tools

Trang 3

Java programmers are in demand

Management/Programming-Development-Skills-In-Demand-505665

http://www.eweek.com/c/a/IT-In the WSJ recently, there was a longarticle on how the language you useaffects how you think

Computer languages foster logicalthought

• But many scientific calculations do not fit nicely into existing computer languages

• Remember that digital computers do discrete mathematics and computations: calculations are done at a finite number

Trang 4

Tools you will need (installed I hope)

The Java development kit

http://www.oracle.com/technetwork/java/javase/downloads/i ndex-jsp-138363.html

The NetBeans IDE Some people prefer Eclipse

Trang 5

Our foray into Java

Purpose: Get your feet wet so you can

understand how scientists use computers and teach yourself more Java.

book

How to do a graphical user interface (GUI)

How to model a real problem and get it into a form a

computer can solve

How to teach yourself

Java Classes and techniques

Trang 6

Some basic syntax

Assignment uses an equals sign

int b = 4; // assigns 4 to the integer variable b

Testing for equality uses ==

⇒ if(b == 4) { /* do something when b is 4 */}

// Comments to the end of the line

/* */ Comments blocks, which can be many lines

/** */ A JavaDoc comment

Java is self documenting if you put these comments into your code they get converted to nice html

Formatting is optional but important for readability

All statements must end in a semicolon

Braces {} group lines of code and define a scope

Things defined in the braces are not accessible outside them.

Names must start with a letter

Trang 7

Java syntax

Built-in types for variables:

char, int, short, byte, long, float, double, boolean

These are not Objects But all have wrapper classes that turn them into Objects

int a = 5;

Integer aInt = new Integer(a);

Everything else is an Object (think noun, its a thing)

Unlike in C or C++, these are the same on all platforms

Otherwise (without ints, floats,…) , you could not write

a = b + c;

Trang 8

while(j < 10) { // Test at start of loop

at end of loop do this

Class methods or fieldsare referenced using "."

System.out returns a

PrintStream object,which has a method

println()

Trang 9

Logic (make decisions)

int b = ((a > 7) ? 0 : 1); // Usually a good idea to put

if(b != 5) b += 7; // Parens around the condition

Trang 11

Everything in Java is part of a class

Classes represent objects from the real world.

Think of a class as “The definition of a set where each member of the set exhibits the same behavior and has the same attributes and associations.”

Good programmers decide what classes they need to write before starting to write a program!

Classes in Java may have methods and attributes.

Methods define actions that a class can perform.

Attributes (or fields) describe properties of the class

Classes are described in JavaDocs that are generated from

comments in your code

(http://docs.oracle.com/javase/7/docs/api/)

You need to learn what the basic classes do by reading JavaDocs:

String, Collection, HashMap, Vector, BufferedReader, BufferedWriter, Integer, Math, File, …

Call with ClassName.method() or ClassName.attribute

Trang 12

/** Method to put pet to sleep */

public void sleep() { System.out.println("Good night See you tomorrow"); }

/** Method to feed pet */

public void eat() { System.out.println("Feed me a cookie!");

} /** Method to let pet speak */

public String say(String aWord) { String petResponse =

"OK!! OK!! " + aWord;

return petResponse;

} }

The returned type

file:///home/jar/TGA/Presentations/FermiAcceleration.ppt

Trang 13

What is an IDE?

You write, compile, run, and profile your program within the Integrated Development Environment (IDE).

It makes your life simpler:

A code-friendly editor with context highlighting, code hints, and code completion

It makes it really easy to create a graphical user

interface

It write lots of boiler-plate code for you

NetBeans is also great for C/C++, Python, Ruby, Fortran

It is extendable with numerous plugins

NetBeans is my favorite IDE by far

You might like Eclipse or JDeveloper

Trang 14

NetBeans should be installed

Trang 15

Set your NetBeans options

Under Tools/Options

In General: Pick your

favorite Web Browser

Under

Options/Formatting, set

the indent and tab

sizes to 3 characters

You can look at the

other options at your

leisure

Trang 16

Install the JavaDocs

The Java documents come in

a zip file:

jdk-7u??-docs.zip

[download it from the JDK page]

NetBeans is smart enough to

use it in its zipped form,

but you might also want to

use it in your Web browser,

so copy the file from the

cd to your Documents folder

into a Java subdirectory

Unzip it by double-clicking

on it.

Add the zip file to

NetBeans

Tools, Java Platforms

You could add the source

code here also

Trang 17

Create a Pet in NetBeans

File/New Project

Create a new Project called “MyPets”

Do not create a Main Class

Trang 18

Make a Package for your project

A package is a way of

specifying a set of classes

that have special

privileges because they

belong with each other.

reverse DN (e.g.,

com.sun.java.utility)

We will use mypets (in lc)

Source Package name and

select “New, Java

Package”

Trang 19

Create the Pet Class

Right-click the mypets Package and select “New, Class”

• Note that the file is always

classname.java, and it is stored

in the package directory tree

• By convention, Classes start

with an uppercase letter

Trang 20

Pet Code

Elements of our class:

Four class attributes

Three class methods

One class constructor

In Java, things have visibility:

public — visible and usable to all

private — only accessible by this class

protected (default) —accessible by classes in this package

Visibility keeps code clean and secure If you want something visible, create getter and setter methods

So the attributes are private

Trang 21

Classes must be instantiated

In order to do anything with a class you must “create an

instance of the object.”

This uses the class definition

to make a copy of the object described by the class and to put it in the computer’s

memory.

Pet myPet = new Pet();

myPet is the name of the

instance and is a member of

the class Pet.

Trang 22

We need code to instantiate Pet

public class PetMaster {

public static void main(String[] args) {

Local variable Make a Pet

Call the Pet methods

Trang 23

Make a PetMaster Class

Trang 24

Run the project

The project needs to know

where the main() method is.

Right-click the Project,

and select Properties

Note that you must specify

the package as well as the

class name in the Run

settings

Run your project by either clicking the green arrow, or

selecting Run Main

Project on the Run Menu

Trang 25

Our class Pet will help us learn yet another

important feature of Java called inheritance In

real life, every person inherits some features

from his or her parents Similarly, in the Java

world you can also create a new class, based on an

existing one (but only one).

A special keyword extends does the trick:

class Fish extends Pet {

}

Fish is a subclass of the class Pet.

Class Pet is a superclass of the class Fish.

Fish myLittleFish = new Fish();

myLittleFish.sleep(); (Fish inherits all of the methods of Pet)

Trang 26

Making a subclass

Creation of subclasses in

NetBeans is a piece of cake!

Right-click the package and

select New, Class, and type Fish

as the name of the class

Then put in “extends Pet” before

the first {

Let’s not forget, however, that

we’re creating a subclass of a

Pet to add some new features

that only fish have, and to reuse

some of the code that we wrote

for a general pet.

Everything inherits from Object

Trang 27

Fleshing out our Fish

public class Fish extends Pet {

private int currentDepth = 0; // keeps track of the depth

public int dive(int howDeep) { // a new method for fish

currentDepth = currentDepth + howDeep; // Incremental

System.out.println("Diving for " + howDeep + " feet"); System.out.println("I’m at " + currentDepth +

" feet below sea level");

return currentDepth;

}

@Override // An annotation This overrides Pet.speak

public String speak(String something) {

return("Don’t you know fish do not talk!");

}

}

Trang 28

Need to change PetMaster

public class PetMaster {

public static void main(String[] args) { String petReaction;

// Your previous code can stay here Fish myFish = new Fish();

Trang 29

Run the code again with your fish

Trang 30

How to run without NetBeans

Taken from README.TXT in the MyPets/Dist folder:

When you build an Java application project that has a main class, the IDE automatically copies all of the JAR

files on the projects classpath to your projects dist/lib folder The IDE

also adds each of the JAR files to the Class-Path element in the application JAR files manifest file (MANIFEST.MF).

To run the project from the command line, go to the dist folder and

type the following:

java -jar "MyPets.jar"

To distribute this project, zip up the dist folder (including the lib folder)

and distribute the ZIP file.

Trang 32

It is even worse under pressure

© Pixar

Trang 33

Making an application with a GUI

There are several methods of making graphical user interfaces in Java — AWT, Swing, SWT We will concentrate on Swing.

A Swing book is on your CD

interface

A Java Bean Object has get and set methods

It adheres to certain naming conventions

Java Bean properties can be manipulated in GUIs by tools such as NetBeans

•But you must always remember the user!

Trang 34

Making a GUI application using NetBeans

Open NetBeans and do

File, New Project

Select Java Application

from the Wizard and hit

Next

Uncheck Create Main

Class

Enter the project Name

YourName and hit Finish

The YourName project

will appear in the left

Package Window, with a

package, files, and a

blank GUI

Trang 35

NetBeans has a new GUI framework

Make a new Java package

Create a new GUI class based upon

A JFrame by right-clicking the yourname Package.

Trang 36

Your new GUI project

Set the properties of each com- ponent here

Trang 37

Add a prompt label

Click the Label in the Palette

(top-right) Swing controls, and then click

near the top-left of the design area

Use the dotted guidelines to space

from the top and left edges.

Double-click jLabel1 to edit the text

and hit Enter (or else it will not

Trang 38

Add a TextField for data input

Add a TextField Note the three spacing option lines and the lower edge alignment markers

Drag the right edge of the TextField to the right edge until the vertical dotted line appears This pins the field to the right edge.

Double-click “jTextField1”, delete it, and hit Enter Right-clicking and selecting “Edit text” may work

better.

Try to run your project.

Trang 39

Rename your swing objects

It is very important to replace the default names

in a more complicated project so that you know

which text field (or other object) is which.

Right-click each label and change its name

I used “enterNameLabel” and “enterNameTextField”

Note that by convention, variables start with a lower-case letter, and I retained the Swing type in the name

Do this to all your Swing objects in the future

Trang 40

Run the app

and right edges as the window is resized

which is due to using a Layout Manager

Trang 41

What is a Java Bean?

A class that exposes its accessor methods:

For each public class member, there is a get and set method

It must be serializable This allows the instance of the

class to be written to a file and read back again.

⇒ class ClassName implements Serializable { }

It must use member names that start with lowercase

⇒ private String myString = “Boo!”

public String getMyString(void) {return String;}

public void setMyString(String s) { myString = s;}

All Swing components are Java Beans

Therefore, we can make our own GUI components by extending a Swing class

Trang 42

Eliminate the StatusBar

Click StatusPanel and

delete it

Source view

Trang 43

Delete the statusBar code

At the end of YourNameView, delete

private final Timer messageTimer;

private final Timer busyIconTimer;

private final Icon idleIcon;

private final Icon[] busyIcons = new Icon[15];

private int busyIconIndex = 0;

In the constructor, delete all but

public YourNameView(SingleFrameApplication app) { super(app);

initComponents();

}

Trang 44

Fix the App name

Expand the yourname.resources package

Open Application.description

Change the Title (to "Your Name" ) and you can replace the other fields (e.g., Vendor or the Description) if you wish.

Save your project

Trang 45

Add an OK Button & output Label

Add a Button aligned to the bottom-right edge guides (which pins the button to this corner as the frame

is resized).

Rename it to okButton, and change the displayed name

to “OK”.

Add a Label for the output text called

“outputLabel” Stretch it to fill the horizontal

width up to the right guideline Delete the text

(the label will collapse to a line).

I made the whole frame smaller verticallyThe Label is

pinned to theleft edge and thetop of the button

Save your project

Trang 46

Change the font for the outputLabel

Double-click the to openthe font dialog Pick a fontyou like!

Save your project

Trang 47

Add an action event to the JButton

The GUI is done, but it does not do anything yet!

An ActionPerformedEvent occurs when a button is pressed

At that point we can get the text the user typed and

display it.

Right-click the okButton and add the event.

Save your project

Trang 48

ActionEvent code Source view

w

The yellowbars indicateunused imports.Right-click in thecode and

choose "Fiximports"

(They belonged

to the progressbar that wedeleted

Trang 49

Code completion and JavaDocs helps

private void okButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

String name = "Your name is " +

enterNameTextField.getText();

outputLabel.setText(name);

}

Save your project

Strings are immutable

They are stored andnever changed

Trang 50

Run the code

Defects in the application:

It would be nice to let the user hit “Enter” in addition to clicking the button

Can make it prettier (e.g., Colored text)

This is a possible security hazard because we

do not check what the user typed in (It would

be for sure in a Web Application.)

Trang 51

Adding a key event

private void enterNameTextFieldKeyTyped(java.awt.event.KeyEvent evt) { // TODO add your handling code here:

}

Right click the enterNameTextFieldand do Event, Key, keyTyped

Trang 52

Edit the JTextField KeyListener

'\n' is generated when the user hits Enter Note that chars are in single quotes.

This code appears twice It is a good candidate for a new class method Then any changes to this code only have to be done once.

How????

Run your code and verify that hitting Enter is the same as clicking OK

Ngày đăng: 23/10/2014, 13:57