Results 1 to 17 of 17
  1. #1
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default Help me on this code of Java swing

    I am beginner in Java and want to learn Java Swing . I have written this small program as GUI addition calculator. The code is..........


    Java Code:
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class win {
        
        public static void main(String args[]){
            JFrame frame = new addwin();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
            frame.show();
        }
        }
    class addwin extends JFrame{
        addwin()
        {      
            setSize(400,150);
            buttonpanel bp = new buttonpanel();
            Container cont = getContentPane();
            cont.add(bp);
        }
    }
    class buttonpanel extends JPanel{
        public buttonpanel(){
            JTextField num1 = new JTextField(25);
            num1.setText("0");
            JTextField num2 = new JTextField(25);
            num2.setText("0");
            JTextField result = new JTextField(25);
            JLabel lbl1 = new JLabel("Operand1");
            JLabel lbl2 = new JLabel("Operand2");
            JLabel res = new JLabel("Result");
            JButton Sum = new JButton("Add");
            JButton Exit = new JButton("Exit");
            add(lbl1);
            add(num1);
            add(lbl2);
            add(num2);
            add(res);
            add(result);
            add(Sum);
            add(Exit);
            clickbutton exit = new clickbutton("Exit");
            clickbutton sum = new clickbutton("Sum",num1.getText(),num2.getText());
            Exit.addActionListener(exit);
            Sum.addActionListener(sum);}
            
    }
    class clickbutton implements ActionListener {
        String action;
        int num1,num2,sum;
        clickbutton(String act){
            action = act;
            }
        clickbutton(String act,String n1,String n2){
            action = act;
            num1 = (new Integer(n1)).intValue();
            num2 = (new Integer(n2)).intValue();
            sum = num1 + num2;
        }
        public void actionPerformed(ActionEvent event){
            if(action == "Exit")
                System.exit(0);
            if(action == "Sum")
             [COLOR="Red"]//This is where I need help.[/COLOR]   
        }
    }

    In this program I created three textfields namely num1, num2 and result. the first two textfields will be used to input numbers and the third one is for displaying result. I am unable to code for the action of clicking of ADD/Sum button.
    Please help me on this code. You are allowed to suggest any changes in the above code.

    Thanks.......

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Please look here for help on a similar problem: coding-newbie-please-help

    Also, with this:
    Java Code:
     if(action == "Sum")
    you'll not want to compare Strings using == but rather using the equals or equalsIgnoreCase method. Also make it a habit of enclosing all if blocks, all loops, and all blocks in general in curly braces, even if it's only one statement long. Also, what is "action"? I think that you mean to get the actionCommand from your event object, correct?

    so to summarize, do this:
    Java Code:
            String action = event.getActionCommand();
            if (action.equals("Exit")) {
                System.exit(0);
            }
            else if (action.equals("Sum")) {
               // see my suggestions in the link above.
            }
    Much luck!

  3. #3
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    You are allowed to suggest any changes in the above code.
    always worries me

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    A suggestion:
    For this: (new Integer(n1)).intValue();

    See the Integer.parseInt() method.

  5. #5
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    Java Code:
    public void actionPerformed(ActionEvent event){
            if(action == "Exit")
                System.exit(0);
            if(action == "Sum")
    watch your String comparisons, String is an object not a primitive type (like Furable said)
    Last edited by al_Marshy_1981; 10-10-2010 at 03:25 AM. Reason: just acknowledgint furables post did not see it

  6. #6
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default

    Guys I want the solution for displaying the result of the addition of two numbers into the third textbox. string is not my problem. My problem is that I am unable to code the clickEvent for the ADD/Sum button that will place the result in the third TextBox ("result"). "Exit" button is working good....................

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    Quote Originally Posted by gauravfzd View Post
    Guys I want the solution for displaying the result of the addition of two numbers into the third textbox. string is not my problem.
    No, the String issue is not your obvious problem, but nevertheless, it is an error in your code that will bite you if you don't correct it. Make no mistake, it is an error whether you see it or not.

    My problem is that I am unable to code the clickEvent for the ADD/Sum button that will place the result in the third TextBox ("result"). "Exit" button is working good....................
    Have you looked at my link regarding a solution that I provided in the first response to your thread? Please look it over as it gives the solution for this. If it confuses you, please post your questions for clarification.

    Luck.

  8. #8
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default

    Quote Originally Posted by Fubarable View Post
    Have you looked at my link regarding a solution that I provided in the first response to your thread? Please look it over as it gives the solution for this. If it confuses you, please post your questions for clarification.

    Luck.
    The code You referred is applied to Applet in which everything is done in one class only, but in my case there is no Applet used. In my code there are 3 classes plus a class with main method. I am unable to use a method of an object in a class where as the object is declared in other class

  9. #9
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    You need to get a reference to the class object with the method in the class where you want to call that method. There are several ways to do that.
    Pass a reference in the constructor.
    Call a set method with the reference and save the reference.
    Call a get method to get the reference from the other class.

  10. #10
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default

    Hi Norm can you show me how pass the reference. I tried to pass the reference in ActionListener class but my code was still not working. May be my method was wrong. so tell me how to pass the reference of textfield in the constructor of "clickbutton class and to use its setText method.......

    Thanks....

  11. #11
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    how to pass the reference of textfield in the constructor
    Say aTF is a reference to a text field.
    Define a construtor to a class as:
    class AClass(JTextField tf) { // Constructor taking a JTextfield

    // Code here saves tf locally for use in this class
    ...
    }

    then pass it when creating a new instance of the class:
    AClass aClss = new AClass(aTF); // pass a reference via a constructor

  12. #12
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default

    nothing is working out. I also used constructor to solve this problem. Can you please modify the clickButton class and post the code ?..................

  13. #13
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Question Program updated

    Guys I have updated the above program but my problem is still not solved...........


    Java Code:
    import java.awt.event.*;
    import javax.swing.*;
    public class win1 extends JFrame{
        JTextField txt1,txt2,result;
        JLabel lbl1,lbl2,lblres,lbl3;
        win1(){
        JPanel panel = new JPanel();
        JTextField txt1 = new JTextField(25);
        JTextField txt2 = new JTextField(25);
        JLabel lbl1 = new JLabel("A");
        JLabel lbl2 = new JLabel("B");
        JLabel lblres = new JLabel("Result");
        JTextField result = new JTextField(25);
        JButton Sum = new JButton("Add");
        JButton Exit = new JButton("Exit");
        panel.add(lbl1); panel.add(txt1); panel.add(lbl2); panel.add(txt2);
        panel.add(lblres);  panel.add(result);
        Sum.addActionListener(new addclick());
        Exit.addActionListener(new exit());
        panel.add(Sum);
        panel.add(Exit);
        
        add(panel);}
        public static void main(String args[]){
            JFrame frame = new win1();
            frame.setSize(400, 300);
            frame.setVisible(true);
        }
        class addclick implements ActionListener {
            String action, s;
            int num1,num2,sum;
            public void actionPerformed(ActionEvent event){
                
                    String s1 = txt1.getText();
                    String s2 = txt2.getText();
                    num1 = Integer.parseInt(s1);
                    num2 = Integer.parseInt(s2);
                    sum = num1 + num2;
                    s = String.valueOf(sum);
                    result.setText(s);
                    }
        }
        class exit implements ActionListener {
            public void actionPerformed(ActionEvent event){
                System.exit(0);
            }
        }
    }

    Add/sum button is still not working .............
    Any Suggestion/Correction/Modification ?.......:

  14. #14
    al_Marshy_1981 is offline Senior Member
    Join Date
    Feb 2010
    Location
    Waterford, Ireland
    Posts
    748
    Rep Power
    5

    Default

    take a look at what you are doing inside the win1 constructor, does this code even compile?

  15. #15
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Default

    Yeah the code compiled, I can see the GUI window with three TextBoxes, three Labels and two Buttons. Clicking of Exit button is working fine. Clicking of Sum/Add button does nothing except some red coloured warning/error under the console tab of Eclipse IDE that are given below:

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at win1$addclick.actionPerformed(win1.java:34)
    at javax.swing.AbstractButton.fireActionPerformed(Unk nown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed (Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseRe leased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent( Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(U nknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unkno wn Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(U nknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  16. #16
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    You've got a problem where a variable in the constructor "shadows" a variable in the class. To wit:

    Java Code:
    public class Win1 extends JFrame {
       JTextField txt1, txt2, result;
       JLabel lbl1, lbl2, lblres, lbl3;
     
       Win1() {
          JPanel panel = new JPanel();
          JTextField txt1 = new JTextField(25);
          JTextField txt2 = new JTextField(25);
    Since you're re-declaring txt1 and txt2 in the constructor these variables are completely distinct from the txt1 and txt2 variables declared in the class, and since you are initializing only the ones declared in the constructor (and only visible from within the constructor), the variables declared in the class are never initialized and are null.

    Solution: don't redeclare the variables in the class but rather use the class fields. So, not this:
    Java Code:
    public class Win1 extends JFrame {
       JTextField txt1, txt2, result;
       JLabel lbl1, lbl2, lblres, lbl3;
     
       Win1() {
          JPanel panel = new JPanel();
          JTextField txt1 = new JTextField(25);
          JTextField txt2 = new JTextField(25);

    But instead to this:
    Java Code:
    public class Win1 extends JFrame {
       JTextField txt1, txt2, result;
       JLabel lbl1, lbl2, lblres, lbl3;
     
       Win1() {
          JPanel panel = new JPanel();
          txt1 = new JTextField(25); // [color="red"] *** see the difference? ***[/color]
          txt2 = new JTextField(25); // [color="red"] *** see the difference? ***[/color]

  17. #17
    gauravfzd's Avatar
    gauravfzd is offline Member
    Join Date
    Oct 2010
    Location
    India
    Posts
    72
    Rep Power
    0

    Thumbs up THANKS TO ALL and FUBARABLE

    Thank you veryyyyyyyyyyy much Fubarable My code is working now and my problem is solved finally. ............................


    THANKS YOU ALL for YOUR REPLIES..........:D

    one more thing, how to declare this thread as solved?.....

Similar Threads

  1. Convert THE APPLET CODE TO SWING USING JPANEL
    By jammyjamsticy in forum AWT / Swing
    Replies: 2
    Last Post: 12-22-2011, 09:16 AM
  2. Code Customiser on Swing Table
    By quddusaliquddus in forum New To Java
    Replies: 6
    Last Post: 09-24-2009, 06:29 PM
  3. EventHandling code for Swing application
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 12-07-2007, 12:06 PM
  4. code for making a java swing program a demo verson
    By fakhruddin in forum AWT / Swing
    Replies: 1
    Last Post: 11-27-2007, 08:54 PM
  5. jdbc/ swing code problem
    By sami in forum Advanced Java
    Replies: 1
    Last Post: 08-13-2007, 02:26 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •