Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Having two WORKING inputs for a applet
Index -> Programming, Java -> Java Help
Goto page 1, 2  Next
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
xLockx




PostPosted: Fri Dec 30, 2005 1:40 am   Post subject: Having two WORKING inputs for a applet

Hey Guys - Here with another question im quite stumped... So heres my dilema I wanted to variables to add, subtract, multiply or divide depending on the buttons pushed. I got it all down pat for one variable but when I added two variables 'to the mix' it got weird on me. I thought just adding some labels, boxes, and duplicate code should handle it - as im just passing 2 variables and returning one variable a method ( I know its only one variable because a method can only return one). So the program runs except it completely disregards the second variable.

Any Ideas?

<Beggining of CODE>

// THE "FunMath" CLASS
//Thanks in Advance Compsci guys (and girls?) for all your help!
//Programmed by - Nick B.
import java.applet.Applet;
import java.awt.*;
//Class to output bus fare given age.
public class FunMath extends Applet
{
Label prompt,prompt2,result;//System.out.printlns of applets Very Happy
TextField input,input2,answer;//Fields for user nput.
int var1,var2;//Intigers that the user types in.
Button adds;
Button subtract;
Button multiply;
Button divide;
// sets up GUI components (just a reminder of what init is)
public void init()
{
prompt = new Label ("Type in first Variable");
input = new TextField (1);

prompt2 = new Label ("Type in second Variable");
input2 = new TextField (5);

//Buttons for basic mathamatical functions
adds = new Button("Add");
subtract = new Button("Subtract");
multiply = new Button("Multiply");
divide= new Button("Divide");

result = new Label ("The result is ");
answer = new TextField (15);

// Place label and text field on applet
add(prompt);
add(input);
add(prompt2);
add(input2);
add(result);
add(answer);
add(adds);
add(subtract);
add(multiply);
add(divide);

}//init method

//Respond to action of user's input

public boolean action(Event e, Object o)
{
//Now this is the part I THINK is messing with my program.
//Basically its always reading the first variable but completely disregard
//The second inputed variable and assigns it to 0.(like it was never entered).
var1 = Integer.parseInt(input.getText ());
var2 = Integer.parseInt(input.getText ());
if(e.target instanceof Button)
{
if(e.target == adds)
answer.setText (""+ Integer.toString (adds(var1,var2)));//ANSWER.SETTEXT its the BOX(side note for me to remeber what it means)
else if (e.target == subtract)
answer.setText ("" + Integer.toString(subtract(var1,var2)));
else if (e.target == multiply)
answer.setText (""+ Integer.toString (multiply(var1,var2)));
else if (e.target == divide)
answer.setText ("" + Integer.toString(divide(var1,var2)));
return true;
}
return true;
}


public int adds (int number, int number2)
{
return (number+number2);
}//adds

public int subtract (int number,int number2)
{
return (number-number2);
}//subtract

public int multiply (int number,int number2)
{
return (number*number2);
}//multiply


public int divide (int number,int number2)
{
return (number/number2);
}//divide
}//end of Fun with Math class

</Beggining of CODE>
Sponsor
Sponsor
Sponsor
sponsor
xLockx




PostPosted: Fri Dec 30, 2005 1:42 am   Post subject: (No subject)

Ah Darnit! I indented everything but for some reason the Copy and Paste didn't work - sorry guys - I know its supposed to be indented - and I did it properly :p but... ya didnt turn out that way apperently
wtd




PostPosted: Fri Dec 30, 2005 1:54 am   Post subject: (No subject)

You need to use code tags.
xLockx




PostPosted: Fri Dec 30, 2005 2:06 am   Post subject: (No subject)

I'm sorry... what is a code tag?
wtd




PostPosted: Fri Dec 30, 2005 3:00 am   Post subject: (No subject)

code:
[code]yada yada[/code]
xLockx




PostPosted: Fri Dec 30, 2005 12:56 pm   Post subject: (No subject)

My bad Razz thanks 'wtd'.
code:

// THE "FunMath" CLASS
//Thanks in Advance Compsci guys (and girls?) for all your help!
//Programmed by - Nick B.
   import java.applet.Applet;
   import java.awt.*;
//Class to output bus fare given age.
    public class FunMath extends Applet
   {
      Label prompt,prompt2,result;//System.out.printlns of applets :D
      TextField input,input2,answer;//Fields for user nput.
      int var1,var2;//Intigers that the user types in.
      Button adds;
      Button subtract;
      Button multiply;
      Button divide;
   // sets up GUI components (just a reminder of what init is)
       public void init()
      {
         prompt = new Label ("Type in first Variable");
         input = new TextField (1);
     
         prompt2 = new Label ("Type in second Variable");
         input2 = new TextField (5);
     
      //Buttons for basic mathamatical functions
         adds = new Button("Add");
         subtract = new Button("Subtract");
         multiply = new Button("Multiply");
         divide= new Button("Divide");
       
         result = new Label ("The result is ");
         answer = new TextField (15);
       
      // Place label and text field on applet
         add(prompt);
         add(input);
         add(prompt2);
         add(input2);
         add(result);
         add(answer);
         add(adds);
         add(subtract);
         add(multiply);
         add(divide);
     
      }//init method
   
   //Respond to action of user's input
   
       public boolean action(Event e, Object o)
      {
                //Now this is the part I THINK is messing with my program.
                //Basically its always reading the first variable but completely disregard
                //The second inputed variable and assigns it to 0.(like it was never entered).
         var1 = Integer.parseInt(input.getText ());
         var2 = Integer.parseInt(input.getText ());
         if(e.target instanceof Button)
         {
            if(e.target == adds)
               answer.setText (""+ Integer.toString (adds(var1,var2)));         
            else if (e.target == subtract)
               answer.setText ("" + Integer.toString(subtract(var1,var2)));
            else if (e.target == multiply)
               answer.setText (""+ Integer.toString (multiply(var1,var2)));
            else if (e.target == divide)
               answer.setText ("" + Integer.toString(divide(var1,var2)));
            return true;
         }       
         return true;                
      }
        
        
       public int adds (int number, int number2)
      {
         return (number+number2);
      }//adds
   
       public int subtract (int number,int number2)
      {
         return (number-number2);
      }//subtract
   
       public int multiply (int number,int number2)
      {
         return (number*number2);
      }//multiply
   
   
       public int divide (int number,int number2)
      {
         return (number/number2);
      }//divide
       
   }//End of program
wtd




PostPosted: Fri Dec 30, 2005 2:40 pm   Post subject: (No subject)

Which version of Java are you using?

I ask because you're using straight AWT rather than Swing, which I think is a bad idea.

Additionally, if you look up the documentation of the "action" method, it has been deprecated since JDK 1.1. You would be much better off using proper ActionListeners.
xLockx




PostPosted: Fri Dec 30, 2005 3:36 pm   Post subject: (No subject)

the reason why I am using action is because it is what I was taught - Action listeners do sound like a better idea - any ideas where I can learn about them? is it the same general concept... ect..? If I use action listeners would it correct my problem, I think it would.... I think the problem with my program is the fact it is simply 'identifying' the first input as var1, and not assinging a variable to var2 simply because it already 'picked up' / 'assigned a value'... Any suggestions with that regard - am I totally off base? :p

In regards to Java, I use JGrasp as my editor and - as far as I know the ladest version of Java Development Kit from www.java.sun.com.
Sponsor
Sponsor
Sponsor
sponsor
wtd




PostPosted: Fri Dec 30, 2005 5:25 pm   Post subject: (No subject)

You could make your code work as it is now. Try registering the object as its own action listener with:

code:
this.addActionListener(this);


Added to the "init" method.
xLockx




PostPosted: Fri Dec 30, 2005 6:18 pm   Post subject: (No subject)

Ok so you say
code:
this.addActionListener(this);
works when placed in the init method - It may be perhaps my placing or my lack of knowledge of action listners - but I assume 'this' would be the inputed variable, therefor I would need to add one for the second variable (as the first one is already identified with
code:
var1 = Integer.parseInt(input.getText ());
However wherever I add
code:
var2.addActionListener(var2);
I have the error 'int cannot be dereferenced' - this to my knowledge means that I have already refrenced or 'called' ( in 'laymans' terms) the variable - but infact I have not (as I deleted
code:
var2 = Integer.parseInt(input.getText ());
from the action method.

Thanks again for your help (in advanced of course)
wtd




PostPosted: Fri Dec 30, 2005 6:32 pm   Post subject: (No subject)

No. Try the code exactly as I wrote it.
xLockx




PostPosted: Fri Dec 30, 2005 6:48 pm   Post subject: (No subject)

code:
this.addActionListener(this)

Yeilds 'FunMath.java:19: cannot find symbol' Perhaps this is occuring because I only imported 'java.applet.Applet; & ava.awt.*;' I tried importing 'javax.swing.*; but it had no effect.
wtd




PostPosted: Fri Dec 30, 2005 6:57 pm   Post subject: (No subject)

Here's an imcomplete example of using Swing.

code:
import javax.swing.*;
import java.awt.event.*;

public class FunMath2 extends JApplet {
    private JLabel firstInputLabel;
    private JLabel secondInputLabel;
    private JLabel answerLabel;

    private JTextField firstInputField;
    private JTextField secondInputField;
    private JTextField answerField;

    private JButton addButton;
    private JButton subtractButton;
    private JButton multiplyButton;
    private JButton divideButton;

    public void init() {
        firstInputLabel = new JLabel("First");
        secondInputLabel = new JLabel("Second");
        answerLabel = new JLabel("Answer");

        firstInputField = new JTextField();
        secondInputField = new JTextField();
        answerField = new JTextField();

        addButton = new JButton("Add");
        subtractButton = new JButton("Subtract");
        multiplyButton = new JButton("Multiply");
        divideButton = new JButton("Divide");

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                answerLabel.setText(
                    Integer.toString(getFirstInputValue() +
                                     getSecondInputValue()));
            }
        });
    }

    public int getFirstInputValue() {
        return Integer.parseInt(firstInputValue.getText());
    }

    public int getSecondInputValue() {
        return Integer.parseInt(secondInputValue.getText());
    }
}
xLockx




PostPosted: Sat Dec 31, 2005 1:19 am   Post subject: (No subject)

Just need a bit of clarifcation - I'll write out what I FIRST had troubles with (because I only have used the Javax.swing.*; once before (really without knowing using JOptionPane)). (Perhaps others will read this post later or now - and have a bit of trouble and you can learn from my confusion)


So as many can see the Difference is (for example) instead of declaring firstInputLabel = new Label; its 'JLabel' firstInputLabel;(when using 'Swing' class).

Also similar for the initiate class - instead of firstInputLabel = new Label("First"); its firstInputLabel = new JLabel("First");(Not a big differece)
However the 'new' 'Swing' (in comparison to using AWT) Instead of having to add all the 'variables' - labels and buttons to the Applet the 'J' String class already does that. MUCH like JOption pane the AWT is actually
just OptionPane but when using 'javax.swing.*;' it makes everything alot eaiser - as it automatically applies everythign without having to add(x) it. (im hoping that explination made sense)


The main improvements to the program is using 'Action Listeners' instead of having to use the method
code:
public boolean action(Event e, Object o)


There is also a change - that I did not notice - perhaps anyone else reading (or mabey just me - but I was stumped) :p Some coders prefer to put their 'curly brackets' or '{ & }' right after a 'command' instead of on a new line ( I was first introduced to that today - with this program 'wtd' made - with a bit of 'research' I found it was quite common..) and what stumped me the most was why
code:
addButton.addActionListener(new ActionListener()
had no ');' on the end! and why there was a ); at the end of the block ( which is just a peice of code incased in { and } (and the portion inside the 'block' is called the scope for anyone wondering))

Anywho - to the main reason why im writing this post - when I added the following to complete the program (because 'wtd' started me of so well and nudged me in the right direction) it came up with a nice 'illegal start of expression 'error at compile... Now it may be me overlooking a simple objection but perhaps you could give it a look?

code:
        addButton.addActionListener(new ActionListener());
                   {
            public void actionPerformed(ActionEvent e)
                                 {
               answerLabel.setText(Integer.toString(getFirstInputValue() +  getSecondInputValue()));
             }
         }//end of add button.
                  
                  
                 subtractButton.subtractActionListener(new ActionListener());
                   {
            public void actionPerformed(ActionEvent e)
                                //block for action preformed
                                 {
                answerLabel.setText(Integer.toString(getFirstInputValue() -  getSecondInputValue()));
             }
         }//end of subtract button.
   
        
           multiplyButton.multiplyActionListener(new ActionListener());
                   {
            public void actionPerformed(ActionEvent e)
                                 {
                answerLabel.setText(Integer.toString(getFirstInputValue() *  getSecondInputValue()));
             }
         }//end of multiply button.
     
               
      divideButton.divideActionListener(new ActionListener());
                   {
            public void actionPerformed(ActionEvent e)
                                 {
                answerLabel.setText(Integer.toString(getFirstInputValue() /  getSecondInputValue()));
             }
         }//end of multiply button.
 
The second question I must ask - as it was unclear with the last post - is the 'Action Listener' AFTER the Init Method - or is it apart of it?

Thanks again 'wtd' for your quick aid and guidance!
wtd




PostPosted: Sat Dec 31, 2005 1:45 am   Post subject: (No subject)

code:
        addButton.addActionListener(new ActionListener());
         {
            public void actionPerformed(ActionEvent e)
             {
               answerLabel.setText(Integer.toString(getFirstInputValue() +  getSecondInputValue()));
             }
         }//end of add button.


Of course this causes errors. It's not valid Java code.

code:
new ActionListener() {
   ...
}


Creates an "anonymous inner class". The ActionListener interface specifies that the actionPerformed method has to be defined. That is what we do within the block.

code:
        addButton.addActionListener(new ActionListener()
         {
            public void actionPerformed(ActionEvent e)
             {
               answerLabel.setText(Integer.toString(getFirstInputValue() +  getSecondInputValue()));
             }
         });//end of add button.


Is the proper form.

And get rid of that trailing comment. It's bad form.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 2  [ 21 Posts ]
Goto page 1, 2  Next
Jump to:   


Style:  
Search: