1 cse1340 class 4. 2 objectives write a simple computer program in java use swing components to...

Post on 05-Jan-2016

215 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1

CSE1340CSE1340Class 4Class 4

2

ObjectivesObjectives Write a simple computer program in Java

Use Swing components to build the GUI

Use proper naming conventions for classes and files

33

Adding Interface Components Adding Interface Components to a java applicationto a java applicationJLabel

– An area where uneditable text can be displayed.JButton

– An area that triggers an event when clicked.JTextField

– An area in which the user inputs data from the keyboard. The area can also display information.

4

Simple steps for creating a user interface:Simple steps for creating a user interface:

1. Create a window where gui components are 1. Create a window where gui components are displayeddisplayed2. Set the layout of the window2. Set the layout of the window3. Create the gui components3. Create the gui components4. Add them to the window4. Add them to the window

5

Step 1: Create a window on which to place the gui components

Container myWindow = getContentPane();

Programmer defined name

Part of the Java API Method call to perform a task

6

Step 2: Set the layout of the window

myWindow.setLayout (null);(Java doesn’t know where to place the components so you will have to set the bounds (specify where) each component should go)

// or

myWindow.setLayout (new FlowLayout()); // Java knows where to place the components // (left to right, top to bottom)

7

3. Creating the gui components3. Creating the gui components

8

JLabelsJLabelsJLabel label = new JLabel();

– Constructs an empty Label-text is not displayedJLabel label1 = new JLabel( “Label with text” );

– Constructs a Label that displays the text with default left-justified alignment.

// where do you want it to go in the window and

// what do you want the size to be

label1.setLocation(100,20);

label1.setSize(200,100);

Kind of object defined in Java api

Programmer defined name of object

9

JLabelsJLabels

// decide on the font or use the default font

label1.setFont(new Font(“Arial”, Font.PLAIN,40));

Any valid font nameFont.BOLDFont.ITALIC

Size of font in pixels

10

JLabelsJLabels

// where within the allocated space should the

// label appear ?

label1.setHorizontalAlignment( JLabel.CENTER);

// other alignment choices: LEFT

RIGHT

// add the label to the window

myWindow.add(label1);

11

JLabelJLabel

JLabel label2= new JLabel( ); – Constructs a label that is empty

label2.setIcon (new ImageIcon(“java.jpg”));

The label contains a picture instead of text.

// set the bounds

label2.setBounds(300,100);

// set the alignment

label2. setHorizontalAlignment( JLabel.CENTER);

12

JLabelJLabel

// add label2 to the window

myWindow.add(label2);

13

Creating a complete Java Creating a complete Java applicationapplication

14

Coding/Implementing the SolutionCoding/Implementing the Solution

Integrated development environments (IDE) such as

NetBeans

can be used to make coding simpler. NetBeans is a free download from Sun and is installed on the computers in the Junkins lab and the SIC open lab. Instructions for using NetBeans are available via a link at the top of your outline. You should print them out before next week’s lab. Lab assistants should show you how to use NetBeans next week.

15

Coding the Program -Coding the Program -Comments as Documentation Comments as Documentation

Purpose of comments– Provides clear description when reviewing code– Helps programmer think clearly when coding

Placement of comments– Use a comment header to identify a file and its

purpose– Place a comment at the beginning of code for each

event and method– Place comments near portions of code that need

clarification

16

Coding the Program -Coding the Program -Comments as Documentation Comments as Documentation

General form:

/* block comments */

// line comments

Example: /* Programmer: Judy

Date: Sept. 3, 2007

Filename: MyProgram.java

Purpose: This program displays the name and webaddress of a company */

17

Import PackagesImport PackagesUse the import statement to access classes in

the SDK– The java.lang package is automatically

imported– Place the import statement before the class

header– Use an asterisk (*) after the package name

and period delimiter to import all necessary classes in the package

import javax.swing.*;

18

19

import javax.swing.JOptionPane;

The import statement includes particular classes from a particular package (folder) in the java library of classes

20

import javax.swing.JApplet;

The import statement includes particular classes from a particular package (folder) in the java library of classes

21

import javax.swing.*;

public class Welcome4

All code in java must be inside a class definition; the above line begins the definition of a class called Welcome4.

22

Coding the Program - Coding the Program - The Class Header The Class Header

Identify how the code can be accessed with an access modifier– public indicates that the code can be accessed

by any and all entities Specify a unique name for the class

– The class name at the beginning of the program must match the file name exactly

– Java is case-sensitive – Must begin with an underscore, dollar sign or

letter and can then contain underscores, $, letters, or digits (no special characters)

23

Coding the Program - Coding the Program - The Class Header The Class Header – Cannot be reserved words– By convention, uppercase letters are used

for class names and to distinguish words in class names

24

Sample Class HeaderSample Class Header

Use braces { } after the class header to enclose the class body

public class Person { // body of the class}

25

import javax.swing.*;

public class Welcome extends JFrame

We want our class to have the characteristics of a JFrame

Keyword extends gives us inheritance in Java

26

Coding the Program -Coding the Program -The Method Header The Method Header

The method header contains modifiers, return value, method name, and parameters along with their data type

Every stand-alone Java application must contain a main() method, which is the starting point during execution

27

Coding the Program -Coding the Program -The Method Header The Method Header

Modifiers set properties for a method– public allows other programs to invoke

this method– static means this method is unique and

can be invoked without creating a subclass or instance

Return value is the data type of the data returned by the method– If no data is returned, the keyword void

is used

28

Coding the Program -Coding the Program -The Method Header The Method Header

Parameters are pieces of data received by the method to help the method perform its operation– Identifiers are used to name the variable

sent to the method

29

Special Characters/Special Characters/keywordskeywordsCharacterCharacter UseUse

// Double slash// Double slash Marks the beginning Marks the beginning of a commentof a comment

importimport Tells the compiler Tells the compiler where to search for where to search for the packages that the packages that contain predefined contain predefined codecode

30

Special CharactersSpecial CharactersCharacterCharacter UseUse

{ } Open / close { } Open / close bracesbraces

Encloses a group of Encloses a group of statements, such as statements, such as the contents of a the contents of a methodmethod

( ) Open / close ( ) Open / close parenthesesparentheses

UsedUsed in naming a in naming a method such as in method such as in public void paint (….)public void paint (….)

31

import javax.swing.*; import javax.swing.*; // import statements required to use part of the Java API// import statements required to use part of the Java APIimport java.awt.*; import java.awt.*; public class LabelFrame extends JFrame {public class LabelFrame extends JFrame { private JLabel label1, label2; private JLabel label1, label2; public LabelFrame( ) public LabelFrame( ) { { Container myWindow= getContentPane(); Container myWindow= getContentPane(); myWindow.setLayout(null); myWindow.setLayout(null); myWindow.setBackground(Color.CYAN); myWindow.setBackground(Color.CYAN);

32

label1 = new JLabel(“Label with text”); label1.setLocation(300,20); label1.setSize(200,100); myWindow.add( label1 ); label2= new JLabel( );

label2.setIcon (new ImageIcon(“java.jpg”));label2.setBounds(300,100);label2. setHorizontalAlignment(JLabel.CENTER);myWindow.add(label2);setTitle(“Testing JLabel”); setSize(300,200); setVisible(true); } // end of LabelFrame()

33

// Every Java application must have a method main public static void main(String a[]){ LabelFrame l = new LabelFrame(); l.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);}// end of main

}// end of class

34

Label with text

35

Testing the SolutionTesting the Solution Compile the source code If the compiler detects errors, fix the

errors and compile again If the compilation was successful, a new

bytecode file for each class is created with a .class extension

run the program (test it logically)

36

Debugging the SolutionDebugging the Solution System Errors

– System command is not set properly– Software is installed incorrectly– Location of stored files is not accessible

Syntax Errors– One or more violations of the syntax rules of

Java

37

Debugging the SolutionDebugging the Solution Logic and Run-Time Errors

– Unexpected conditions during execution of a program

– Wront results

38

Running the ApplicationRunning the Application After compilation is successful, run the

program to test for logic and run-time errors

39

Editing the Source Code - cont.Editing the Source Code - cont.Recompile and run the application

– The bytecode should be updated after any changes to the source code

Print a hard copy of the source code– The final step of the program

development cycle is to document the solution

top related