Results 1 to 7 of 7
  1. #1
    newbie123 is offline Member
    Join Date
    Nov 2009
    Posts
    90
    Rep Power
    0

    Question variable scope between classes

    I think I have a variable scope problem that I am hoping someone can help me with.

    I create a variable and set its value in one class. I then want to use this variable and its value in another class.

    When I try to access the value in the second class, the value is returned as "null".

    How do I declare the variable in the first class so that it is usable in the second class?

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    You have a bug in your program probably unrelated to what you think is wrong. I think we'll need to see example code to help determine what is wrong, an SSCCE would be perfect.

  3. #3
    nolsen01 is offline Member
    Join Date
    Jul 2009
    Posts
    18
    Rep Power
    0

    Default

    Java Code:
    public class A{
    
        private int intToReturn;
    
        public A(){
            this.intToReturn = 5;
        }
    
        public int returnInt(){
            return this.intToReturn;
        }
    
    }
    
    
    public class B{
    
        private A a;
        int myInt;
    
        public B(){
            a = new A();
            myInt = a.returnInt();
        }
    
    }

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    There are no scope problems in the code you've posted that I can see.

  5. #5
    newbie123 is offline Member
    Join Date
    Nov 2009
    Posts
    90
    Rep Power
    0

    Default the problematic code

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Main1 extends JFrame implements ActionListener
    {
            JPanel cards;
    
            final static String CARD1 = "firstWindow";
            final static String CARD2 = "secondWindow";
    
            public void addComponentToPane( Container pane )
            {
                    JPanel Pane = new JPanel();
    
                    Panel1 p1 = new Panel1();
    
                    JPanel card1 = new JPanel();
                    card1.setLayout( new FlowLayout() );
    
                    card1.add( p1 );
    
                    JButton startButton = new JButton( "START" );
                    startButton.setActionCommand( "START" );
                    startButton.addActionListener( this );
                    card1.add( startButton );
    
                    Panel2 p2 = new Panel2();
    
                    JPanel card2 = new JPanel();
    
                    card2.add( p2 );
    
                    cards = new JPanel( new CardLayout() );
                    cards.add( card1, CARD1 );
                    cards.add( card2, CARD2 );
    
                    pane.add( Pane, BorderLayout.PAGE_END );
                    pane.add( cards, BorderLayout.CENTER );
            }
    
            public void actionPerformed( ActionEvent ae )
            {
                    if ( ae.getActionCommand().equals( "START" ) )
                    {
                            CardLayout cl = ( CardLayout )( cards.getLayout() );
                            cl.show( cards, CARD2 );
                    }
            }
    
            private static void createAndShowGUI()
            {
                    JFrame frame = new JFrame( "Main Frame" );
                    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    
                    Main1 m1 = new Main1();
                    m1.addComponentToPane( frame.getContentPane() );
    
                    frame.setSize( 500, 700 );
                    frame.setVisible( true );
            }
    
            public static void main( String[] args )
            {
                    javax.swing.SwingUtilities.invokeLater( new Runnable()
                    {
                            public void run()
                            {
                                    createAndShowGUI();
                            }
                    } );
            }
    }
    
    class Panel1 extends JPanel implements ActionListener
    {
            JComboBox gradeComboBox;
            JLabel variableLbl;
    
            Panel1()
            {
                    setOpaque( true );
            
                    setPreferredSize( new Dimension( 500, 500 ) );
                    
                    setLayout( new GridLayout( 3, 1, 5, 5 ) );
                            
                    JLabel selectLbl = new JLabel( "Select Parameters", SwingConstants.CENTER );
                    add( selectLbl );
            
                    JLabel gradeLbl = new JLabel( "Grade:" );
            
                    String gradeArray[] = { "First", "Second", "Third", "Fourth", "Fifth" };
                    
                    gradeComboBox = new JComboBox( gradeArray );
                    gradeComboBox.addActionListener( this );
                    
                    JPanel gradePnl = new JPanel();
    
                    gradePnl.add( gradeLbl );
                    gradePnl.add( gradeComboBox );
            
                    add( gradePnl );
            
                    variableLbl = new JLabel( "" );
                    add( variableLbl );
            }       
                            
            public void actionPerformed( ActionEvent ae )
            {                       
                    String grade = ( String ) gradeComboBox.getSelectedItem();
                    variableLbl.setText( "Grade: " + grade );
            }
    }
    
    
    class Panel2 extends JPanel
    {
            JLabel variableLbl;
    
            Panel2()
            {
                    setOpaque( true );
    
                    setPreferredSize( new Dimension( 500, 500 ) );
    
                    setLayout( new GridLayout( 2, 1, 5, 5 ) );
    
                    JLabel selectLbl = new JLabel( "Parameters", SwingConstants.CENTER );
                    add( selectLbl );
    
                    JLabel gradeLbl = new JLabel( "Grade: " );
                    //JLabel gradeLbl = new JLabel( "Grade: " + Panel1.grade );
    
                    JPanel variablePnl = new JPanel();
    
                    variablePnl.add( gradeLbl );
    
                    add( variablePnl );
            }
    }
    Moderator Edit: Code tags added to aid readability
    Last edited by Fubarable; 03-03-2010 at 10:56 PM. Reason: Moderator Edit: Code tags added to aid readability

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    It's simply a matter of getter and setter methods and variable scope, that's all.

    1) Give your Panel1 and Panel2 variables (p1 and p2) class scope so that they can be used in other methods of the class (in particular the actionPerformed method).

    2) Give your Panel1 class a getter method that will allow users of this object to extract the string selected from the combobox.

    3) Give your Panel2 class a setter method that allows users of this object to set the grade string.

    4) Combine these guys in your control class (here your main class's actionPerformed method).

    5) Please use code tags when posting code here (see my signature below for details).

    e.g.,
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class Main1 extends JFrame implements ActionListener {
      JPanel cards;
    
      final static String CARD1 = "firstWindow";
      final static String CARD2 = "secondWindow";
      
      // give these variables class scope, so they can be 
      // used by other methods.
      private Panel1 p1 = new Panel1();
      private Panel2 p2 = new Panel2();
    
      public void addComponentToPane(Container pane) {
        JPanel Pane = new JPanel();
    
        //Panel1 p1 = new Panel1();
    
        JPanel card1 = new JPanel();
        card1.setLayout(new FlowLayout());
        card1.add(p1);
    
        JButton startButton = new JButton("START");
        startButton.setActionCommand("START");
        startButton.addActionListener(this);
        card1.add(startButton);
    
        //Panel2 p2 = new Panel2();
    
        JPanel card2 = new JPanel();
        card2.add(p2);
        cards = new JPanel(new CardLayout());
        cards.add(card1, CARD1);
        cards.add(card2, CARD2);
    
        pane.add(Pane, BorderLayout.PAGE_END);
        pane.add(cards, BorderLayout.CENTER);
      }
    
      public void actionPerformed(ActionEvent ae) {
        if (ae.getActionCommand().equals("START")) {
          CardLayout cl = (CardLayout) (cards.getLayout());
          cl.show(cards, CARD2);
          
          //use your p1 and p2 objects here:
          p2.setGrade(p1.getGradeSelected());
        }
      }
    
      private static void createAndShowGUI() {
        JFrame frame = new JFrame("Main Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
        Main1 m1 = new Main1();
        m1.addComponentToPane(frame.getContentPane());
    
        frame.setSize(500, 700);
        frame.setVisible(true);
      }
    
      public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
          }
        });
      }
    }
    
    class Panel1 extends JPanel implements ActionListener {
      JComboBox gradeComboBox;
      JLabel variableLbl;
    
      Panel1() {
        setOpaque(true);
        setPreferredSize(new Dimension(500, 500));
        setLayout(new GridLayout(3, 1, 5, 5));
        JLabel selectLbl = new JLabel("Select Parameters",
            SwingConstants.CENTER);
        add(selectLbl);
        JLabel gradeLbl = new JLabel("Grade:");
        String gradeArray[] = { "First", "Second", "Third",
            "Fourth", "Fifth" };
        gradeComboBox = new JComboBox(gradeArray);
        gradeComboBox.addActionListener(this);
        JPanel gradePnl = new JPanel();
        gradePnl.add(gradeLbl);
        gradePnl.add(gradeComboBox);
        add(gradePnl);
        variableLbl = new JLabel("");
        add(variableLbl);
      }
    
      public void actionPerformed(ActionEvent ae) {
        String grade = (String) gradeComboBox.getSelectedItem();
        variableLbl.setText("Grade: " + grade);
      }
      
      // add a "getter" method here
      public String getGradeSelected() {
        return (String)gradeComboBox.getSelectedItem();
      }
    }
    
    class Panel2 extends JPanel {
      private static final String GRADE = "Grade: ";
      private JLabel gradeLbl = new JLabel(GRADE);  
    
      Panel2() {
        setOpaque(true);
        setPreferredSize(new Dimension(500, 500));
        setLayout(new GridLayout(2, 1, 5, 5));
        JLabel selectLbl = new JLabel("Parameters", SwingConstants.CENTER);
        add(selectLbl);
        JPanel variablePnl = new JPanel();
        variablePnl.add(gradeLbl);
        add(variablePnl);
      }
      
      // Give this class a public setter method 
      public void setGrade(String gradeStr) {
        gradeLbl.setText(GRADE + gradeStr);
      }
    }

  7. #7
    newbie123 is offline Member
    Join Date
    Nov 2009
    Posts
    90
    Rep Power
    0

    Smile Thanks!

    Thanks for your quick reply. I'll give it a go, and let you know how it works.

    This forum is great!

Similar Threads

  1. Replies: 9
    Last Post: 12-01-2009, 08:30 PM
  2. Variable Scope
    By Laura Warren in forum New To Java
    Replies: 3
    Last Post: 01-11-2009, 10:16 PM
  3. jsf scope query
    By nc_newie in forum JavaServer Faces (JSF)
    Replies: 1
    Last Post: 08-06-2008, 02:34 PM
  4. return out of scope?
    By another_steve in forum New To Java
    Replies: 5
    Last Post: 01-28-2008, 09:34 PM
  5. Passing variable information between classes
    By zen_to_go in forum New To Java
    Replies: 1
    Last Post: 10-30-2007, 08:09 PM

Posting Permissions

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