Chapter2pp
Upcoming SlideShare
Loading in...5
×

Like this? Share it with your network

Share
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads

Views

Total Views
1,710
On Slideshare
1,710
From Embeds
0
Number of Embeds
0

Actions

Shares
Downloads
39
Comments
0
Likes
0

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. Chapter 2 Using Variables and Constants
  • 2. Objectives
    • Use multiple forms of constructors.
    • Add buttons and text fields to an interface.
    • Use variables to store information.
    • Input data into a text field.
    • Display multiple lines of output in a text area.
    • Obtain and display the system date.
    • Capture user actions with a listener.
    • Add event handling for a button and text field.
    • Incorporate mouse events.
  • 3. Applet Panel with Text Field, Text Area, and a Button
  • 4. Constructor Methods Constructor method executes automatically
  • 5. Variables and Constants
    • Data can be stored in a variable or constant.
    • Variables can change value while the program is executing.
    • Constants cannot change at any time while the program is executing.
    • You have already used constants, e.g. “Hello World.”
    • Anything in quotes is a constant.
    • You used color constants such red, cyan.
    • You have alignment options in the labels such as Label.RIGHT, where RIGHT is a constant.
  • 6.  
  • 7. Java Data Types
    • The data type determines the way that a program handles and stores data.
    • Java has eight primitive data types , which are built-into the language.
    • Java supplies some classes that define additional data types to give more flexibility.
  • 8. Java Primitive Data Types Unicode character—a code designed for internationalization of applications char code 0 single character chr char -128 to 127 0 small integers byt byte true or false false true or false bln boolean Possible Values Default Initial Value Contents Naming Prefix Data Type
  • 9. Java Primitive Data Types Continued -32,768 to 32,767 0 short integer int short -9,223,372.036,854,775,808L to 9,223,372,036,854,775,807L 0 long integer lng long -2,147,483,648 to 2,147,483,647 0 integer data int int 7 digit precision 0.0 single precision floating point number flt float 15 digit precision 0.0 double precision floating point number dbl double
  • 10. Valid and Invalid Variable Names Accepted by Java but is a terrible identifier, since the name is not meaningful. valid X No periods allowed. invalid dblBig.Number Only letters, letters, and underscore characters allowed. No special characters. invalid fltBig# Must begin with a letter or underscore. invalid 2Times valid blnIsFinished valid chrLetter valid int_Person_Count No spaces allowed in a name. invalid int Person Count Reason Valid or Invalid Identifier
  • 11. Declaring Variables
    • When you declare variable, you reserve a location in memory.
    • The data type determines the amount of memory reserved and how the data is handled.
    • To name a variable, you must have the data type prefix and the name you want to give in accordance with naming rules.
    • General Format - datatype variablename ;
    • Examples – float fltTotalSales;
    • int intStudentCount;
  • 12. Forming Numeric Literals
    • Numeric literals can consist of the digits 0-9, a decimal point, a sign at the left, and an exponent.
    • For the floating point variable you must use a f or F after the variable. You can use a D or d for double. Floating point variables default to double.
    • If you type a whole number it assumes an integer unless the value is greater than the integer allowed.
  • 13. Declaring Numeric Constants
    • Use the keyword final to specify that the data remains a constant.
    • You must use final before the data type.
    • Follow standard naming conventions.
    • Begin with 3 character lowercase prefix for the data type.
    • Use uppercase for the rest of the name.
    • Separate the words with an underscore.
    • Example – final float fltTAX_RATE = 0.07f;
  • 14. Selected Java Data Type Wrapper Classes Integer Int Integer floating point numeric Flt Float True or False Bln Boolean character data str String Contents Naming Prefix DataType
  • 15. Scope and Lifetime of Variables New copy each time the method is called. Until the method ends. Visible only inside the method where it is declared. Inside a method. Local One copy for each object instantiated from the class. As long as this specific instance of the class exists. Visible in all methods of the class. Inside a class but not within a method. Instance One copy for the class. As long as any instance of the class exists. Visible in all methods of the class. Inside a class but not within a method. Keyword static . Class Memory allocated Lifetime Scope (Visibility) Location of Declaration Type
  • 16. The TextField Component—Constructor Formats TextField() TextField(int maximumNumberCharacters) TextField(String initialValue) TextField(String initialValue, int maximumNumberCharacters)
  • 17. The TextField Component—Examples TextField txtName = new TextField(20); TextField txtQuantity = new TextField(5); TextField txtZipCode = new TextField("91789"); TextField txtZipCode = new TextField("91789",9);
  • 18. The TextArea Component—Constructor Formats TextArea() TextArea(int numberRows, int maximumNumberCharacters) TextArea(String initialValue) TextArea(String initialValue, int numberRows, int maxNumberCharacters) TextArea(String initialValue, int numberRows, int maxNumberCharacters, int Scroll)
  • 19. The TextArea Component—Examples TextArea txaInvoice = new TextArea(20,40); TextArea txaGrades = new TextArea(15,20); TextArea txaGrade = new TextArea("Name Average",15, 20); TextArea txaGrade = new TextArea("Name Average", 15, 20, TextArea.SCROLLBARS_BOTH)
  • 20. Selected Methods of the TextField and TextArea Components Returns only the text that is selected in the text component. getSelectedText() Selects (highlights) the contents of the text component. selectAll() Adds text to the end of the contents, only available with TextArea. append() Assigns the value to the text component. setText(String value ) Returns the contents of the text component. getText() Purpose Method
  • 21. The getText Method—General Format componentName .getText()
  • 22. The getText Method —Example strName = txtName.getText();
  • 23. The setText Method—General Format componentName.setText(string to be displayed)
  • 24. The setText Method—Examples lblMessage.setText("Hello World"); txtGreeting.setText(strName); txtAnswer.setText("Hello " + txtName.getText()); txtName.setText(""); //Clear the text field
  • 25. Concatenation “ +” means concatenation of two items
  • 26. Including Control Characters
    • ‘ ’ – new line (line feed)
    • ‘ ’ – horizontal tab (advance to the next tab stop)
    • ‘ f’ – form feed (eject a page when sending it to the printer)
    • ‘ ”’ – double quote(include a double quote within the string)
    • ‘ ’’ – single quote(include a single quote within the string)
    • ‘ - backslash
  • 27. The append Method—General Format componentName .append( string );
  • 28. The Append Method—Examples txaInvoice.append("Sold To: " + strName +" "); txaInvoice.append("Address: " + strStreet + " "); txaInvoice.append(" City: " + strCity);
  • 29. Use Unnamed Labels for Prompts Prompts
  • 30. Prompts for Text Components
    • The prompt is never going to be referred to in the program.
    • We can create an unnamed label and eliminate a step.
    • For example: add a prompt named Department – add(new Label(“Department”));
  • 31. Positioning the Cursor
    • You would want the cursor to appear in the first textfield when the user runs the program.
    • The can be achieved by using the requestfocus method for that component.
    • txtDept.requestfocus();
  • 32. System Dates
    • You can easily access systems dates and time using the Calendar class found in the Java util package.
    • The getInstance method creates an instance of the Calendar class which contains the current date and time for the default locale and time zone.
  • 33. Partial List of Calendar Integer Constants Minute of hour MINUTE Hour (12 hour time) HOUR BC or AD ERA Starts with 0 for Sunday DAY_OF_WEEK Julian date DAY_OF_YEAR Day starting with 1 DAY_OF_MONTH Month starting with 0 MONTH 4 digit year YEAR Returns Constant
  • 34. The Button Component—Constructor Formats Button() Button(String label );
  • 35. The Button Component—Examples Button btnBlank = new Button() Button btnClear = new Button ("OK"); Button btnDisplay = new Button("Display");
  • 36. The ActionListener Interface
    • The ActionListener detects (listens) to the click of a button.
    • To add a listener to your code you must:
    • Add another import java.awt.event.*; statement.
    • Include an “implements ActionListener” clause in the class header.
  • 37. Adding a Listener to the Component
    • To add the ActionListener to the component uses the addActionListener method.
    • In the argument, you must include this , which means current class.
    • The current class is notified of the event occurring for that component.
    • btnCalculate.addActionListener(this);
  • 38. Coding for the Event
    • After having added the ActionListener, you must code the actionPerformed method of the interface ActionListener.
    • This method executes each time the user clicks on the button(the event fires).
    • The method header is as follows: public void actionPerformed(ActionEvent pl).
    • The argument pl is that system supplies a value for the action event.
    • The argument indicates which component has triggered the event.
  • 39. Mouse Events
    • Java allows you to listen mouse events such as mouse clicked, mouse moved over an object or mouse moved away from an object, using the MouseListener interface.
    • The MouseListener interface requires you to include five methods, even if you have to leave them empty.
    • The five mouse methods are mouseClicked, mousePressed, mouseReleased, mouseEntered, and mouseExited.
    • You will code in the mouseEntered method. When the mouse enters in the button.
  • 40. Mouse Events Continued
    • You will code in the mouseExited method. When the mouse exits the button.
    • If you are not coding in the other methods, they must be included and empty.
    • They override the methods defined in the MouseListener.
  • 41. Other Listeners
    • Many other listeners are available in Java.
    • For example: MouseMotionListiner, TextListener, WindowListener, and KeyListener.
    • Each of the listeners have a set of methods.
  • 42. The showStatus Method—General Format showStatus(String);
  • 43. The showStatus Method—Examples showStatus("Click here to Calculate"); showStatus("Invalid entry");