Results 1 to 18 of 18
  1. #1
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Post ActionListener how to get variable.

    Hi. I'm new in java and trying to learn it since 4 weeks. I did a project - please see code below:

    Java Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.Statement;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Date;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;
    
    public class Rozliczenie extends JFrame 
    {
        private JButton b1;
        private JButton b2;
        private JTextField t;
        public JTextField t1;
        public JComboBox pracownik;
        public JComboBox status;
        private TextArea pole1;
            
        public Rozliczenie() 
        {
            setTitle("ROZLICZNIK");
            setLayout(null);
            setLocation(280, 200);                      
            setVisible(true);
            getContentPane().setBackground(Color.gray);
            
            JLabel label1 = new JLabel();
            label1.setBounds(650,10,80,80);
            add(label1);
            label1.setIcon(new ImageIcon("logo.gif"));
    
            JLabel tytul= new JLabel("Rozliczenie");
            tytul.setBounds(310,20,400,30);
            tytul.setForeground (Color.white);
            add(tytul);
            add(t=new JTextField(8));
            
            JLabel label2 = new JLabel("Pracownik");
            label2.setBounds(120,130,80,30);
            label2.setForeground (Color.white);
            add(label2);
                            
            b1=new JButton("Zatwierdź");
            b1.setBounds(280,305,150,30);
            b1.setBackground (Color.green);
            add(b1);
            
            b2=new JButton("Powrót");
            b2.setBounds( 280,355,150,30);
            b2.setBackground (Color.green);
            add(b2);
            
            final JTextField t1=new JTextField("Data");
            t1.setBounds(360,170,150,30);
            t1.setBackground (Color.lightGray);
            DateFormat d= new SimpleDateFormat("dd.MMMMM ");
            Date today = Calendar.getInstance().getTime();        
            String wyswietlDate = d.format(today);
            t1.setText("   " + wyswietlDate); 
            t1.setEditable(false);
            add(t1);
            String kalendarz=t1.getText();
            
            JLabel label3 = new JLabel("Data");
            label3.setBounds(415,130,80,30);
            label3.setForeground (Color.white);
            add(label3);
            
            JLabel label4 = new JLabel("Status");
            label4.setBounds(585,130,80,30);
            label4.setForeground (Color.white);
            add(label4);
    
            pracownik = new JComboBox();
            Connection c = null;
            Statement stmt = null;
            try
            {
                Class.forName("org.postgresql.Driver");
                c = DriverManager.getConnection("jdbc:postgresql://localhost:5432/jacek","jacek", "zuza");
                c.setAutoCommit(false);
                System.out.println("Dostęp do bazy danych \n");
     
                stmt = c.createStatement();
                ResultSet rs = stmt.executeQuery( "select id_pracownika,nazwisko,imie from pracownicy;" );
                        pracownik.addItem(" \n");        
                while ( rs.next() ) 
                {
                        pracownik.addItem(rs.getInt("id_pracownika" )+ " "  + rs.getString(   "imie") + " " + rs.getString("nazwisko"));
                }    
                rs.close();
                stmt.close();
                c.close();
            }    
            
            catch ( Exception e )
            {
                System.err.println( e.getClass().getName()+": "+ e.getMessage() );
                System.exit(0);
            }        
            pracownik.setBounds(60,170,250,30);
            pracownik.setBackground(Color.lightGray);
            pracownik.addActionListener(new MyPracListener());
            add(pracownik);
            MyPracListener mpl = new MyPracListener();
            System.out.println(" " +mpl.prac);
    
                    
            String statusy []={" ","obecny","nieobecny","urlop","chory","dzien_wolny"};
            status = new JComboBox(statusy);
            status.setBounds(565,170,120,30);
            status.setBackground(Color.lightGray);
            status.setSelectedIndex(0);
            status.addActionListener(new MyStatListener());
            add(status);
            MyStatListener msl = new MyStatListener();
            System.out.println(" " + msl.stat);
            
            
            
            b1.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e)
                {
                    
                }    
            });     
                    
            b2.addActionListener(new ActionListener() 
            {
                public void actionPerformed(ActionEvent e)
                {
                    dispose();
                    Program okno=new Program();
                    okno.setVisible(true);
                }
            });
            
            setSize(750,450);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
        
        public class MyPracListener implements ActionListener 
        {
            public Integer prac;         
            public void actionPerformed(ActionEvent actionevent) 
            {
                JComboBox pracownik = (JComboBox) actionevent.getSource();
                prac = (int)pracownik.getSelectedIndex();
            }
        }
        
        public class MyStatListener implements ActionListener 
        {
            public String stat;         
            public void actionPerformed(ActionEvent actionevent) 
            {
                JComboBox status = (JComboBox) actionevent.getSource();
                stat = (String)status.getSelectedItem();
                System.out.println(" " +stat);
            }
        }
        
        public static void main(String args[]) 
        {
            new Rozliczenie();
        }    
    }

    The problem is ActionListener. Why I can get only default value from JComboBox? When line:

    System.out.println(" " +mpl.prac);

    was inside the private actionlistener class everything was fine but i couldn't get a variable value outside a class. Now when I can get it value is only default --> none. Need help. Thanks.
    Last edited by poliocertes; 12-12-2013 at 03:47 PM.

  2. #2
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default Re: ActionListener how to get variable.

    The only time you print out the prac variable of that ActionListener is at creation time. What value do you expect it to print out at creation time?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  3. #3
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    Quote Originally Posted by KevinWorkman View Post
    The only time you print out the prac variable of that ActionListener is at creation time. What value do you expect it to print out at creation time?
    I need to get present value from both JComboBoxes when I'm making a choice. After that I need to put it into database.

  4. #4
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default Re: ActionListener how to get variable.

    And what part of that is giving you trouble?
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  5. #5
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    As you can see stat variable (which is inside a class) always is updated after any changes on the JComboBox. Unfortunatelly is not available outside. Prac variable is available but always has the same defaul value. I need to get updated value outside a class and use it. Unfortunately I don't know how to do this.

  6. #6
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default Re: ActionListener how to get variable.

    I'm really not sure what you mean, as your code is a little too big to debug. I'd suggest posting an SSCCE instead.

    Without that SSCCE I can only guess, so here goes: Are you trying to access a variable inside an anonymous class? You can't do that. Consider converting that class to a regular named class.
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  7. #7
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default Re: ActionListener how to get variable.

    One problem is that the code creates two instances of the listener class: the first is added as a listener on line 123 and the other (line 125) is not used as a listener. The first instance is the one that will be called when there is an action event. The other one will never be called.
    If you don't understand my response, don't ignore it, ask a question.

  8. #8
    gimbal2 is offline Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    4,016
    Rep Power
    6

    Default Re: ActionListener how to get variable.

    I'm stupid, but I have the crazy idea that this whole thing is solved if the 'prac' variable is moved from the MyPracListener inner class to the Rozliczenie outer class. Probably the stat variable requires the same treatment. If you do that, the variables become available anywhere in the posted code, including in the action listeners.

    EDIT: assuming that what Norm spotted (sharp eyes) is fixed.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    Quote Originally Posted by Norm View Post
    One problem is that the code creates two instances of the listener class: the first is added as a listener on line 123 and the other (line 125) is not used as a listener. The first instance is the one that will be called when there is an action event. The other one will never be called.
    After removing line 123 still have error.

    Quote Originally Posted by gimbal2 View Post
    I'm stupid, but I have the crazy idea that this whole thing is solved if the 'prac' variable is moved from the MyPracListener inner class to the Rozliczenie outer class. Probably the stat variable requires the same treatment. If you do that, the variables become available anywhere in the posted code, including in the action listeners.(...)
    Moved variable prac to Rozliczenie class. Still no access to the variable from outside a class.
    Last edited by poliocertes; 12-12-2013 at 09:36 PM.

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default Re: ActionListener how to get variable.

    After removing line 123 still have error.
    Line 123 was the line that was working. Line 125 was not working correctly.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    A little error. Of course a mean line 125.

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default Re: ActionListener how to get variable.

    What happens when you compile and execute the new version of the program? You need to post the new code if you are having problems with it.
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    When i'm trying to get a value from ComboBox I'm getting only default value (null) if I'm trying to print this value from outside a Listener class. No any changes when I'm choosing another value from combo. When command "System.out.print(" " + value) is inside a class everything is fine, and values is updated after changes on combo but I can't use this value somewhere else.

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default Re: ActionListener how to get variable.

    Sorry, I can't tell what is wrong without seeing the whole of the code with the problem
    Last edited by Norm; 12-12-2013 at 11:05 PM.
    If you don't understand my response, don't ignore it, ask a question.

  15. #15
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    Please find code below:

    Java Code:
    String statusy []={" ","obecny","nieobecny","urlop","chory","dzien_wolny"};
    		status = new JComboBox(statusy);
    		status.setBounds(565,170,120,30);
    		status.setBackground(Color.lightGray);
    		status.setSelectedIndex(0);
    		status.addActionListener(new StatusListener());
    		System.out.println(" " +stat);   //  <---- If I'm trying here is not ok. value is not updated after every changes on combo ( always is null because default on combo is empty) but accesible from outside
    		add(status);	
    //..
    public class StatusListener implements ActionListener 
    	{         
    		public void actionPerformed(ActionEvent actionevent) 
    		{
    			JComboBox status = (JComboBox) actionevent.getSource();
    			stat = (String)status.getSelectedItem();
    			System.out.println(" " +stat);  //  <---- Here is ok. value is updated every changes on combo but no access from outside
    		}
    	}
    I need to put a "stat" (and also "prac" but it's similar situation) on the database so variable should be accesible from outside a class.

  16. #16
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,410
    Rep Power
    25

    Default Re: ActionListener how to get variable.

    Think about when those two println() statements are executed.
    The first is a LONG time before the user makes any selection;
    the second is immediately after the user makes a selection.

    Look at the console and see WHEN the messages are printed.
    Last edited by Norm; 12-12-2013 at 11:18 PM.
    If you don't understand my response, don't ignore it, ask a question.

  17. #17
    poliocertes is offline Member
    Join Date
    Dec 2013
    Posts
    13
    Rep Power
    0

    Default Re: ActionListener how to get variable.

    Java Code:
    	public class StatusListener implements ActionListener 
    	{       
    		public String stat;   
    		public void actionPerformed(ActionEvent actionevent) 
    		{
    			JComboBox status = (JComboBox) actionevent.getSource();
    			stat = (String)status.getSelectedItem();	
    		}
    	}
    How can I can I use stat values from StatusListener class outside a class?

  18. #18
    KevinWorkman's Avatar
    KevinWorkman is offline Crazy Cat Lady
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    3,963
    Rep Power
    8

    Default Re: ActionListener how to get variable.

    You use an instance of StatusListener, dereference it, and access the variable directly (since you've made the variable public).

    StatusListener listener = new StatusListener();
    //...
    String newState = listener.stat;
    How to Ask Questions the Smart Way
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

Similar Threads

  1. Replies: 2
    Last Post: 11-02-2013, 08:53 AM
  2. Replies: 2
    Last Post: 01-09-2013, 08:10 PM
  3. How to compare variable with multiple variable?
    By mharckz009 in forum New To Java
    Replies: 5
    Last Post: 09-11-2012, 04:33 PM
  4. Dynamic variable name based on other variable
    By nadissen in forum Eclipse
    Replies: 4
    Last Post: 05-06-2011, 06:22 PM
  5. Replies: 11
    Last Post: 07-07-2010, 06:02 AM

Tags for this Thread

Posting Permissions

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