Link to home
Start Free TrialLog in
Avatar of Mannsi
Mannsi

asked on

Reference a object from another method in Java

Hello experts,

I'm having some java problems. I've created a program that starts with a call to CreateGUI() from main. CreateGUI() creates a frame and a couple of panels that I add some buttons on to. When one of the buttons is pressed some data is read from a file and added to a array. I than need to edit the GUI based on the data read, but I don't know to reference to the panels that where created in the CreateGUI() method. How can I accomplish this ?

I've added the code hierarchy below. Please ask if I've not made somethings clear.

I don't really need to use the setup as described below. If my problem can be solved by completely altering things, I'm all for it.

Thanks
public class Panel_class
{
	public static void main (String[] args)
	{
		CreateGUI();
	}
 
        public static void load_array(String s)
        {
              //loads the array from input file
              //HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
        }
 
        public static class ButtonListener1 implements ActionListener
        {
             //Listens for the button click
        }
 
       	 public static void CreateGUI()
         {
              //Creates the GUI based on the description above         
         }
}

Open in new window

Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

You need accessor (get) method in the gui that you create. CreateGUI should probably not be a void method but return the main container (JFrame?) that gets created. You need get method in that container for what you want to access
Avatar of Mannsi
Mannsi

ASKER

Yes, it's a JFrame.

I'm new to Java, could you maybe give me a simple example ?
You need to read up on creating frames. Try starting here and look at the examples they give:

http://java.sun.com/docs/books/tutorial/uiswing/components/frame.html
Avatar of Mannsi

ASKER

I changed to CreateGUI() method so that it returned a JFrame object. I then talked to a friend of mine who advised me to set the returned JFrame as a global variable, and that seems to work. I'm gonna give you a few minutes to criticize this solution (e.g. if it's not good practice or something) before I award the points.
Generally speaking, you should rarely write static methods (apart from main) unless they are in a utility library or you have some special reason.

Similarly, global variables should be avoided if possible
Avatar of Mannsi

ASKER

hmmm...

Change of status. After I changed CreateGUI from void to JFrame (returning myFrame) and declared myFrame as a global variable I was able to change the title of myFrame from the load_array method. However, I can't seem to add another panel to it.

fsze88: I'm a java retard, where and how should I use these methods ?
Other commenters are quite correct that it is considered bad form to have large numbers of static (global) variables.  What *would* be considered good form would be to create a new class to represent your GUI and have createGUI return that.  Any or all of the components of the gui would be stored in fields of this class.  If you wanted a quick-and-dirty solution, you could make those fields public so that you could manipulate it directly.  Even better would be to keep the fields private but add appropriate manipulation fields to the GUI class.  For example, if your array were a bunch of customer names to be shown in a list, you'd include an "addCustomers" method to the class.
private JPanel panelCenter = new JPanel ();
this.getContentPane().add( panelCenter, BorderLayout.CENTER);
JFrame jf = (JFrame)panelCenter.getTopLevelAncestor();
System.out.println("jf.getName() : " + jf.getName());
Returning your JFrame generally is not that useful and just complicates things.
beekeep's suggestion is good to create a new class, and have your firelds that you need access to as a member.
I'd suggest subclassing JPanel for this purpoee like this:

public class MyPanel extends JPanel
{
   // field member vars
   private JButtom button;

   public MyPanel()
   {
       // initialise your gui here
   }

        public static void main (String[] args)
        {
            JFrame frame = new JFrame();
            frame.add(new MyPanel());
            ...
        }

There's no need to create a new class really. The class that represents the gui might just as well be the JFrame itself or a subclass thereof. It really depends on what you want to do with it.

Don't stack up code in your main method and create GUI components like that. See Sun's recommended way of handling initialisation in examples such as:

http://java.sun.com/docs/books/tutorial/uiswing/examples/components/FrameDemoProject/src/components/FrameDemo.java
Avatar of Mannsi

ASKER

Ok.
Given the example that you pointed out CEHJ, how should I change that code so that I could edit the variable frame that gets created in 'private static void createAndShowGUI()' when I'm in another method ?
I don't quite understand the getters and setters thing.
public class Panel_class extends JPanel
{
      // add the compoents you need here as member variables

        public static void main (String[] args)
        {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CreateGUI();
            }
        });
        }
 
        public static void load_array(String s)
        {
              //loads the array from input file
              //HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
        }
 
        public static class ButtonListener1 implements ActionListener
        {
             //Listens for the button click
        }
 
         public static void CreateGUI()
         {
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel panel = new Panel_class();
frame.getContentPane().add(panel);

// add your components to panel here
// make them member vars so you can access from other methods

        //Display the window.
        frame.pack();
        frame.setVisible(true);
         }
}
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
you can get rid of those statics with what i suggesated above

public class Panel_class extends JPanel
{
      // add the compoents you need here as member variables

        public static void main (String[] args)
        {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                CreateGUI();
            }
        });
        }
 
        public void load_array(String s)
        {
              //loads the array from input file
              //HERE I WOULD LIKE TO EDIT THE PANELS IN CREATEGUI()
        }
 
        public class ButtonListener1 implements ActionListener
        {
             //Listens for the button click
        }
 
         public static void CreateGUI()
         {
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


JPanel panel = new Panel_class();
frame.getContentPane().add(panel);

// add your components to panel here
// make them member vars so you can access from other methods

        //Display the window.
        frame.pack();
        frame.setVisible(true);
         }
}

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
:-)