Page 1 of 3 123 LastLast
Results 1 to 20 of 46
Like Tree1Likes

Thread: How to access a variable in one class from another?

  1. #1
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Exclamation How to access a variable in one class from another?

    Ok just FYI, I did look up how to do this already, I just can't get it to work in my program yet. In one class I have a store where you buy things varying in price. (My program just consists of different JFrames and you go from one to another) Then I have a bank variable which keeps track of how much money you spend and the Glabel is updated everytime in that class. Then I have another class with another store but I want to use the same bank variable as the last class so that way I start out with the amount in my bank leftover. My problem is, no matter how much I buy in the Town, my bank always displays 0 in the other class. Everything works fine in the Town class but not in the port class. What is wrong? Here is a small portion of my code:

    Town class //this is a JFrame
    private int bank;
    private JComboBox Store;
    private GLabel banklabel;

    public int getBank(){
    return this.bank;
    }
    private void StoreActionPerformed(java.awt.event.ActionEvent evt) {
    if (Store.getSelectedItem().equals("Map") ) {

    Dialog.showMessage("You bought a world map");
    bank = bank - 10;
    bankLabel.setText("Gold: " + bank);
    Map=true;
    Store.removeItem("Map"); //all this works fine
    }
    }


    Port class //this is also a JFrame
    public Port() { //constructor

    Town thebank=new Town();
    newBank=thebank.getBank();
    BankLabel.setText("Gold: " + newBank); //then I have another store method just like before
    }
    Thanks!!

  2. #2
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,423
    Rep Power
    20

    Default Re: How to access a variable in one class from another?

    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  3. #3
    superhaNds is offline Senior Member
    Join Date
    Apr 2013
    Location
    Sweden
    Posts
    265
    Rep Power
    2

    Default Re: How to access a variable in one class from another?

    I'm really having a hard time understanding your design. Port is a JFrame you say and that's its whole constructor? When Town thebank is created you get its bank variable value
    which I assume the initial is 0 and you set a label to Gold: 0 and that happens when you want to construct a Port object, which is a JFrame.
    Other than that, I do not understand much, post more code maybe..

  4. #4
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    The code does look a bit messy (and incomplete), yeah. One suggestion I have is to have a third class that keeps track of how much gold you have; that way it will sync up automatically between Port and Town. Also remember that variables aren't shared between instances, so when you do this:

    Town thebank=new Town();
    newBank=thebank.getBank();

    newBank will always end up as 0, since you create a whole new Town.

    Also, a part of the reason your code is so messy is your lack of coding convention. For instance:

    private JComboBox Store;
    private GLabel banklabel;

    should be:

    private JComboBox store;
    private GLabel bankLabel;

    Classes should always start with a capital (i.e. JComboBox, String, JFrame) while methods and variables should always start with a lowercase (i.e. bankLabel, getBank(), etc).

  5. #5
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    Sorry for the confusion, I am new to java so I am still getting used to all the naming conventions. Ok I made a new class called bankStuff that now contains the bank int variable instead of town. Of course I have run into the same problem as before, when I create a new instance I always get a bank value of 0. How do I make it so I will get a new value in the port class JFrame? Here is my new bank class.

    public class bankStuff {
    private int bank;
    public bankStuff(){
    bank=0;
    }

    public int getBank(){
    return this.bank;
    }

    }
    And in the Town class I do this and something pretty similiar in the port class
    Town class
    public Town(){
    initComponets(); //does all the JFrame stuff
    bankStuff thebank=new bankStuff();
    otherBank=thebank.getBank();
    }

    Thanks a ton!!!!!!!!!!!!!!!!

  6. #6
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    The trick is to pass along the Bank object at some point instead of creating a new one. Unless you want to have separate banks in Town and Port? Anyway, if you just want to have the one Bank, then you could either pass it along in the constructor of both Town and Port (assuming you never want to use a different Bank object), or pass it along in the StoreActionPerformed method (in those cases, you'd be able to use different banks if you wanted to).

  7. #7
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    Ok that sounds good? So does that mean I need to make parameters of type int in my constructors and then have the parameter variable equal to bank? Please forgive my basic lack of understanding, I am very very new to java so I am still fuzzy about all java terms.

  8. #8
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    The parameter would be the bank class you created earlier. Here's a quick example:

    Java Code:
    class Bank
    {
      int amount;
    }
    
    class Town
    {
      Bank bankToUse;
      public Town(Bank bankToUse)
      {
        this.bankToUse=bankToUse;
      }
    }
    
    class Port
    {
      Bank bankToUse;
      public Port(Bank bankToUse)
      {
        this.bankToUse=bankToUse;
      }
    }
    Then, every time you wanted to use the money in the bank, you'd use the bankToUse.amount variable (or use getters and setters).

  9. #9
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    thank you so much!!!!

  10. #10
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    Oh one last question, when I make the parameter in my constructor my public void run method has an error.
    PHP Code:
    public void run() {
                    new Town().setVisible(true);
    
    
                }
    When I put the bankToUse variable in there it says something about not being able to use a non static cannot be referenced to a static context. What do I need to do to fix that? Thanks a million

  11. #11
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    Without seeing virtually any code at all, I can't answer with any precision. You get that error when you use non-static variables in static methods though.

  12. #12
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    Ok I actually fixed that problem, I just made bankToUse static then said new Town(bankToUse).setVisible in the run method. My new problem is(and hopefully my last problem for awhile) is this:

    Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - constructor TownRevisit in class findinghome.TownRevisit cannot be applied to given types;
    required: findinghome.bankStuff //findinghome is the name of the game. bankStuff is the bank class
    found: no arguments
    reason: actual and formal argument lists differ in length

    Here is some of my code if you can make sense of all this:
    Town class

    static bankStuff bankToUse;

    public TownRevisit(bankStuff bankToUse) {
    initComponents(); //all the graphics stuff, buttons, etc..
    this.setLocationRelativeTo(null);
    this.bankToUse=bankToUse;
    }


    public static void main(String args[]) {
    //I did this using the swing editor in netbeans so it did all this stuff for me
    try {
    for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
    javax.swing.UIManager.setLookAndFeel(info.getClass Name());
    break;
    }
    }
    } catch (ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(TownRevisit.cla ss.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
    java.util.logging.Logger.getLogger(TownRevisit.cla ss.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(TownRevisit.cla ss.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(TownRevisit.cla ss.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */

    java.awt.EventQueue.invokeLater(new Runnable() {

    @Override
    public void run() {
    new TownRevisit(bankToUse).setVisible(true); //this is my problem


    }
    }
    Last edited by Snake006; 07-15-2013 at 06:22 PM. Reason: messy

  13. #13
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    Huh. Never gotten that error message before, I must admit... Could be that it wasn't compiled properly? Try to recompile it and see if that fixes it.

  14. #14
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    ok, I will try that

  15. #15
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    Ok whenever I try to run it, it says it has errors even though there are no lines in red

  16. #16
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    ok I fixed it, I just needed to put bankToUse everywhere either Town or port is called. Now when I get to port it says the value in my bank is null? It should be the amount leftover from town but it is still null. Why is that.

    Here is what I did in the Port class:

    PHP Code:
    static bankStuff bankToUse;
        public Port(bankStuff bankToUse) {
            
            initComponents();
            this.setLocationRelativeTo(null);
    
            this.bankToUse=bankToUse;
            BankLabel.setText("Gold: " + this.bankToUse);
        }

  17. #17
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    Then you send a null-value to the constructors.

  18. #18
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    so I need bankToUse=null? How might that look? Sorry for all the trouble

  19. #19
    Toll's Avatar
    Toll is offline Senior Member
    Join Date
    May 2011
    Location
    Sweden
    Posts
    392
    Rep Power
    4

    Default Re: How to access a variable in one class from another?

    No, you would need to initialise a bank first before sending it to the constructors.

  20. #20
    Snake006 is offline Senior Member
    Join Date
    Jun 2013
    Posts
    121
    Rep Power
    0

    Default Re: How to access a variable in one class from another?

    Ok so I need to do that in my bank class? This is what I did although I haven't had any luck yet

    public class bankStuff {

    private int bank;

    public bankStuff(){
    bank=0; //won't let me set it equal to null but I thought 0 is the same thing
    }

Page 1 of 3 123 LastLast

Similar Threads

  1. How to Access and Set variable in parent class
    By java_newbie88 in forum New To Java
    Replies: 6
    Last Post: 01-20-2011, 02:48 AM
  2. how to access JSP variable in javascript
    By sauravsinha in forum JavaServer Pages (JSP) and JSTL
    Replies: 1
    Last Post: 03-31-2010, 04:41 PM
  3. variable access from another file
    By riadmazloum in forum AWT / Swing
    Replies: 1
    Last Post: 08-06-2007, 07:13 PM
  4. Access a variable
    By Eric in forum New To Java
    Replies: 2
    Last Post: 07-04-2007, 08:29 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
  •