user163505
user163505

Reputation: 499

Java How to inherit variables from ActionListener Classes

I am writing a program that will involve a user pressing a button that will generate a random number. That number will determine what text will display on a JLabel. The way the program works is that the main JFrame holds a button called "Work", which opens another JFrame with a button called "Get a new job" and displays the JLabel with the result. I can't seem to pass the variable that holds the randomly generated number from the number generator class to the "Work" buttons ActionListener class. Also, how would I save the text on the JLabel so that if I exited out of that JFrame with the JLabel and re-opened it, it would display the text it had before I closed it and not reset to the default of no text. Thanks, let me know if you need more details.

Main class:

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;



public class Main{

            public static void main(String [] args){

                JFrame main = new JFrame("This is the real life!");
                main.setSize(500,500);
                main.setResizable(false);
                main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                main.setVisible(true);

                JPanel mainPanel = new JPanel(new GridBagLayout());
                main.getContentPane().add(mainPanel, BorderLayout.NORTH);
                GridBagConstraints c = new GridBagConstraints();

                JLabel mainText = new JLabel("This is your life.");
                c.gridx = 50;
                c.gridy = 50;
                c.insets = new Insets(50,10,10,10);
                mainPanel.add(mainText, c);

                JButton workButton = new JButton("Work");
                c.gridx = 50;
                c.gridy = 75;
                c.insets = new Insets(150,10,10,10);
                mainPanel.add(workButton, c);
                workButton.addActionListener(new workButtonAction());

            }
}

"Work" Button ActionListener class:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class workButtonAction extends numGeneratorAction implements ActionListener{

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

        JFrame workFrame = new JFrame("Your job");
        workFrame.setSize(250,250);
        workFrame.setResizable(false);
        workFrame.setVisible(true);

        JPanel workPanel = new JPanel();
        workFrame.add(workPanel);

        JButton numGenerator = new JButton("Get a new job.");
        workPanel.add(numGenerator);
        numGenerator.addActionListener(new numGeneratorAction());

        JLabel Job = new JLabel();

        numGeneratorAction generatorObject = new numGeneratorAction();
        generatorObject.actionPerformed(e);

        if(job == 0){ //The job variable is not recognized in this class.
            Job.setText("Text will go here.");
        }
    }

}

Number Generator Class:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class numGeneratorAction implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        int job;

        Random dice = new Random();
        job = dice.nextInt(4);
        System.out.println(job);

    }

}

Upvotes: 1

Views: 2563

Answers (2)

nachokk
nachokk

Reputation: 14413

is not recognized your job cause you are declaring as local variable, has no scope outside method, just declare outisde actionPerformed as protected int job;

BTW Some advices:

  • Call frame.setVisible(true) at the end.

  • 2- public class workButtonAction extends numGeneratorAction implements ActionListener Why you extend this? If you extend you don't need to implements ActionListener cause parent implements it.

  • 3- Don't implement ActionListener in top classes i prefer using annonymus classes or private inner classes.

  • 4- Don't create your frame in actionListener method put them as global variable no local variable

  • 5- Follow java code convetions (first letter of classes should
    be UpperCase)

Now in your code:

Create a class that holds the Frame

public class MainFrame {

private JFrame main;
private JPanel mainPanel;
private JLabel mainText;
private JButton workButton;

public MainFrame(){
                main = new JFrame("This is the real life!");
                main.setSize(500,500);
                main.setResizable(false);
                main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


                mainPanel = new JPanel(new GridBagLayout());
                main.getContentPane().add(mainPanel, BorderLayout.NORTH);
                GridBagConstraints c = new GridBagConstraints();

                mainText = new JLabel("This is your life.");
                c.gridx = 50;
                c.gridy = 50;
                c.insets = new Insets(50,10,10,10);
                mainPanel.add(mainText, c);

                workButton = new JButton("Work");
                c.gridx = 50;
                c.gridy = 75;
                c.insets = new Insets(150,10,10,10);
                mainPanel.add(workButton, c);
                workButton.addActionListener(new WorkButtonAction());
                main.pack();
                main.setVisible(true);
}


private class WorkButtonAction implements ActionListener {
       @override
       public void actionPerformed(ActionEvent evt){
               // here create a JDialog instead of a JFrame
                 JDialog dialog = new MyDialog(main,true);
                 dialog.setVisible(true);
       }


}

}

The JDialog

public class MyDialog extends JDialog{

private JPanel workPanel;
private JButton numGenerator;
private JLabel jlabel;
private Random dice = new Random();

public MyDialog(){

        setTitle("Your job");
        setSize(250,250);
        setResizable(false);
        workPanel = new JPanel();
        add(workPanel);
        numGenerator = new JButton("Get a new job.");
        workPanel.add(numGenerator);

       numGenerator.addActionListener(new NumGeneratorAction(){
                @Override
                public void actionPerformed(ActionEvent evt){
                      int job = dice.nextInt(4);
                      if(job == 0)
                            jobLabel.setText("Text will go here.");
                }

       });

        jobLabel = new JLabel();

}




}

and in your Main class

public class Main {
  public static void main(String args []){
       SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                  new MainFrame();
                }
         });

  }
}

Upvotes: 1

Asaf Sh.
Asaf Sh.

Reputation: 49

I use simple technique as pattern if there is need to make callback to parent class - child class must be extended with some methods to hold reference to parent. Parent must implement new interface the child will use to signal parent. For this example i would try to add interface to new class based on button. then make a new class of action listener which takes button as object as argument in its constructor so you will have the origin of it.

But, disregard what is written above - that is pattern, which is not needed in your case. There is ActionEvent which goes straight to the ActionListener and holds source of event: http://www.daniweb.com/software-development/java/threads/196917/the-e.getsource-method-from-actionevent-e-in-a-listener

Upvotes: 1

Related Questions