Using variables in 5 instances of one Class in a seperate Class

I have 5 instances of the one Class all returning different values. These values are parameteres for a final calculation. I am using Sliders as my data validation and I want my final calculation to react to the individual sliders being moved. I need to know the name of the slider and its value or do I?
I would like to Calculate Tractive effort in Extra Panel, I know that all this has something to do with Event Handling but what?
Any and help vastly appreciated otherwise I am goint to eat this computer cables and all.
By the way I Hate Computers!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
Code as follows:
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TractiveEffortCalculator extends JFrame
     private static final long serialVersionUID = 1L;
     public ConstructParametersPanel Instance = new ConstructParametersPanel();
     public ExtraPanel Sample = new ExtraPanel();
     public JPanel thisPanel;
     public TractiveEffortCalculator()
          thisPanel = new JPanel();
          //super ("N Generation Steam"+"           "+"Tractive Effort Calculator");
          BackGroundColour myColor = new BackGroundColour();
          //ConstructParametersPanel Instance = new ConstructParametersPanel();
          GridLayout grid = new GridLayout();
          grid.setColumns(2);
          grid.setHgap(10);
          grid.setRows(1);
          grid.setVgap(5);
          thisPanel.setLayout(grid);
          thisPanel.add(Instance.ConstructParametersPanelMethod());
          thisPanel.add(Sample.ExtraPanelMethod());
          setBackground(myColor.NewBackGroundColour());
          getContentPane().add(thisPanel);
          pack();
          setVisible(true);
          setLocation(40,50);
          setSize(800,600);
          //setResizable(false);
     public static void main(final String[]args)
          final TractiveEffortCalculator app = new TractiveEffortCalculator();
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
public class ConstructParametersPanel extends JPanel
     private static final long serialVersionUID = 1L;
     private JPanel sidePanel;
     TheSliderClass Instance1 = new TheSliderClass();
     TheSliderClass Instance2 = new TheSliderClass();
     TheSliderClass Instance3 = new TheSliderClass();
     TheSliderClass Instance4 = new TheSliderClass();
     TheSliderClass Instance5 = new TheSliderClass();
     public JPanel ConstructParametersPanelMethod()
          sidePanel = new JPanel();
          BackGroundColour myColor = new BackGroundColour();
          GreenColour myColor2 = new GreenColour();
          BlackShadowColour myColor3 = new BlackShadowColour();
          sidePanel.setBorder(BorderFactory.createBevelBorder(1
                                                                      ,myColor2.NewGreenColour()
                                                                      ,myColor3.NewBlackShadowColour()
                                                                      ,myColor2.NewGreenColour()
                                                                      ,myColor3.NewBlackShadowColour()));
          GridLayout grid = new GridLayout();
          grid.setColumns(1);
          grid.setHgap(10);
          grid.setRows(6);
          grid.setVgap(5);
          sidePanel.setLayout(grid);
          sidePanel.setBackground(myColor.NewBackGroundColour());
          sidePanel.add(Instance1.TheSliderClassMethod("Boiler Pressure",200,320));
          sidePanel.add(Instance2.TheSliderClassMethod("Wheel Diameter",60,80));
          sidePanel.add(Instance3.TheSliderClassMethod("Stroke",10,20));
          sidePanel.add(Instance4.TheSliderClassMethod("Piston Rod",2,4));
          sidePanel.add(Instance5.TheSliderClassMethod("Tail Rod",1,3));
          return sidePanel;          
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import javax.swing.BorderFactory;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.NumberFormatter;
public class TheSliderClass extends JPanel implements ChangeListener
     private static final long serialVersionUID = 1L;
     //Add a formatted text field to supplement the slider.
     public JFormattedTextField textField,textField2;
     public String publicSliderName = "";
     public int fps;
     //And here's the slider.
     public JSlider sliderParameterValue;
     JPanel labelAndTextField,allTogether;
     int TractiveEffort = 0;
     public JPanel TheSliderClassMethod(String sliderName, int minimumValue, int maximumValue)
          JPanel allTogether = new JPanel();
          Font font = new Font("palatino linotype regular", Font.BOLD, 12);
          int initialValue = ((minimumValue+maximumValue)/2);
          int tickMarkValue = (maximumValue-minimumValue);
          publicSliderName = sliderName;
          //Create the label.
          JLabel sliderLabel = new JLabel(sliderName,JLabel.CENTER);
          sliderLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
          sliderLabel.setFont(font);
          sliderLabel.setForeground(Color.BLUE);
          //Create the formatted text field and its formatter.
          java.text.NumberFormat numberFormat =
               java.text.NumberFormat.getIntegerInstance();
          NumberFormatter formatter = new NumberFormatter(numberFormat);
          formatter.setMinimum(new Integer(minimumValue));
          formatter.setMaximum(new Integer(maximumValue));
          textField = new JFormattedTextField(formatter);
          textField.setValue(new Integer(initialValue));
          textField.setColumns(3); //get some space
          textField.setEditable(false);
          textField.setForeground(Color.red);
          textField2 = new JFormattedTextField(formatter);
          textField2.setValue(new Integer(initialValue));
          textField2.setColumns(3); //get some space
          textField2.setEditable(false);
          textField2.setForeground(Color.red);
          //Create the slider.
          sliderParameterValue = new JSlider(JSlider.HORIZONTAL,
          minimumValue, maximumValue, initialValue);
          sliderParameterValue.addChangeListener(this);
          //Turn on labels at major tick marks.
          sliderParameterValue.setMajorTickSpacing(tickMarkValue);
          sliderParameterValue.setMinorTickSpacing(10);
          sliderParameterValue.setPaintTicks(true);
          sliderParameterValue.setPaintLabels(true);
          sliderParameterValue.setBorder(
          BorderFactory.createEmptyBorder(0,0,0,0));
                                                  sliderParameterValue.setBackground(Color.cyan);
          //Create a subpanel for the label and text field.
          JPanel labelAndTextField = new JPanel(); //use FlowLayout
          labelAndTextField.setBackground(Color.cyan);      
          labelAndTextField.add(sliderLabel);
          labelAndTextField.add(textField);
          //Put everything together.
          GridLayout gridThis = new GridLayout();
          gridThis.setColumns(1);
          gridThis.setRows(2);
          allTogether.setLayout(gridThis);
          allTogether.add(labelAndTextField);
          allTogether.add(sliderParameterValue);
          allTogether.setBorder(BorderFactory.createBevelBorder(1,Color.red,
                                                                                Color.red));
          return allTogether;
     /** Listen to the slider. */
     public void stateChanged(ChangeEvent e)
          JSlider source = (JSlider)e.getSource();
          fps = (int)source.getValue();
          textField.setText(String.valueOf(fps));
          textField2.setText(String.valueOf(fps));
import java.awt.GridLayout;
import javax.swing.JPanel;
public class ExtraPanel extends JPanel
     private static final long serialVersionUID = 1L;
     public JPanel thisPanel;
     public ConstructParametersPanel aPointer;
     public JPanel ExtraPanelMethod()
          thisPanel = new JPanel();
          aPointer = new ConstructParametersPanel();
          GridLayout grid = new GridLayout();
          grid.setColumns(1);
          grid.setHgap(10);
          grid.setRows(6);
          grid.setVgap(5);
          thisPanel.setLayout(grid);
          return thisPanel;

I don't know if anyone's going to go through all that code...but here's a hint.
if you have 5 sliders and each one represents a separate variable you're going to use in your calculation...you will need to be able to read the change in THAT PARTICULAR slider to update that particular variable and recalculate.
So you have a change state listener: The ChangeEvent passed to the
public void stateChanged(ChangeEvent e) method will have a method called getSource() which you use. However, you aren't figuring out which slider it came from, you're just updating the text areas with info that comes from ANY slider.
You can use e.getSource() to identify which slider it came from.
Say you had the following JSlider sl1, sl2, sl3, sl4.
And each one represents int int1, int2, int3, int4;
what you do in your stateChanged code say
if (e.getSource()==sl1){
int1 = sl1.getValue();
} else if (e.getSource()==sl2){
  int2 = sl2.getValue();
} now you have identified which slider was activated. Hope this helps!

Similar Messages

  • What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?

    Hi All,
    I am new to TestStand. Still in the process of learning it.
    What are Parameters? How are they differenet from Variables? Why can't we use variables for passing data from one sequnece to another? What is the advantage of using Parameters instead of Variables?
    Thanks in advance,
    LaVIEWan
    Solved!
    Go to Solution.

    Hi,
    Using the Parameters is the correct method to pass data into and out of a sub sequence. You assign your data to be passed into or out of a Sequence when you are in the Edit Sequence Call dialog and in the Sequence Parameter list.
    Regards
    Ray Farmer

  • A Cocoa window which is used multiple times (for instances of a class)

    Hi everyone,
    I develop with newest xCode using Obj-C, Java and Cocoa.
    It works perfectly to create a window and connect it to some code: I just design it, and connect it to a class which has been instantiated previously.
    What I need now is a window, which is used multiple times. Means that I create a class where the window should be connected to, from which I create multiple instances.
    I've seen that it works to create a class in Obj-C and just generate the window by code: it works to generate multiple windows. But how would I be able to design a window with InterfaeBuilder for a class which is not yetinstantiated? A class for which I create the instances while my app is running?
    Thanks a lot for your answers!
    -Lucas

    Like PeeJay says, a custom window controller seems the way to go. Try creating a subclass of NSWindowController, with header something like this:
    #import <Cocoa/Cocoa.h>
    @interface MyWindowController : NSWindowController
    IBOutlet NSTextField *infoField;
    -(void)setInfoText:(NSString *)str;
    @end
    The implementation of the setInfoText would be something like:
    -(void)setInfoText:(NSString *)str{
    [infoField setStringValue:str];
    Create a nib file with your window in interface builder. Drop the header file for your custom window controller into the interface builder window. Set the custom class of the nib's File's Owner to MyWindowController. You can then hook up the window and infoField outlets from File's Owner to your window.
    In the body of your code where you open a new info window, add something like:
    MyWindowController *windowController=[[MyWindowController alloc] initWithWindowNibName:@"nameOfWindowNibFile"];
    [windowController setInfoText:@"Whatever"];
    [windowController showWindow:self];
    If you are going to have an undetermined amount of these custom window, it might be a good idea to store the window controller instances in a mutable array, rather than retaining instance variables for each one.
    Jim

  • Creating different instances of one class

    Hi everyone thanks so much for all the help so far! I want to create a new instance of class coauthorship everytime the loop goes around to a new record! However thats not whats happening it only creates 1 instance of coauthorship and it is overwritten with every loop here is Class Coauthorship
    public class Coauthorship {
        private String name, coauthor, title;
        private List titles;
        /** Creates a new instance of Coauthorship */
        public Coauthorship(String name1, String name2, String TITLE){
            name = name1;
            coauthor = name2;
            title = TITLE;
            //List titles = Collections.synchronizedList(new ArrayList(alltitles));
        public String getauthor(){
            return name;
        public void settitle(String TITLE){
            title = TITLE;
        public void setname(String name1){
            name = name1;
       public void setcoauthor( String name2){
            coauthor = name2;
      // public void addTitle(String TITLE){
        //    if(TITLE != null)
        //    titles.add(TITLE);
        public String getcoauthor(){
            return coauthor;
           public String gettitle(){
            return title;
           public int getTitleCount(){
               return titles.size();
             public void printcoauthors(String currentauthor){
             //Extractdata ed = new Extractdata();
            // Coauthorship c = new Coauthorship(ed.getname1(), ed.getname2(), ed.getTITLE());
             if(currentauthor.equals(getauthor()))
                 System.out.println(getcoauthor());
             else if (currentauthor.equals(getcoauthor()))
                 System.out.println(getauthor());
             System.out.println(gettitle());
             System.out.println("Hello is this thing on?");
    }and here is where the values are coming from in Class Extractdata
    //Checks if the document was cowritten
                    if(authors.getLength() > 0)            
                                for(int z = 0; z < authors.getLength(); z++){
                               //Begin with the second author so not to include the author in the list of coauthors
                                        for(int w = 1; w < authors.getLength(); w++){
                                            Coauthorship coauthorship = null;
                                            //Ensures that the author is not counted as a co-author
                                            if(z != w){
                                                name1 = names[z];
                                                name2 = names[w];
                                                Coauthorship c = new Coauthorship(name1, name2, TITLE);
                                                c.setname(name1);                                           
                                                c.setcoauthor(name2);
                                                c.settitle(TITLE);
                                }Thanks so much for everyones help so far

    One thing to remember is that when you write:
    Coauthorship c = new Coauthorship(name1, name2, TITLE);
    Coauthorship c is creating a reference variable that points to an object that is of class type Coauthorship. It is NOT the object itself. It only points to the object in question.
    It is the new Coauthorship(...) that actually creats the object in memory. So each time through the loop you are asking for a new Coauthoriship object and a new reference to that new object. Of course, Java (meaning the JVM) may (or always will - not sure here) re-use the reference variable at the same memory location. You loose the reference to each object create in the previous loop iteration leaving you with a reference pointing to the last object created in the loop when the loop ends.
    If you could state in plain English what your goal is, that would help. From your code, I can tell that the goal (or problem domain) is not clear. Or at least, how to achieve that goal is not clear. State the requirements using ergular words (not psuedo code or such) that would help get things a little clearer.

  • Problem using different Map key types in one class

    I'm running Kodo 2.3.3. It seems I can only have one Map key types for all
    maps in a class. For example, if I have two maps in a class, their keys
    must be of the same type.
    Is there a plan to remove this limitation soon?
    Thanks,

    Abe White wrote:
    Kodo should generate a separate table for each Map. We have internal tests
    that use classes with Map fields using a lot of different key/value type
    combinations, so there shouldn\'t be a problem.It looks like two maps (keyValues and versions) are sharing the same
    table. Here is the table generated by schematool (db: Oracle 8.1.7):
    desc persistentmotiveresourcebean_x;
    Name Null? Type
    ID_JDOIDX VARCHAR2(255)
    JDOKEYX NUMBER
    KEYVALUESX VARCHAR2(255)
    VERSIONSX VARCHAR2(255)
    ==========================================================================
    Following is the simplified code I run:
    -----------internal.jdo--------------------------------------
    <?xml version=\"1.0\"?>
    <jdo>
    <package
    name=\"com.motive.services.resourceManagementService.internal\">
    <class name=\"PersistentMotiveResourceBean\"
    identity-type=\"application\"
    objectid-class=\"com.motive.model.PrimaryKey\">
    <field name=\"id\" primary-key=\"true\"/>
    <field name=\"versions\">
    <map key-type=\"java.lang.Float\"
    embedded-key=\"true\" value-type=\"java.lang.String\"
    embedded-value=\"true\"/>
    </field>
    <field name=\"keyValues\">
    <map key-type=\"java.lang.String\"
    embedded-key=\"true\" value-type=\"java.lang.String\"
    embedded-value=\"true\"/>
    </field>
    </class>
    </package>
    </jdo>
    Java source:
    -----------PersistentMotiveResourceBean.java---------
    package com.motive.services.resourceManagementService.internal;
    import java.util.HashMap;
    public class PersistentMotiveResourceBean
    private String id;
    private String name;
    private HashMap versions;
    private HashMap keyValues;
    public PersistentMotiveResourceBean()
    public String getId() { return id; }
    public void setId(String id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public HashMap getVersions() { return versions; }
    public void setVersions(HashMap versions) { this.versions = versions; }
    public HashMap getKeyValues() { return keyValues; }
    public void setKeyValues(HashMap keyValues) { this.keyValues =
    keyValues; }
    ----------------PrimaryKey.java-------------------------------------
    package com.motive.model;
    import java.io.Serializable;
    public class PrimaryKey implements Serializable
    public String id;
    public PrimaryKey ()
    public PrimaryKey (String id)
    this.id = id;
    public boolean equals (Object ob)
    if (this == ob) return true;
    if (!(ob instanceof PrimaryKey)) return false;
    PrimaryKey o = (PrimaryKey) ob;
    return (this.id == o.id);
    public int hashCode ()
    return id.hashCode();
    public String toString ()
    return id;

  • Using a variable from one class to another

    Hi !
    I've a class called ModFam (file ModFam.java) where I define a variable as
    protected Connection dbconn;
    Inside ModFam constructor I said:
    try
    String url = "jdbc:odbc:baselocal";
    Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
    dbconn = DriverManager.getConnection(url);
    System.err.println("Connection successful");
    } ..... rest of code
    This class define a TabbedPane as follows:
    tabbedPane.addTab("Welcome",null,new Familias(),"Familias");
    As you can see it call a new instance of the Familias class (file Familias.java).
    This constructor will try to connect with the DB to populate a combo box with some data retireved from the DB.
    If I do
    Statement stmt;
    stmt = dbconn.createStatement();
    inside Familias constructor I receive the message
    Familias.java:50: cannot resolve symbol
    symbol : variable dbconn
    location: class fam.Familias
    stmt = dbconn.createStatement();
    at compile time.
    While I can�t use a variable defined as "protected" in one class of my package on another class of the same package ?
    How could I do ?
    Thanks in advance
    <jl>

    Familias doesn't have a reference to ModFam or the Connection.
    So change the constructor in Familias to be
    public class Familias {
      private ModFam modFam;
      public Familias(ModFam m) {
        modFam = m;
    // ... somewhere else in the code
    Statement stmt = modFam.dbconn.createStatement();
    }or
    public class Familias {
      private Connection dbconn;
      public Familias(Connection c) {
        dbconn = c;
    // ... somewhere else in the code
    Statement stmt = dbconn.createStatement();
    }And when you instantiate Familias it should then be
    new Familias(this) // ModFam reference
    or
    new Familias(dbconn)

  • Using variable of one  class in another class

    what are the different ways in which we can access a variable defined in one class in some other class ,i am aware of making object of that class and using variable ,inheritance polymorphisms,is there any other way

    learnerpuneet wrote:
    i don't want to use objects of the respective class to access methods and variablesSo you've given up on OO already?
    Well okay, then declare everything static and you can use class names to access methods and variables.

  • Using a variable from one class in another

    For learning purposes, I thought I'd have a stab at making a role-playing RPG.
    The first class I made was the Player class;
    public class Player
         public static void main(String[] args)
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public static String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public static void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public static void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public static void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public static void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public static void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public static void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public static void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
    }And that would be used in the Play class;
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }     But I'm not sure how the Play class will get the arrays from the Player class. I tried simply putting public in front of the them, for example;
    public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};But I get an illegal start of expression error.
    I may have taken the wrong approach to this all together, I'm completely new, so feel free to suggest anything else. Sorry for any ambiguity.
    Edited by: xcd on Jan 6, 2010 8:12 AM
    Edited by: xcd on Jan 6, 2010 8:12 AM

    HI XCD ,
    what about making Player class as
    public class Player
              // [0] being base points and  [1] being skill points
              int[] points = {50, 10};
              // Elements in statNames are relevent to stats, so stats[0] is health, and so on
              public String[] statNames = {"Health", "Mana", "Attack", "Magic", "Craft"};
              int[] stats = new int[5];
         public String setName()
              Scanner input = new Scanner(System.in);
              System.out.print("Character name: ");
              String name = input.nextLine();
              return name;
         public void setHealth(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Health (" + points[0] + " base points remanining): ");
              stats[0] = input.nextInt();
              points[0] -= stats[0];
            public void setMana(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Mana (" + points[0] + " base points remanining): ");
              stats[1] = input.nextInt();
              points[0] -= stats[1];
         public void setAttack(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Attack (" + points[1] + " skill points remanining): ");
              stats[2] = input.nextInt();
              points[1] -= stats[2];
         public void setMagic(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Magic (" + points[1] + " skill points remanining): ");
              stats[3] = input.nextInt();
              points[1] -= stats[3];
         public void setCraft(int[] points, int[] stats)
              Scanner input = new Scanner(System.in);
              System.out.print("Craft (" + points[1] + " skill points remanining): ");
              stats[4] = input.nextInt();
              points[1] -= stats[4];
         public void setStats(int[] points, int[] stats)
              setHealth(points, stats);
              setMana(points, stats);
              setAttack(points, stats);
              setMagic(points, stats);
              setCraft(points, stats);
         public void charSummary(String name, String[] statNames, int[] stats)
              System.out.println("\n------  " + name);
              for(int index = 0; index < stats.length; index++)
                   System.out.println(statNames[index] + ":\t" + stats[index]);
         }and Play class
    public class Play
         public static void main(String[] args)
              Player player = new Player();
              String name = player.setName();
              player.setStats(points, stats);
         }Now you can access names , you can't assign keyword to variable into method scope , make it class variable .
    Hope it help :)

  • How can I write an instance of a class in a static variable

    Hi !
    I have an instance of a class
    Devisen dev = new Devisen();
    In an other class I have a static method and I need there the content of some variables from dev.
    public static void abc()
    { String text=dev.textfield.getText()
    I get the errormessage, that the I cannot use the Not-static variable dev in a static variable.
    I understand that I cannot reference to the class Devisen because Devisen is not static I so I had to reference to an instance. But an instance is the same as a class with static methodes. (I think so)
    Is there a possibility, if I am in a static method, to call the content of a JTextField of an instance of a class ?
    Thank you Wolfgang

    Hallo, here is more code for my problem:
    class Login {
       Devisen dev=new Devisen();
    class Devisen {
       JTextField field2;
       if (!Check.check_field2()) return; // if value not okay than return
    class Check {
       public static void check_field2()
         HOW TO GET THE CONTENT OF field2 HERE ?
    One solution ist to give the instance to the static function, with the keyword "this"
    if (!Check.check_field2(this)) return;and get the instance
    public static void check_field2(Devisen dev)BUT is that a problem for memory to give every method an instance of the class ? I have 50 fields to control and I dont want do give every check_method an instance of Devisen, if this is a problem for performance.
    Or do I only give the place where the existing instance is.
    Hmm...?
    Thank you Wolfgang

  • How to send a variable from one class to another?

    hello,
    i have "One.as", which is the document class for one.swf.
    i also have "two.swf", with "Two.swf" entered as its document
    class...
    One loads two into it. two is basically a 10 frame movieClip
    with a variable at the beginning called "var endFrame:Boolean =
    false", then on the last frame it says endFrame = true.
    my question: how in the world do I communicate this back to
    One.as??? i've tried ENTER_FRAME listeners, declaring the variable
    here and there... and many other embarrassingly usuccessful
    strategies.
    i would just like to load in "three.swf" after two.swf
    finishes... but One needs to know that it has indeed finished.
    your help would be greatly appreciated. thanks

    yarkehsiow,
    > David,
    > thank you for responding.
    Sure thing! :)
    > so does what you are saying mean that endFrame is a
    property of
    > two (the movieClip), or Two (the Class)?
    If you've written a property named endFrame for your Two
    class, then
    yes, Two.endFrame is a property of that class.
    Looking back at your original post, I see that you wrote
    this:
    > One loads two into it. two is basically a 10 frame
    movieClip
    > with a variable at the beginning called "var
    endFrame:Boolean = false",
    > then on the last frame it says endFrame = true.
    So it sounds like your Two class extends MovieClip. (I'm not
    sure
    that's true, but that's what it sounds like.) That means your
    Two class
    supports all the features of the MovieClip class, including a
    play() method,
    a currentFrame property, and so on. In addition, you've added
    new
    functionality that amounts to -- by the sound of it -- a
    property named
    endFrame. If you made your property public (i.e., public var
    endFrame),
    then it should be accessible by way of an object reference to
    your Two
    instance.
    myTwoInstance.endFrame;
    > so can i invoke that method in One.as? do I call it
    Two.endFrame (if
    > (Two.endFrame == true) {?
    Methods are things an object can *do,* such as
    gotoAndPlay(). What
    you're describing is a property (a characteristic ... in this
    case, a
    Boolean characteristic). You wouldn't use the expression
    Two.endFrame
    unless that property was static. Static classes are those
    that cannot have
    an instance made of them. Think of the Math class. It
    contains numerous
    static properties in the form of constants, such as Math.PI,
    Math.E,
    Math.SQRT2, and so on. You can't create an instance of the
    Math class -- it
    wouldn't make sense to -- so Math is a static class.
    On the other hand, you definitely create instances of the
    MovieClip
    class. Every movie clip symbol is an instance of MovieClip
    class, which
    means that each instance carries its own unique values for
    MovieClip class
    members. The MovieClip class defines x and y properties, but
    each movie
    clip symbol (that is, each instance of the MovieClip class)
    configures its
    own values of those properties, depending on where each
    instance is located
    on the Stage.
    Assuming your Two class is not static, then somewhere along
    the line,
    your One class will have to make an instance of it. Somethine
    like ...
    // inside your One class ...
    var myTwo:Two = new Two();
    ... at which point that myTwo variable because a reference to
    that
    particular instance of Two. You can invoke Two methods on
    that instance.
    You can invoke Two properties and events on that instance.
    You can invoke
    whatever functionality is defined by the Two class on that
    myTwo instance.
    If Two extends MovieClip, that means you can also invoke any
    MovieClip class
    member on that myTwo instance.
    At some point in your One class, you can refer to that myTwo
    instance
    later and check if the value of myTwo.endFrame is true or
    false.
    David Stiller
    Adobe Community Expert
    Dev blog,
    http://www.quip.net/blog/
    "Luck is the residue of good design."

  • Using an array in one class from another

    If I create a new string array in a class, and then set the values in that class, how can I use these value in another class? The way I have tried is to create a new instance of the class that holds the array, but when thinking about it, if I create a new instance surely the value in the array wont have been set? hence why when I am trying to use the array all the values are null.
    Thanks

    You could create a member variable in one class, making the the variable of the other class' type. Then simply call one of the member object's methods, passing the array reference as an argument.

  • How to pass a variable from one class to another class?

    Hi,
    Is it possible to pass a variable from one class to another? For e.g., I need the value of int a for calculation purpose in method doB() but I get an error <identifier> expected. What does the error mean? I know, it's a very, very simple question but once I learn this, I promise to remember it forever. Thank you.
    class A {
      int a;
      int doA() {
          a = a + 1;
          return a;
    class B {
      int b;
      A r = new A();
      r.a;  // error: <identifier> expected. What does that mean ?
      int doB() {
         int c = b/a;  // error: operator / cannot be applied to a
    }Thank you!

    elaine_g wrote:
    I am wondering why does (r.a) give an error outside the method? What's the reason it only works when used inside the (b/r.a) maths function? This is illegal syntax:
    class B {
      int b;
      A r = new A();
      r.a;  //syntax error
    }Why? Class definition restricts what you can define within a class to a few things:
    class X {
        Y y = new Y(); //defining a field -- okay
        public X() { //defining a constructor -- okay
        void f() { //defining a method -- okay
    }... and a few other things, but you can't just write "r.a" there. It also makes no sense -- that expression by itself just accesses a field and does nothing with it -- why bother?
    This is also illegal syntax:
    int doB() {
          A r = new A();
          r.a;  // error: not a statement
    }Again, all "r.a" does on its own is access a field and do nothing with it -- a "noop". Since it has no effect, writing this indicates confusion on the part of the coder, so it classified as a syntax error. There is no reason to write that.

  • Create an instance of my class variable

    Hello all,
    I'm a newbie to iPhone/iPad programming and am having some trouble, I believe the issue is that I'm not creating an instance of my class variable.  I've got a class that has a setter and a getter, I know about properties but am using setters and getters for the time being.  I've created this class in a View-based application, when I build the program in XCode 3.2.6 everything builds fine.  When I step through the code with the debugger there are no errors but the setters are not storing any values and thus the getters are always returning 0 (it's returning an int value).  I've produced some of the code involved and I was hoping someone could point out to me where my issue is, and if I'm correct about not instantiating my variable, where I should do that.  Thanks so much in advance.
    <p>
    Selection.h
    @interface Selection : NSObject {
      int _choice;
    //Getters
    -(int) Choice;
    //Setters
    -(void) setChoice:(int) input;
    Selection.m
    #import "Selection.h"
    @implementation Selection
    //Getters
    -(int)Choice {
      return _choice;
    //Setter
    -(void)setChoice:(int)input{
              _choice = input;
    RockPaperScissorsViewController.m
    #import "RockPaperScissorsViewController.h"
    @implementation RockPaperScissorsViewController
    @synthesize rockButton, paperButton, scissorsButton, label;
    //@synthesize humanChoice, computerChoice;
    -(void)SetLabel:(NSString *)selection{
              label.text = selection;
    -(IBAction)rockButtonSelected {
    //          [self SetLabel:@"Rock"];
              [humanChoice setChoice:1];
    </p>
    So in the above code it's the [humanChoice setChoice:1] that is not working.  When I step through that portion with the debugger I get no errors but when I call humanChoice.Choice later on in the code I get a zero.
    -NifflerX

    It worked, thank you so much.  I put
    humanChoice = [[Selection alloc]init];
    In viewDidLoad and it worked like a charm.  Thank you again.
    -NifflerX

  • Accessing a variable defined in one class from another class..

    Greetings,
    I've only been programming in as3 for a couple months, and so far I've written several compositional classes that take MovieClips as inputs to handle behaviors and interactions in a simple game I'm creating. One problem I keep coming upon is that I'd love to access the custom variables I define within one class from another class. In the game I'm creating, Main.as is my document class, from which I invoke a class called 'Level1.as' which invokes all the other classes I've written.
    Below I've pasted my class 'DieLikeThePhishes'. For example, I would love to know the syntax for accessing the boolean variable 'phish1BeenHit' (line 31) from another class. I've tried the dot syntax you would use to access a MovieClip inside another MovieClip and it doesn't seem  to be working for me. Any ideas would be appreciated.  Thanks,
    - Jeremy
    package  jab.enemy
    import flash.display.MovieClip;
    import flash.events.Event;
    import jab.enemy.MissleDisappear;
    public class DieLikeThePhishes
    private var _clip2:MovieClip; // player
    private var _clip3:MovieClip; //phish1
    private var _clip4:MovieClip; //phish2
    private var _clip5:MovieClip; //phish3
    private var _clip6:MovieClip; //phish4
    private var _clip10:MovieClip; // background
    private var _clip11:MovieClip // missle1
    private var _clip12:MovieClip // missle2
    private var _clip13:MovieClip // missle3
    private var _clip14:MovieClip // missle4
    private var _clip15:MovieClip // missle5
    private var _clip16:MovieClip // missle6
    private var _clip17:MovieClip // missle7
    private var _clip18:MovieClip // missle8
    private var _clip19:MovieClip // missle9
    private var _clip20:MovieClip // missle10
    private var _clip21:MovieClip // missle11
    private var _clip22:MovieClip // missle12
    var ay1 = 0;var ay2 = 0;var ay3 = 0;var ay4 = 0;
    var vy1 = 0;var vy2 = 0;var vy3 = 0;var vy4 = 0;
    var phish1BeenHit:Boolean = false;var phish2BeenHit:Boolean = false;
    var phish3BeenHit:Boolean = false;var phish4BeenHit:Boolean = false;
    public function DieLikeThePhishes(clip2:MovieClip,clip3:MovieClip,clip4:MovieClip,clip5:MovieClip,clip6:M ovieClip,clip10:MovieClip,clip11:MovieClip,clip12:MovieClip,clip13:MovieClip,clip14:MovieC lip,clip15:MovieClip,clip16:MovieClip,clip17:MovieClip,clip18:MovieClip,clip19:MovieClip,c lip20:MovieClip,clip21:MovieClip,clip22:MovieClip)
    _clip2 = clip2;_clip3 = clip3;_clip4 = clip4;_clip5 = clip5;_clip6 = clip6;
    _clip10 = clip10;_clip11 = clip11;_clip12 = clip12;_clip13 = clip13;_clip14 = clip14;
    _clip15 = clip15;_clip16 = clip16;_clip17 = clip17;_clip18 = clip18;_clip19 = clip19;
    _clip20 = clip20;_clip21 = clip21;_clip22= clip22;
    _clip3.stage.addEventListener(Event.ENTER_FRAME, onEnterFrame)
    function onEnterFrame(event:Event):void
    vy1+= ay1;_clip3.y += vy1; vy2+= ay2;_clip4.y += vy2;
    vy3+= ay3;_clip5.y += vy3; vy4+= ay4;_clip6.y += vy4;
    if (phish1BeenHit ==false)
    if(_clip3.y >620)
    {_clip3.y = 620;}
    if (phish2BeenHit ==false)
    if(_clip4.y >620)
    {_clip4.y = 620;}
    if (phish3BeenHit ==false)
    if(_clip5.y >620)
    {_clip5.y = 620;}
    if (phish4BeenHit ==false)
    if(_clip6.y >620)
    {_clip6.y = 620;}
    if (_clip11.hitTestObject(_clip3) ||_clip12.hitTestObject(_clip3)||_clip13.hitTestObject(_clip3)||_clip14.hitTestObject(_cl ip3)||_clip15.hitTestObject(_clip3)||_clip16.hitTestObject(_clip3)||_clip17.hitTestObject( _clip3)||_clip18.hitTestObject(_clip3)||_clip19.hitTestObject(_clip3)||_clip20.hitTestObje ct(_clip3)||_clip21.hitTestObject(_clip3)||_clip22.hitTestObject(_clip3))
    _clip3.scaleY = -Math.abs(_clip3.scaleY);
    _clip3.alpha = 0.4;
    ay1 = 3
    vy1= -2;
    phish1BeenHit = true;
    if (_clip11.hitTestObject(_clip4) ||_clip12.hitTestObject(_clip4)||_clip13.hitTestObject(_clip4)||_clip14.hitTestObject(_cl ip4)||_clip15.hitTestObject(_clip4)||_clip16.hitTestObject(_clip4)||_clip17.hitTestObject( _clip4)||_clip18.hitTestObject(_clip4)||_clip19.hitTestObject(_clip4)||_clip20.hitTestObje ct(_clip4)||_clip21.hitTestObject(_clip4)||_clip22.hitTestObject(_clip4))
    _clip4.scaleY = -Math.abs(_clip4.scaleY);
    _clip4.alpha = 0.4;
    ay2 = 3
    vy2= -2;
    phish2BeenHit = true;
    if (_clip11.hitTestObject(_clip5) ||_clip12.hitTestObject(_clip5)||_clip13.hitTestObject(_clip5)||_clip14.hitTestObject(_cl ip5)||_clip15.hitTestObject(_clip5)||_clip16.hitTestObject(_clip5)||_clip17.hitTestObject( _clip5)||_clip18.hitTestObject(_clip5)||_clip19.hitTestObject(_clip5)||_clip20.hitTestObje ct(_clip5)||_clip21.hitTestObject(_clip5)||_clip22.hitTestObject(_clip5))
    _clip5.scaleY = -Math.abs(_clip5.scaleY);
    _clip5.alpha = 0.4;
    ay3 = 3
    vy3= -2;
    phish3BeenHit = true;
    if (_clip11.hitTestObject(_clip6) ||_clip12.hitTestObject(_clip6)||_clip13.hitTestObject(_clip6)||_clip14.hitTestObject(_cl ip6)||_clip15.hitTestObject(_clip6)||_clip16.hitTestObject(_clip6)||_clip17.hitTestObject( _clip6)||_clip18.hitTestObject(_clip6)||_clip19.hitTestObject(_clip6)||_clip20.hitTestObje ct(_clip6)||_clip21.hitTestObject(_clip6)||_clip22.hitTestObject(_clip6))
    _clip6.scaleY = -Math.abs(_clip6.scaleY);
    _clip6.alpha = 0.4;
    ay4 = 3
    vy4= -2;
    phish4BeenHit = true;
    if (_clip3.y > 10000)
    _clip3.x = 1000 +3000*Math.random()-_clip10.x;
    _clip3.y = 300;
    _clip3.alpha = 1;
    _clip3.scaleY = Math.abs(_clip3.scaleY);
    ay1 = vy1 = 0;
    phish1BeenHit = false;
    if (_clip4.y > 10000)
    _clip4.x = 1000 +3000*Math.random()-_clip10.x;
    _clip4.y = 300;
    _clip4.alpha = 1;
    _clip4.scaleY = Math.abs(_clip4.scaleY);
    ay2 = vy2 = 0;
    phish2BeenHit = false;
    if (_clip5.y > 10000)
    _clip5.x = 1000 +3000*Math.random()-_clip10.x;
    _clip5.y = 300;
    _clip5.alpha = 1;
    _clip5.scaleY = Math.abs(_clip5.scaleY);
    ay3 = vy3 = 0;
    phish3BeenHit = false;
    if (_clip6.y > 10000)
    _clip6.x = 1000 +3000*Math.random()-_clip10.x;
    _clip6.y = 300;
    _clip6.alpha = 1;
    _clip6.scaleY = Math.abs(_clip6.scaleY);
    ay4 = vy4 = 0;
    phish4BeenHit = false;
    var missleDisappear1 = new MissleDisappear(_clip11,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear2 = new MissleDisappear(_clip12,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear3 = new MissleDisappear(_clip13,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear4 = new MissleDisappear(_clip14,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear5 = new MissleDisappear(_clip15,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear6 = new MissleDisappear(_clip16,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear7 = new MissleDisappear(_clip17,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear8 = new MissleDisappear(_clip18,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear9 = new MissleDisappear(_clip19,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear10 = new MissleDisappear(_clip20,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear11 = new MissleDisappear(_clip21,_clip3,_clip4,_clip5,_clip6,_clip10);
    var missleDisappear12 = new MissleDisappear(_clip22,_clip3,_clip4,_clip5,_clip6,_clip10);

    I would approach it in much the same way as you would in java, by making getters and setters for all of your class variables.
    Getters being for returning the values, Setters being for setting them.
    So you would make a get function for the variable you want to access ala:
    function get1PhishBeenHit():boolean {
         return this.phish1BeenHit;
    Then to access the value of that variable from outwith the class:
    var result:boolean = ClassInstanceName.get1PhishBeenHit();

  • Use of swings- one class calling the gui class

    Hi,
    I have a class Manager and a class ManagerGUI.
    My ManagerGUI class looks somehting like this-
    public class ManagerGUI extends JFrame
    String name;
    JPanel namePanel;
    JTextField nameInput;
    JLabel nameLabel;
    Manager empAgent;
    ManagerGUI(Manager ea)
    super(ea.getLocalName());
    empAgent = ea;
    //make the name panel and add it to the topPanel.
    addListeners();
    getContentPane().add(topPanel, BorderLayout.CENTER);
    setResizable(false);
    }//end constructor.
    public void show()
    pack();
    super.setVisible(true);
    void addListeners()
    nameInput.addActionListener(new NameL());
    class NameL implements ActionListener
    public void actionPerformed(ActionEvent e)
    nameE = nameInput.getText();
    }//end class ManagerGUI.
    I have tried to seperate it out so that any changes can be easily implemented (although it perhaps is a long way of doing things).
    Now I have a class Manager that wants to call the GUI and then process the information got from the text field.
    I use the following lines to call the GUI class.
    manGui = new ManagerGUI(this);
    manGui.show();
    Is this the correct way of calling the GUI class?
    How do I get to use the variable nameE here, in the Manager?
    Thanks.

    Hi,
    I have no idea why you want to have an instance of Manager class in class ManagerGUI and an instance of ManagerGUI class in Manager class.
    I will create an instance of Manager in ManagerGUI and show the GUI there.
    In Manager you can create method that will accept the text from textfield in parameter.
    L.P.

Maybe you are looking for