Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Making Your Knowledge Add Up

java



+ Font mai mare | - Font mai mic



Making Your Knowledge Add Up

Most of the programs you created during the first 20 hours of this book were short tutorials intended to demonstrate a specific aspect of Java programming. These types of programs can be useful when you're introduced to how a language works, but they also can be instructive in developing more sophisticated programs.



For the concluding hour of this 24-hour span, you'll create a Java class that works as a simple calculator. This project gives you a chance to design a graphical user interface, respond to user mouse clicks, and develop the calculator so that it can be used in any Java applet or application.

The following topics will be covered during this hour:

Adding components to a window

Arranging components with a layout manager

Putting one grid layout inside another

Adding components to containers

Responding to action events

Reading information from a text field

Sending information to a text field

Using your own classes in a Java program

A Calculating Class

The MiniCalc project will be a simple calculator that can handle addition, subtraction, multiplication, and division. In addition to numeric buttons from 0 to 9, there will be a clear button (C), a change sign key (+/-), and a decimal point key. Instead of creating the calculator as an applet, you will create it as a class called MiniCalc that is a subclass of Panel.

The advantage of making MiniCalc its own class is that you will be able to use it in other programs. If you design the calculator as an applet, it will be difficult to use in other programs without making major changes. Once you have the MiniCalc class working the way that you want it to, using it in a new program is as easy as using any other object.

The MiniCalc project can be broken down into the following five steps:

Create the components that will make up the calculator interface.

2.
Put those components into containers and set them up to send out action events.

3.
Lay out those containers.

4.
Keep track of mouse clicks on the components.

5.
Change the calculator display area based on which components were clicked.

Creating the Interface

The first thing to do is develop the user interface of the MiniCalc class. Figure 24.1 shows what the calculator will look like when you're done. It's displayed at this point to give you a better feel for the steps that you'll be taking to create it.

When you are trying to create an attractive user interface for a program, one of the best layout managers to use is the GridLayout class. This manager enables you to organize components into a grid. When you use GridLayout, you decide how many rows and columns the grid should have; each component in the grid is given the same amount of space as the other components.

Figure 24.1. <../art/24/24tja01.jpg> A calculator implemented as a Java class and displayed on an applet window.

The MiniCalc class uses GridLayout to organize components into a grid with six rows and one column. Each of these components is a Panel object. Figure 24.2 shows this grid superimposed over a calculator so you can see how it is arranged. The Panel objects have the names row1 through row6. When you add these Panel objects with the add() method, they automatically are given the same amount of space based on the layout manager being used.

Figure 24.2. <../art/24/24tja02.jpg> Six Panel objects arranged in horizontal rows.

These six Panel objects will be subdivided into their own grids using their own GridLayout objects. Each Panel will be organized as a grid four columns wide and one row tall. When components are added to each Panel, they will get the same amount of space within their row. Figure 24.3 shows how the row2 object is subdivided into a four-by-one grid. Note how each of the buttons has the same size because of the use of GridLayout.

Figure 24.3. <../art/24/24tja03.jpg> One of the rows subdivided into four vertical columns.

Using Panel objects is a good way to make part of a window follow one set of layout rules and other parts work differently. If you had used only one GridLayout class on this project, every component would have exactly the same size--even the text field where answers are displayed.

The first half of the MiniCalc class contains statements to create all of the user interface components that will be used in the program. These statements are located right after the class statement along with other variables that are needed. After all of the components have been created, they will be added to the proper place. The large Panel objects shown as rows in Figure 24.1 will be added to the main window of MiniCalc itself. Every other component will be added to one of these Panel objects.

Create a new file in your word processor called MiniCalc.java. Enter Listing 24.1 and save the file.

Listing 24.1. The first half of MiniCalc.java.

1: import java.awt.*;

2: import java.awt.event.*;

3:

4: public class MiniCalc extends Panel implements ActionListener


Lines 5-34 create several variables and numerous components--buttons, six panels, a text field, and a canvas. The constructor method MiniCalc() in Lines 36-104 will be called whenever a program creates a MiniCalc object with a statement such as the following:

MiniCalc calculator = new MiniCalc();

The constructor method uses GridLayout objects to define the way components will be arranged, first for the entire MiniCalc window and then for each of the specific rows of the window.

Before you add a component to a row, you must set it up to send out action events. These events enable the program to respond when a user interacts with the component--by clicking a button, for example. You set up these events by using the addActionListener() method of each component.

The components are first added to each row, starting with row1. When that's done, the entire row is added to the MiniCalc window. This is all the code that's needed to create the user interface.

Responding to User Events

To make the calculator calculate, you need to make the program respond to mouse clicks on the buttons. Whenever a user clicks on a button that has been set up as a listener to action events, the actionPerformed() method automatically is called. Information about the user's action is stored as an ActionEvent object, and the actionPerformed() method responds to the action. All action events are received by the actionPerformed() method of MiniCalc itself.

Return to your word processor and insert a blank line at the bottom of the MiniCalc.java file. Continue by entering Listing 24.2, making sure to save the file when you're done.

Listing 24.2. The last half of MiniCalc.java.

1: public void actionPerformed(ActionEvent event)

9: else switch ( keyHit.charAt(0) )

addToDisplay(keyHit);

}

}

public void solveProblem()

clearDisplay();

addToDisplay('' + storedValue);

clearNext = true;

}

public void addToDisplay(String keyHit) else

newText += keyHit;

int newLength = newText.length();

display.setText(newText);

}

public void clearDisplay()

public float getValue(String argument)


The following statements from this part of the program might be unfamiliar to you:

Line 2: This line calls the getActionCommand() method of the event object and stores the response in the String variable keyHit. The value stored in this variable is the label of the key that was clicked.

Line 9: This switch statement converts the value stored in keyHit to a single character before using it in case statements. This conversion must be done because case can handle characters, but it cannot handle strings. The charAt() method returns a single character at the position indicated by the argument. represents the first character, the second, and so on.

Line 19: The storedValue variable keeps track of the first half of any operations. For example, if you're using the calculator to work out the equation 12 plus 10, storedValue would equal 12.

Line 20: The operator variable, used here and many places elsewhere, stores the most recent operator key that was pressed: +, -, *, or /. The variable has the value 0 when no operators have been pressed or the current problem has been cleared out with the C or = keys.

Line 21: The Boolean variable clearNext indicates when the calculator display should be cleared out after the next key is pressed.

Lines 74-76: These lines make sure that a user cannot enter more than one decimal point on a number.

Solving Problems

Several methods have been created in the MiniCalc class to handle specific tasks. The solveProblem() method in Lines 48-70 is called whenever the calculator display should be updated with the answer to a calculation. This occurs when the = key is pressed. The addToDisplay() method in Lines 72-81 is used to add another digit to the number that is being shown in the calculator's display area. The clearDisplay() method in Lines 83-85 clears out the calculator's display area so that the user can enter a new number. The last special method is the getValue() method in Lines 87-92. This method returns a float value, as shown on Line 91. This method converts the text shown in the calculator's display window into a floating-point number.

Trying Out the Program

Save and compile the MiniCalc class file. Before you can try it out, you need to create a MiniCalc object as a component in an applet and add it in the same way any component would be added. Create a new file with your word processor and save it as CalcApplet.java. Enter Listing 24.3 into the file.

Listing 24.3. The full text of CalcApplet.java.

1: import java.awt.*;

2:

3: public class CalcApplet extends java.applet.Applet


As you can see, the applet doesn't need to do very much because the MiniCalc class does all of its own work. Save and compile this file.

To see the CalcApplet program on a Web page, create another file with the name CalcApplet.html. Enter Listing 24.4 into the file.

Listing 24.4. The full text of CalcApplet.html.

1: <applet code='CalcApplet.class' height=200 width=200>

2: </applet>


Use the appletviewer tool or a Web browser that can handle Java, and take a look at the CalcApplet.html page.

Summary

Once you've gotten the MiniCalc class to work in conjunction with an applet, take a long look over the program to determine what's being done at each point in the program. The MiniCalc project is a good example of how graphical programs can be written with a small amount of programming in Java. In less than 200 lines, you can implement a working calculator that handles the basic mathematic operations.

The purpose of Teach Yourself Java 1.1 Programming in 24 Hours is to make you comfortable with the concepts of programming and confident in your ability to write your own applets and applications. Java has an approach that is somewhat difficult to master. (Feel free to scratch out the word 'somewhat' in the previous sentence if it's a gross misstatement of the truth.)

If it's any consolation, as you build experience in Java, you're building experience that will be increasingly relevant in the coming years. If you become knowledgeable in object-oriented programming and distributed network computing, the MiniCalc program could be useful--there's no better afternoon for a millionaire than projecting the rate of return on your no-load mutual funds using a Java program you wrote!

You ought to read the appendixes to find out about this book's Web site, other Java books from Sams.net, and other useful information. Even if you don't, there's one last bit of bad news to deliver. Your 24 hours are up.

At the conclusion of this hour, you are contractually obligated to learn no more about Java programming. You cannot use Internet discussion groups such as comp.lang.java.misc to talk to other people who share your skills. You must not look for Java user groups in your area. You cannot search employment World Wide Web sites such as <https://www.careerpath.com> for companies that seek Java programmers. Under no circumstances should you send electronic mail to the author of this book at rogers@prefect.com with questions, comments, or criticisms in regard to the past 24 hours.

The only legally permissible way for you to continue building your skills as a Java programmer is to read Teach Yourself Java 1.1 Programming in 21 Days or one of the other excellent Java-related books from Sams.net Publishing. If you are caught violating these prohibitions and learning more about Java without spending another cent of your money, there's really only one thing left to be said

I lied. There's no current law in any jurisdiction that forces you to Teach Yourself Everything only by reading our books. You are free to learn freely. My apologiesif I sell enough copies of this book, my name is entered into a drawing with other top Sams.net authors to win special prizes.

My heart's set on a banana-yellow Schwinn Sting-Ray bicycle.

--Rogers Cadenhead

Q&A

Q Does a layout manager have to be specified for a program?

A
If one is not used, components will be arranged on an applet window or other container in the same way words are typed onto a page--left to right until there's no more room and then down to the next line. This occurs because the default layout manager, FlowLayout, is used if no other manager is specified.

Q The CalcApplet program looks different on my version of Netscape Navigator than it does on the appletviewer tool. The most noticeable differences are the C and = buttons, which are thinner on Navigator. Why is this?

A
Because Java is a language that is presented on many different platforms, some graphical elements will vary depending on the software or operating system being used. Your programs should be presentable on any implementation of Java, but if you're creating a complicated program that arranges numerous components and other visual elements, it's worthwhile to test it on several different systems and Web browsers.

Quiz

To calculate your level of knowledge about this hour's subjects, answer the following questions.

Questions

What type of class do you use to specify how components will be arranged in a program?

(a)
Arranger
(b)
Composer
(c)
LayoutManager

2.
What type of method is used to set up all the variables and components that need to be displayed with the
MiniCalc class?

(a)
an
init() method
(b) a constructor method
(c) a destructor method

3.
What type of variable is used to store calculator results?

(a)
String
(b)
int
(c) float

Answers

c. You can use layout styles such as GridLayout BorderLayout, and GridBagLayout.

2. b. Any method that is called with a
new statement during variable creation is a constructor method. You can have more than one constructor if the number and type of arguments used with each constructor are different.

3. c. Because there's a decimal key on a calculator, you must use the
float variable type instead of some other numeric type such as int

Activities

If you'd like to teach yourself even more Java programming in hours 24 and beyond, do the following activities:

Add a square root button to the MiniCalc class that will display the square root of the currently displayed number.

Visit the Gamelan Web site at <https://www.gamelan.com> to see some other calculators that have been written using Java. Look over any available source files and compare them with the MiniCalc source file.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 576
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved