Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Action Listener

  1. #1
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Action Listener

    host_name.addActionListener(new HostnameListener());
     
    private class HostnameListener implements ActionListener
        {
     
          public void actionPerformed (ActionEvent event)
          {
     
            hname = host_name.getText();
            textArea1.append(hname + newline);
            host_name.selectAll();
            textArea1.setCaretPosition(textArea1.getDocument().getLength());
            System.out.println(hname);
           // host_name.setText(hname);
          }
        }
    The variable in the ActionListener is updated but when I print the variable outside the ActionListener, it has not been updated.

    I don't know why
    Pls help
    Last edited by helloworld922; May 29th, 2010 at 03:00 PM. Reason: please use [code] tags


  2. #2
    Member Darryl.Burke's Avatar
    Join Date
    Mar 2010
    Location
    Madgaon, Goa, India
    Posts
    494
    Thanks
    8
    Thanked 48 Times in 46 Posts

    Default Re: Action Listener

    To get better help sooner, post a SSCCE* that demonstrates the problem.

    * SSCCE : Java Glossary

    db

  3. #3
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Action Listener

    please see a standalone part of my code

    hname and p_number are variables whose values do not seem updated outside the respective action listeners. perhaps, i have made some basic mistake. please help.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
     
    public class PrimaryInterface extends JFrame{
        public static String hname;
        public static String pnumber;
        public static Integer p_port;
     
        JPanel jp1 = new JPanel();
        JLabel h_name = new JLabel("");
        JLabel p_number = new JLabel("");
     
        private static JTextField host_name = new JTextField(26);
        private static JTextArea textArea1 = new JTextArea(5, 20);
        private static JTextField port_number = new JTextField(16);
        private static JTextArea textArea2 = new JTextArea(5, 20);
        private static String newline = "\n";
     
     
        public PrimaryInterface()
    	{
              h_name.setText ("Enter Host Name");
              p_number.setText ("Enter Port Number");
              jp1.add(host_name);
              jp1.add(port_number);
              jp1.add(h_name);
              jp1.add(p_number);
     
     
          host_name.addActionListener(new HostnameListener());
          port_number.addActionListener(new PortnumberListener());
     
          System.out.println("returned value after action listener" + hname);
          System.out.println("returned value after action listener" + p_number);
     
             add(jp1);
        }
      private class HostnameListener implements ActionListener
        {
     
          public void actionPerformed (ActionEvent event)
          {
     
            hname = host_name.getText();
            textArea1.append(hname + newline);
            host_name.selectAll();
            textArea1.setCaretPosition(textArea1.getDocument().getLength());
            System.out.println(" inside action listener" +hname);
     
          }
        }
     
       private class PortnumberListener implements ActionListener
       {
           public void actionPerformed(ActionEvent e)
           {
     
            pnumber = port_number.getText();
            textArea2.append(hname + newline);
            port_number.selectAll();
            textArea2.setCaretPosition(textArea2.getDocument().getLength());
            System.out.println(" inside action listener" + pnumber);
            p_port = Integer.parseInt(pnumber);
     
             Socket CalcSocket = null;
     
         try
          {
             System.out.println("reached here first"+ hname +p_port);
             CalcSocket        = new Socket(hname, p_port);
             PrintStream outStream    = new PrintStream(CalcSocket.getOutputStream());
     
             DataInputStream inStream = new DataInputStream(CalcSocket.getInputStream());
     
             StringBuffer buf = new StringBuffer(50);
     
             int aChar;
             String fromServer;
     
             System.out.println("reached here"+ hname +p_port);
     
            while ((fromServer = inStream.readLine()) != null)
             {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Bye"))
                    break;
                while ((aChar = System.in.read()) != '\n')
                {
                   buf.append((char)aChar);
                }
                System.out.println("Client: " + buf);
                outStream.println(buf.toString());
                outStream.flush();
                buf.setLength(0);
             }
     
             outStream.close();
             inStream.close();
             CalcSocket.close();
             System.exit(0);
          }
          catch (UnknownHostException e1)
          {
             System.err.println("Trying to connect to unknown host: " + e1);
          }
          catch (Exception e2)
          {
             System.err.println("Exception:  " + e2);
          }
     
           }
       }
     
      public static void main(String args[]) {
                    PrimaryInterface p_interface = new PrimaryInterface();
                    p_interface.setTitle(" Check connection to server ");
    		p_interface.setSize(241, 217);
    		p_interface.pack();
    		p_interface.setLocation(400, 250);
    		p_interface.setVisible(true);
    		p_interface.setResizable(false);
     
      }
    }
    Last edited by helloworld922; May 29th, 2010 at 03:00 PM. Reason: please use [code] tags

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Action Listener

    The variable in the ActionListener
    Which variable?
    Can you post the println() output so we can see how the code executed? And where the error occurred.

    It'd help if you'd mark your code with comments like:
    //<<<<<<<<<<<<<<<<<<<<< Here its set <<<<<<<<<<<

    and
    //<<<<<<<<<<<<<<<<<<<<< HERE it isn't

  5. #5
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Action Listener

    the variables are hname and p_number. The updates to the variables inside the action listener are not visible outside. I have commented the code in those places...
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
     
    public class PrimaryInterface extends JFrame{
     
    // Declaration of the variables
        public static String hname;
        public static String pnumber;
        public static Integer p_port;
     
        JPanel jp1 = new JPanel();
        JLabel h_name = new JLabel("");
        JLabel p_number = new JLabel("");
     
        private static JTextField host_name = new JTextField(26);
        private static JTextArea textArea1 = new JTextArea(5, 20);
        private static JTextField port_number = new JTextField(16);
        private static JTextArea textArea2 = new JTextArea(5, 20);
        private static String newline = "\n";
     
     
        public PrimaryInterface()
    	{
              h_name.setText ("Enter Host Name");
              p_number.setText ("Enter Port Number");
              jp1.add(host_name);
              jp1.add(port_number);
              jp1.add(h_name);
              jp1.add(p_number);
     
     // Action listeners to read in data entered by user in the JTextFields for hname and p_number
     
          host_name.addActionListener(new HostnameListener());
          port_number.addActionListener(new PortnumberListener());
     
    // These are the output values of hname and p_number outside the action listener
    // <<<<<<<<<<<<<<<<<<<<< Here the o/p is null for both hname and p_number>>>>>>>>>>>>>>>>>>>
     
          System.out.println("returned value after action listener" + hname);
          System.out.println("returned value after action listener" + p_number);
     
             add(jp1);
        }
      private class HostnameListener implements ActionListener
        {
     
          public void actionPerformed (ActionEvent event)
          {
     
            hname = host_name.getText();
            textArea1.append(hname + newline);
            host_name.selectAll();
            textArea1.setCaretPosition(textArea1.getDocument().getLength());
     
    //<<<<<<<<<<<<<<<<< Here  the println o/p is correct >>>>>>>>>>>>>>>>>>>>>>
     
            System.out.println(" inside action listener" +hname);
     
          }
        }
     
       private class PortnumberListener implements ActionListener
       {
           public void actionPerformed(ActionEvent e)
           {
     
            pnumber = port_number.getText();
            textArea2.append(hname + newline);
            port_number.selectAll();
            textArea2.setCaretPosition(textArea2.getDocument().getLength());
     
    //<<<<<<<<<<<<<<<<< Here  the println o/p is correct >>>>>>>>>>>>>>>>>>>>>> 
     
            System.out.println(" inside action listener" + pnumber);
            p_port = Integer.parseInt(pnumber);
     
             Socket CalcSocket = null;
     
         try
          {
             System.out.println("reached here first"+ hname +p_port);
             CalcSocket        = new Socket(hname, p_port);
             PrintStream outStream    = new PrintStream(CalcSocket.getOutputStream());
     
             DataInputStream inStream = new DataInputStream(CalcSocket.getInputStream());
     
             StringBuffer buf = new StringBuffer(50);
     
             int aChar;
             String fromServer;
     
             System.out.println("reached here"+ hname +p_port);
     
            while ((fromServer = inStream.readLine()) != null)
             {
                System.out.println("Server: " + fromServer);
                if (fromServer.equals("Bye"))
                    break;
                while ((aChar = System.in.read()) != '\n')
                {
                   buf.append((char)aChar);
                }
                System.out.println("Client: " + buf);
                outStream.println(buf.toString());
                outStream.flush();
                buf.setLength(0);
             }
     
             outStream.close();
             inStream.close();
             CalcSocket.close();
             System.exit(0);
          }
          catch (UnknownHostException e1)
          {
             System.err.println("Trying to connect to unknown host: " + e1);
          }
          catch (Exception e2)
          {
             System.err.println("Exception:  " + e2);
          }
     
           }
       }
     
      public static void main(String args[]) {
                    PrimaryInterface p_interface = new PrimaryInterface();
                    p_interface.setTitle(" Check connection to server ");
    		p_interface.setSize(241, 217);
    		p_interface.pack();
    		p_interface.setLocation(400, 250);
    		p_interface.setVisible(true);
    		p_interface.setResizable(false);
     
      }
    }
    Last edited by helloworld922; May 29th, 2010 at 03:01 PM. Reason: please use [code] tags

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Action Listener

    Try adding some println() statements to the code that show where it is executing and when.

    I don't see where the code sets the variables before you show them. The listener code is not called when the listeners are added to the object. The listener will be called when there is an action event on the object.

  7. #7
    Junior Member
    Join Date
    May 2010
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Action Listener

    thank you. does that mean the variables that are set inside the Action listener cannot be used outside the Action listener for any further purpose ? for example, I wanted to use the values of hname and p_number after the data entry has been done by the user (inside the Action Listener) in order to set up connection with the server, but I guess that is not possible. Seems like all further actions with hname and p_number's values need to be used within the action listener. Is that right ?

  8. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,042
    Thanks
    63
    Thanked 2,708 Times in 2,658 Posts

    Default Re: Action Listener

    No. The values in the variables are available to the rest of the code. Its a question of how to tell the code that wants to use the data that it is available. Perhaps you could start a Thread in the listener to do the connection when it gets the data. Its best to NOT do too much in a listener as the listener is using the GUI thread which means that your Menu items etc won't get responses while your code is using the GUIs thread.

    The sequence of events: You create some text fields and add action listeners and then the user enters something in a text field. This triggers an action event that causes your listener to be called. The action listener gets the data from the text field and stores it in the variables you're looking at. Now the data in the variable is available to the rest of the program.
    Last edited by Norm; May 29th, 2010 at 10:52 AM.

Similar Threads

  1. Beginner Help (Action Listener)
    By gradstudent in forum AWT / Java Swing
    Replies: 2
    Last Post: April 30th, 2010, 10:26 AM
  2. Action Listener
    By kray66 in forum AWT / Java Swing
    Replies: 2
    Last Post: April 19th, 2010, 03:26 PM
  3. Problem with Action Listener
    By JonoScho in forum AWT / Java Swing
    Replies: 4
    Last Post: March 19th, 2010, 01:03 AM
  4. Key listener help
    By airsim15 in forum AWT / Java Swing
    Replies: 2
    Last Post: December 13th, 2009, 03:15 PM
  5. Need Help Action Listener....
    By vhizent23 in forum AWT / Java Swing
    Replies: 2
    Last Post: October 9th, 2009, 01:46 PM