/* The code used in the article is only a part of the source can be contacted by email me [email protected]*/
Some time ago just to help classmates with MFC wrote a calculator, now learn Java graphics development, try to water a calculator out. (can be said to be a water-no-water calculator, I feel that MFC is really useful)
Since is the design calculator, first of all must be to do a calculator interface come out, but face Java container of two kinds of layout, want to put button neat really is a relatively difficult thing, I directly use coordinates method map (the previous blog has introduced). This is the interface I designed.
Interface design is finished, the following will start to implement press the button input data. Then you need to use the event monitoring mechanism.
First you need to know how to get data,
// define a class with ActionListener as the interface Public class Implements ActionListener { publicvoid actionperformed (ActionEvent e) { = E.getactioncommand (); // Use this method to get the string represented by each button // ... }}
When you get to the string that the button represents, you need to do the next step based on the contents of the string, which can be used if. else or switch to do
Data section
1 if(FLAG1)2{//integer part, the integer part by a FLAG1 variable to determine whether the decimal point is written3A *= 10;4A = A + (Double) Integer.parseint (str);5s + =str;6 This. Text1.settext (s);7 //System.out.println (a);8 } 9 Else Ten{//number of decimal parts Onei++; AB = b + double.parsedouble (str)/Math.pow (10, i); -s + =str; - This. Text1.settext (s); the //System.out.println (b); -}
The symbol section can have a variable of type int, which is used to record what operator was entered, and finally, when the equal sign is clicked, then the value of the variable is calculated.
case "." : Flag1 = false ; //...
break ; case "+" : Flag1 = True ; Flag2 = 1;
//... break //.....
case "=" :
if (Flag2 = = 1 .... .
break ;
After defining this class, we just need to modify the method to modify the picture Calculator interface, how to modify it? is to create an object for the event listener class, and then add the object to the addActionListener () method of each button object.
Buttonlistener blist = new Buttonlistener ();
New JButton (); Button.addactionlistener (blist);
//.....
Run it and calculate a formula. Emmmmmmmmm ..... Did you find anything? The text box does not show the result?!! Think about what else is missing .... We didn't send the text box to the class we wrote! So, we need to write a construction method to pass in the text box object.
Public Buttonlistener (JTextField jtext) { this. Text1 = jtext; }
The front should be changed accordingly.
Button.addactionlistener (blist);
Well, let's run it again, can you calculate it? But it's just a simple calculator that can't be simpler, and then think about how you can make it better.
JAVA Graphics Development Calculator design (event monitoring mechanism)