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 18 of 18

Thread: Set Variable In Event Handler

  1. #1
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Set Variable In Event Handler

    I have a class variable, that I want to set in a separate class. I am instantiating an instance of this class in my second class, and referencing and setting the variable. If I use a message box to show the value of the variable in the EventHandler the value is set. However, when I try to access the value from my 'main' class Data the value is empty.

    How should I re-write the below code so the value of playerSelected remains set?

    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.border.LineBorder;
    import java.awt.*;
     
    public class Data {
     
        JFrame frame		= new JFrame();
        JPanel mainPanel	= new JPanel();
        JPanel secondPanel  = new JPanel();
     
        String playerSelected;
        String playerimage;
        String cpuimage;
        String BattlesWon = "0";
        String BattlesLost = "0";
        String Gold = "0";
        String PlayerLevel = "1";
     
        public static void main(String args[]) {
            new Data().start();
        }
     
        public void start() {
            JLabel myLabel = new JLabel("Enter Player Name:");
            JPanel pnlHeaderInfo = new JPanel(); 
            JPanel pnlCharacters = new JPanel();
            JPanel pnlNextButton = new JPanel();
     
            JTextField myText = new JTextField(20); 
            myLabel.setAlignmentX(JTextField.CENTER_ALIGNMENT);
     
            pnlHeaderInfo.setPreferredSize(new Dimension(300, 60));
            pnlHeaderInfo.setLayout(new FlowLayout());
            pnlHeaderInfo.add(myLabel);
            pnlHeaderInfo.add(myText);
            pnlHeaderInfo.setBorder(new LineBorder(Color.RED, 3));
            mainPanel.setPreferredSize(new Dimension(600, 400));
            mainPanel.add(pnlHeaderInfo);
     
            JLabel lblLeftChar1 = new JLabel();
            JLabel lblCenterChar2 = new JLabel();
            JLabel lblRightChar3 = new JLabel();
     
            MyMouseHandler myMouseHandler = new MyMouseHandler();
     
            lblLeftChar1.setMinimumSize(new Dimension(141,244));
            lblLeftChar1.setMaximumSize(new Dimension(141,244));
            lblLeftChar1.setName("Link");
            lblLeftChar1.setIcon(new ImageIcon(getClass().getResource("/resources/__Link.jpg")));
            lblLeftChar1.addMouseListener(myMouseHandler);
     
            lblCenterChar2.setMinimumSize(new Dimension(141,244));
            lblCenterChar2.setMaximumSize(new Dimension(141,244));
            lblCenterChar2.setName("Mario");
            lblCenterChar2.setIcon(new ImageIcon(getClass().getResource("/resources/__Mario.png")));
            lblCenterChar2.addMouseListener(myMouseHandler);
     
            lblRightChar3.setMinimumSize(new Dimension(141,244));
            lblRightChar3.setMaximumSize(new Dimension(141,244));
            lblRightChar3.setName("Pikachu");
            lblRightChar3.setIcon(new ImageIcon(getClass().getResource("/resources/__Pikachu.png")));
            lblRightChar3.addMouseListener(myMouseHandler);
     
            pnlCharacters.setPreferredSize(new Dimension(496, 256));
            pnlCharacters.setLayout(new BorderLayout());
     
            pnlCharacters.add(lblLeftChar1, BorderLayout.LINE_START);
            lblCenterChar2.setHorizontalAlignment(JLabel.CENTER);
            pnlCharacters.add(lblCenterChar2, BorderLayout.CENTER);
            pnlCharacters.add(lblRightChar3, BorderLayout.LINE_END);
            pnlCharacters.setBorder((new LineBorder(Color.BLUE, 3)));
            mainPanel.add(pnlCharacters);
     
            //JOptionPane.showMessageDialog(null, playerSelected, "TITLE", JOptionPane.WARNING_MESSAGE);
     
            JButton btnNext = new JButton("Start Game");
            btnNext.addActionListener(new ActionListener() {
     
                @Override
                public void actionPerformed(ActionEvent e) {
                    //hide the current main panel
                    mainPanel.setVisible(false);
                    beginstagetwo();
                }
            });
     
            btnNext.setMinimumSize(new Dimension(112,29));
            btnNext.setMaximumSize(new Dimension(112,29));
            pnlNextButton.add(btnNext, BorderLayout.CENTER);
            pnlNextButton.setBorder((new LineBorder(Color.GREEN)));
            mainPanel.add(pnlNextButton);
     
            frame.add(mainPanel);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
            frame.pack(); 
            frame.setLocationRelativeTo(null); 
            frame.setVisible(true);
        }
     
        public void beginstagetwo() {
            JPanel pnlPlayerStats = new JPanel();
     
            pnlPlayerStats.setPreferredSize(new Dimension(300, 60));
     
            JLabel lblPlayerName = new JLabel("Player Name:");
            JTextField txtPlayerName = new JTextField(30);
            txtPlayerName.setText(playerSelected);
            lblPlayerName.setAlignmentX(JTextField.CENTER_ALIGNMENT);
     
            JLabel lblPlayerGold = new JLabel("Gold:");
            JTextField txtPlayerGold = new JTextField(6);
            lblPlayerGold.setAlignmentX(JTextField.CENTER_ALIGNMENT);
     
            pnlPlayerStats.setLayout(new FlowLayout());
            pnlPlayerStats.add(lblPlayerName);
            pnlPlayerStats.add(txtPlayerName);
            pnlPlayerStats.add(lblPlayerGold);
            pnlPlayerStats.add(txtPlayerGold);
     
     
            pnlPlayerStats.setBorder(new LineBorder(Color.ORANGE, 3));
            secondPanel.setPreferredSize(new Dimension(600, 400));
            secondPanel.add(pnlPlayerStats);
            frame.add(secondPanel);
            frame.pack();
            frame.setVisible(true);
        }
    }
    class MyMouseHandler extends MouseAdapter {
     
        Data dt = new Data();
     
        @Override
        public void mouseClicked(MouseEvent evt) {
            JLabel source = (JLabel) evt.getSource();
            String labelname = source.getName();
            dt.playerSelected = labelname;
        }
     
    }

  2. #2
    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: Set Variable In Event Handler

    The instance of Data created in the listener class is different from the instance created in the main method. Each instance has its own version of the playerSelected variable.
    One solution is to pass a reference to the one and only instance of the Data class to the listener class's constructor and save that reference in the listener class. Code in the Data class would use the this variable to reference to its instance.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2019
    Location
    Belgium
    Posts
    13
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Set Variable In Event Handler

    Or don't make an instance at al and call the classvariable direct.
    YourClass.variable

  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: Set Variable In Event Handler

    YourClass.variable
    @ufotje
    That only works if the variable is static. Not a recommended solution.

    Another solution would be to make the listener class an inner class so it could reference the enclosing Data class's variables directly.
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by Norm View Post
    The instance of Data created in the listener class is different from the instance created in the main method. Each instance has its own version of the playerSelected variable.
    One solution is to pass a reference to the one and only instance of the Data class to the listener class's constructor and save that reference in the listener class. Code in the Data class would use the this variable to reference to its instance.

    I am new to JAVA - can you provide an example of this?

  6. #6
    Junior Member
    Join Date
    Jan 2019
    Location
    Belgium
    Posts
    13
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by Norm View Post
    @ufotje
    That only works if the variable is static. Not a recommended solution.
    He said classvariable so I automaticly asumed it was static, what's the point otherwise of creating a classvariable.
    If he uses your solution, I would declare a private instance variable and provide a getter
    Last edited by ufotje; January 15th, 2019 at 08:45 AM.

  7. #7
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by Norm View Post
    @ufotje
    That only works if the variable is static. Not a recommended solution.
    Why do you recommend against setting the variable as static?

  8. #8
    Junior Member
    Join Date
    Jan 2019
    Location
    Belgium
    Posts
    13
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by jo15765 View Post
    I am new to JAVA - can you provide an example of this?
    class MyMouseHandler extends MouseAdapter {
        private Data dt;
     
        //Add Constructor
        class MyMouseHandler(Data data){
            dt = data;
        }
     
        //Add Getter
        public Data getData(){
            return data;
        }
     
        @Override
        public void mouseClicked(MouseEvent evt) {
            JLabel source = (JLabel) evt.getSource();
            String labelname = source.getName();
            dt.playerSelected = labelname;
        }
     
    }

  9. #9
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Set Variable In Event Handler

    I get a compile error of Duplicate Class: MyMouseHandler when I add this line in
    //Add Constructor
        class MyMouseHandler(Data data){
            dt = data;
        }

  10. #10
    Junior Member
    Join Date
    Jan 2019
    Location
    Belgium
    Posts
    13
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by jo15765 View Post
    I get a compile error of Duplicate Class: MyMouseHandler when I add this line in
    //Add Constructor
        class MyMouseHandler(Data data){
            dt = data;
        }
    Sorry my bad it should be:
    public MyMouseHandler(Data data){
        ...
    }

  11. The Following User Says Thank You to ufotje For This Useful Post:

    jo15765 (January 15th, 2019)

  12. #11
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Set Variable In Event Handler

    And I am assuming I will have to update how I call it? I am getting this compile error
    Error:(45, 41) java: constructor MyMouseHandler in class MyMouseHandler cannot be applied to given types;
      required: Data
      found: no arguments
      reason: actual and formal argument lists differ in length

  13. #12
    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: Set Variable In Event Handler

    @ufotje Please read:
    http://www.javaprogrammingforums.com...n-feeding.html

    You have written all the OPS code for him without letting him work through the details and learn as he goes.
    If you don't understand my answer, don't ignore it, ask a question.

  14. #13
    Junior Member
    Join Date
    Jan 2019
    Location
    Belgium
    Posts
    13
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by Norm View Post
    @ufotje Please read:
    http://www.javaprogrammingforums.com...n-feeding.html

    You have written all the OPS code for him without letting him work through the details and learn as he goes.
    Lol apperently not, otherwise he wouldn't have run in to that error...

    --- Update ---

    Quote Originally Posted by jo15765 View Post
    And I am assuming I will have to update how I call it? I am getting this compile error
    Error:(45, 41) java: constructor MyMouseHandler in class MyMouseHandler cannot be applied to given types;
      required: Data
      found: no arguments
      reason: actual and formal argument lists differ in length
    No offence, but if you have to ask something like this, I would start with following some basic java tutorials before starting on a swing app

    --- Update ---

    Quote Originally Posted by jo15765 View Post
    Why do you recommend against setting the variable as static?
    The message disapeard after editting so...
    They're hard to control, anything or anyone could modify them and they can have any state at any time.
    The general rule is how smaller the scope, the better and how easier to control

  15. #14
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Set Variable In Event Handler

    I have my code as the below, where I declare the variable in my Data class, and from what I know, passing variable to the MouseEvent class. However, my JLabel prompt still shows empty?

    public void start() {
            Data data = new Data();
     
            MyMouseHandler myMouseHandler = new MyMouseHandler(data);
     
            JOptionPane.showMessageDialog(null, this.playerSelected, "TITLE", JOptionPane.WARNING_MESSAGE);
        }
     
        class MyMouseHandler extends MouseAdapter {
     
        private Data dt;
     
        //Add Constructor
        public MyMouseHandler(Data data){
            dt = data;
        }
     
        //Add Getter
        public Data getData(){
            return dt;
        }
     
        @Override
        public void mouseClicked(MouseEvent evt) {
            JLabel source = (JLabel) evt.getSource();
            String labelname = source.getName();
            dt.playerSelected = labelname;
        }
     
    }

  16. #15
    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: Set Variable In Event Handler

    How many instances of the Data class are created? It looks like one in the main method and another in the start method. Don't create a second instance, use the current one.
    Use the this variable to reference the current instance.
    If you don't understand my answer, don't ignore it, ask a question.

  17. #16
    Member
    Join Date
    May 2012
    Posts
    36
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Set Variable In Event Handler

    Quote Originally Posted by Norm View Post
    How many instances of the Data class are created? It looks like one in the main method and another in the start method. Don't create a second instance, use the current one.Use the this variable to reference the current instance.
    If I try to use the variable this like below
    Data this.data;

    I get errors of
    Error:(25, 9) java: not a statement
    Error:(25, 13) java: ';' expected
    Error:(25, 19) java: not a statement

  18. #17
    Junior Member
    Join Date
    Jan 2019
    Location
    Belgium
    Posts
    13
    Thanks
    0
    Thanked 1 Time in 1 Post

    Default Re: Set Variable In Event Handler

    What did you expect? You create a new Data with the default constructor, which takes no parameters.
    So every instance variable Data has is still null.
    Of cource you need to set the value's first.
    Make a constructor for Data that takes the arguments or provide setter methods

    --- Update ---

    Quote Originally Posted by jo15765 View Post
    If I try to use the variable this like below
    Data this.data;

    I get errors of
    Error:(25, 9) java: not a statement
    Error:(25, 13) java: ';' expected
    Error:(25, 19) java: not a statement
    The middle one is easy: go to line 25 of your code and add an ; where it's missing?
    for the other two, what is line 25 of your code?
    What idea are you using? It should warn you for stuff like that...

    --- Update ---

    And the prob isn't with your Data it's your JLabel, since you're using that to set the String labelName
    From what I understand from your question I think you're trying to do something like this:
    source.setText(data.getName());

  19. #18
    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: Set Variable In Event Handler

    this is a builtin variable that contains a reference to the current instance of the class.
    Use this anywhere a reference to the current instance is needed.
            MyMouseHandler myMouseHandler = new MyMouseHandler(this);  // pass reference to current instance of Data
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. Event Handler Question
    By shep in forum Java Theory & Questions
    Replies: 5
    Last Post: April 10th, 2014, 02:39 PM
  2. Event Handler For a JTextField
    By JamesdTurnham in forum What's Wrong With My Code?
    Replies: 8
    Last Post: June 17th, 2013, 06:16 PM
  3. JButton event handler
    By gkelly642 in forum What's Wrong With My Code?
    Replies: 3
    Last Post: April 3rd, 2013, 09:01 PM
  4. Separate Event Handler Class
    By beer-in-box in forum AWT / Java Swing
    Replies: 2
    Last Post: April 1st, 2013, 09:19 AM
  5. JButton event handler
    By Jsri in forum AWT / Java Swing
    Replies: 1
    Last Post: October 25th, 2011, 07:02 AM