Passing variables to other classes
Hi the problem im having is ive made 3 classes class A, A1 and A2 when i create A i also create A1 what i am wanting to do is if a condition in A1 is met it will pass a variable to A so A can delete A1 and then create A2, im having some dificulty in passing this variable back to A.
Any help appreciated
You mean you want to return a variable from a method in class A?
Read:
http://java.sun.com/docs/books/tutorial/getStarted/application/objects.html
Similar Messages
-
How to access variables from other class
public boolean inIn(Person p)
if (name == p.name && natInsceNo == p.natInsceNo && dateOfBirth == p.dateOfBirth)
return true;
else
return false;
}//returns true if Person with same name/natInsceNo/dateOfBirth as phello,
here am trying to compare the existing object with another object.
could you please tell me how to access the variables of other class because i meet this error?
name cannot be resolved!
thank you!public class Person
protected String name;
protected char gender; //protected attributes are visible in the subclass
protected int dateOfBirth;
protected String address;
protected String natInsceNo;
protected String phoneNo;
protected static int counter;//class variable
//Constractor Starts, (returns a new object, may set an object's initial state)
public Person(String nme,String addr, char sex, int howOld, String ins,String phone)
dateOfBirth = howOld;
gender = sex;
name = nme;
address = addr;
natInsceNo = ins;
phoneNo = phone;
counter++;
public class Store
//Declaration of variables
private Person[] list;
private int count;
private int maxSize;
//constructor starts
public Store(int max)
list = new Person[max];//size array with parameters
maxSize = max;
count = 0;
}//end of store
//constructor ends
//accessor starts
public boolean inIn(Person p)
return (name == p.name && address == p.address && natInsceNo == p.natInsceNo);
}//returns true if Person with same name/natInsceNo/dateOfBirth as phope it helps now! -
Passing instance to other classes
Hi,
I have the following class
public class myApp extends SingleFrameApplicationWhen I pass the instance like as given below, the instance of SingleFrameApplication is passed. How can I pass the instance of myApp along with this, so that I can access the variables of myApp class from other classes and packages.
new TreeTableView(this);Please help.
Any help in this regard will be well appreciated with points.
Warm Regards,
RonyHi,
i think the constructor of TreeTableView looks sth. like TreeTableView(SingleFrameApplication app), so the TreeTableView takes a SingleFrameApplication and not a myApp. you have two possibilities to access your methods and variables.
1. Extend TreeTableView with a constructor TreeTableView(myApp app)
or
2. You cast the SingleFrameApplication to a myApp everytime you have to access myApp
=>
a = ((myApp)singleFrameApplicationInstance).variable; -
Passing Variables from One Class to Another
Hello, I am new to Java Programming and I'm currently starting off by trying to build a simple application.
I need help to pass variables created in one class to another.
In my source package, I created 2 java classes.
1. Main.java
2. InputFileDeclared.java
InputFileDeclared reads numerical data from an external text file and store them as string variables within the main method while Main converts a text string into a number.
Hence, I would like to pass these strings variables from the InputFileDeclared class to the Main class so that they can be converted into numbers.
I hope somebody out there may enlighten me on this.
Thank you very much in advance!Values are passed from method to method, rather than from class to class. In a case such as you describe the code of a method in Main will probably call a method in InputFileDeclared which will return the String you want. The method in Main stores that in a local variable and processes it. It really doesn't matter here which class the method is in.
You InputFileDeclared object probably contains "state" information in its fields such as the details of the file it's reading and how far it's got, but generally the calling method in Main won't need to know about this state, just the last data read.
So the sequence in the method in Main will be:
1) Create an new instance of InputFileDeclared, probably passing it the file path etc..
2) Repeatedly call a method on that instance to return data values, until the method signals that it's reached the end of file, e.g. by returning a null String.
3) Probably call a "close()" method on the instance, which you should have written to close the file. -
I have two seperate classes in my program.
The class with main sends an LinkedList to the other class with this statement...
PanelB a = new PanelB();
a.setLink(points);Then in my other class I have this code...
public LinkedList q;Then I have a subclass with this code to accept the LinkedList...
public void setLink(LinkedList p, Graphics g){
q = p;At this point everything is great the data is passing along nicely.
Until I try to send the data to another sub class in the same class...
public void paint(Graphics g, LinkedList q) {
int k = q.size();
System.out.println(k);It compiles fine but the program does not print out the size of the LinkedList. It does print it out at every step though before this one. What am I missing or is there a better way of doing all of this?Okay I messed with the code a little bit this is what I got.
public class shapeDraw{
public static void main (String[] args) {
JFrame frame = new JFrame("Shape Outline");
JPanel panel = new PanelB();
panel.setPreferredSize(new Dimension(500,500));
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
LinkedList points = new LinkedList();
PanelB a = new PanelB();
a.setLink(points);
}}I left a lot out of the code to make it easier and quicker to read. This is my next class that is called by this class.
public class PanelB extends JPanel {
public LinkedList q;
public void setLink(LinkedList p){
q = p;
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(Color.red);
Point trig = new Point(10,200), trigB = new Point (50, 300);
double x1=trig.getX();
double x2=trigB.getX();
double y1=trig.getY();
double y2=trigB.getY();
super.paint(g);
g2.draw(new Line2D.Double(x1, y1, x2, y2));
}This code draws a line. I would like bring my ListLinked to this subclass because I want to use the points I have stored in it to draw a picture. -
Accessing public variables from other classes
Probably a simple questions, but how can I access a variable from another class. My exact situation is as follows.
A class called WorldCalender has a variable which is defined: public int hour; (the value is given to it elsewhere).
I want to access this variable and increase it by one in a subroutine in the class Hour. In this class I have put: WorldCalender.hour++; but it doesn't seem to work. How should I do it?don't expose the hour variable at all.
have a method eg addToHourBy( int hrs )
Probably a simple questions, but how can I access a
variable from another class. My exact situation is as
follows.
A class called WorldCalender has a variable which is
defined: public int hour; (the value is given to it
elsewhere).
I want to access this variable and increase it by one
in a subroutine in the class Hour. In this class I
have put: WorldCalender.hour++; but it doesn't seem to
work. How should I do it? -
Use of variables from other class
hallo,
i have two classes A and B
i would like to access a variable of the class B out of A class
without class A extends B or
A classA = new A();
to use
i attempted it with a constructor
class A{
B klb;
public A(B b1){
this.klb = b1;
int a;
a= klb.varausB;
}with that I get, however, a NullPointerException
in a similar form i saw it already once and it functioned
somebody can help me?that is it what I mean
public class ClassA {
ClassB clb;
public ClassA (ClassB cb){
this.clb = cb;
public static void main(String[] args) {
System.out.println("Var from class B:
class B: "+clb.varb1);// there is an error, i know
but how it is right?
public class ClassB {
public String varb1 ="var b1";
}nevertheless so similarly it should function, or?So if you create an instance of ClassA, clb will be initialized. But you don't do that in main. Hence your errors:
1) You're not calling the constructor, so clb is null
2) You're trying to access an instance variable without having an instance, so clb is not only null, it actually doesn't exist.
public static void main(String[] args) {
Class A myA = new ClassA();
System.out.println("Var from class B: "+ myA.clb.varb1);
}You're outside of any object, ehnce you need to address clb through an instance of ClassA. -
Accessing class level variable in other class.
Hi All,
I have one variable declared at class level i.e. global variable (non-static). In one method I am setting one value in this variable.Now I want to access this variable with this new set value in other class.
Can anybody tell me how to do this?
Thanks in advance.
NehaNeha_20 wrote:
Thanks for your reply. But its business req. to have byte[] as return type.
Pls suggest me other approches as well.Comments embedded.
Neha_20 wrote:
*Decode.java*
class Decode
byte[] decodeMessage(byte []datatoReceive)
for(int i=0,j=6; i<dataLen && j<j+responseData.length;i++,j++)
responseData[i] = datatoReceive[j];
System.out.println("Response Data [ "+i +" ]"+responseData);
Syntax syntaxObj1 = new Syntax(); // this creates a Syntax instance
syntaxObj1.returnData(responseData); // this populates it
return responseData; // now it goes out of scope and disappears
Neha_20 wrote:
*User.java*
class User
public static void main(String args[])
// this creates a new unpopulated Syntax instance
Syntax syntaxObj = new Syntax();
for(int i =0;i<syntaxObj.dataRet.length;i++)
System.out.println("dataRet [ "+i+ " ]"+syntaxObj.dataRet); -
How to use Public variables in other classes
Please have a look at the program.
In the below program, i want to use the variable 'name' in the class cl_airplane1 implementation under the method aircraft to display 'BRITISH AIRWAYS' which i am passing through the object AIR1.
The variable 'name' is declared under public section of the class cl_airplane. I do not want to use inheritance. Can i do this.
*& CLASS DEFINITION
CLASS cl_airplane DEFINITION.
PUBLIC SECTION.
METHODS set IMPORTING im_name TYPE string
im_weight TYPE i.
METHODS display.
DATA name TYPE string.
PRIVATE SECTION.
DATA weight TYPE i.
ENDCLASS.
*& CLASS IMPLEMENTATION
CLASS cl_airplane IMPLEMENTATION.
*******METHOD SET*****************
METHOD set.
name = im_name
weight = im_weight.
ENDMETHOD.
*******METHOD DISPLAY**************
METHOD display.
WRITE : / ' NAME :', name, ' AND ', 'WEIGHT:', weight.
ENDMETHOD.
ENDCLASS.
*& END OF CLASS CL_AIRPLANE IMPLEMENTATION
*& CLASS DEFINITION-CL_AIRPLANE1
CLASS cl_airplane1 DEFINITION .
PUBLIC SECTION.
METHODS : aircraft IMPORTING im_name1 TYPE string,
dis1.
ENDCLASS.
*& CLASS IMPLEMENTATION
CLASS cl_airplane1 IMPLEMENTATION.
*******METHOD AIRCRAFT
METHOD aircraft.
ENDMETHOD.
********METHOD DIS1
METHOD dis1.
ENDMETHOD.
ENDCLASS.
**********CREATING REFERENCE VARIABLES
DATA : air TYPE REF TO cl_airplane.
DATA : air1 TYPE REF TO cl_airplane1.
START-OF-SELECTION.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE
CREATE OBJECT air .
CALL METHOD air->set
EXPORTING
im_name = 'Lufthansa'
im_weight = '1000'.
CALL METHOD air->display.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE1
CREATE OBJECT air1.
CALL METHOD air1->aircraft
EXPORTING
im_name1 = 'BRITISH AIRWAYS'.
CALL METHOD air1->dis1.
<removed_by_moderator>
Thanks.
Edited by: Julius Bussche on Jul 30, 2008 3:13 PMHere is ur solution:
*& Report Z157780_PRG1
REPORT z157780_prg1.
*& CLASS DEFINITION
CLASS cl_airplane DEFINITION.
PUBLIC SECTION.
METHODS set IMPORTING im_name TYPE string
im_weight TYPE i.
METHODS display.
DATA name TYPE string.
PRIVATE SECTION.
DATA weight TYPE i.
ENDCLASS. "
*& CLASS IMPLEMENTATION
CLASS cl_airplane IMPLEMENTATION.
********METHOD SET******************
METHOD set.
name = im_name.
weight = im_weight.
ENDMETHOD. "set
********METHOD DISPLAY***************
METHOD display.
WRITE : / ' NAME :', name, ' AND ', 'WEIGHT:', weight.
ENDMETHOD. "display
ENDCLASS. "
*& END OF CLASS CL_AIRPLANE IMPLEMENTATION
*& CLASS DEFINITION-CL_AIRPLANE1
CLASS cl_airplane1 DEFINITION INHERITING FROM cl_airplane.
PUBLIC SECTION.
METHODS : aircraft IMPORTING im_name1 TYPE string,
dis1.
ENDCLASS. "
*& CLASS IMPLEMENTATION
CLASS cl_airplane1 IMPLEMENTATION.
*******METHOD AIRCRAFT
METHOD aircraft.
name = im_name1.
WRITE : / ' NAME :', name.
ENDMETHOD. "aircraft
********METHOD DIS1
METHOD dis1.
ENDMETHOD. "dis1
ENDCLASS. "
**********CREATING REFERENCE VARIABLES
DATA : air TYPE REF TO cl_airplane.
DATA : air1 TYPE REF TO cl_airplane1.
START-OF-SELECTION.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE
CREATE OBJECT air .
CALL METHOD air->set
EXPORTING
im_name = 'Lufthansa'
im_weight = '1000'.
CALL METHOD air->display.
***CREATING AN OBJECT OF THE CLASS CL_AIRPLANE1
CREATE OBJECT air1.
CALL METHOD air1->aircraft
EXPORTING
im_name1 = 'BRITISH AIRWAYS'.
CALL METHOD air1->dis1.
Hope That Helps
Anirban M. -
Pass variable name to class that modifies it
in my main fla:
import Preloader;
var prel:Preloader = new Preloader();
var toPass=9;
prel.loads(this,stage,"toPass",2);
in my Preloader.as:
package {
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
public class Preloader extends Sprite {
private var stageRef:Stage;
private var mainTimeLineRef:*;
public function loads(a,b,c,d):void{
this[c]=d
I want to pass the toPass var to my class that has to edit that, how can i do? (i know that i could simply write toPass = d)i'm not sure what you're trying to do but to pass a variable's value, use:
framode wrote:
in my main fla:
import Preloader;
var prel:Preloader = new Preloader();
var toPass:int=9;
prel.loads(stage,toPass);
in my Preloader.as:
package {
import flash.display.Sprite;
import flash.display.Stage;
import flash.events.Event;
public class Preloader extends Sprite {
private var stageRef:Stage;
private var mainTimeLineRef:*;
private var toPassRef:int;
public function loads(a:Stage,b:int):void{
stageRef=a;
toPassRef=b; -
Passing variables / accessing other swfs
It has been years since I used flash, so I consider myself a
rank armature. I'm Using Flash 8 and would like the code to be
backward-compatible to ver. 6.
I have a big movie, with lots of images. I've comprimised the
image quality as much as I dare, but it still takes 20-30 seconds
to load (my client is in Paris, and claims to have the fastest
connection in Paris, but it takes more than a minute to load it
from there, even when loaded on his local server). I'm assuming
that the only way to achieve a meaningful decrease in load time
will be to split it up into smaller swf's, one mail swf, and each
sub-page in it's own swf, and have each swf loaded only when
needed. The fla can be downloaded here:
cjreynolds.com/fuda30.zip
The movie currently runs an intro animation, then when a link
is clicked, it loads different "pages" which consist of large movie
clips. These are contained in a MC called "pages", and are called
by manipulating a root variable called "level" - ie: "level = 1"
causes the MC at frame 1 of the "pages" MC to be displayed. (this
was an existing movie that I have been tasked with modifying).
#1 - Is it correct that splitting the individual pages into
different swfs the only way to lessen load time? I would welcome
any other suggestions.
#2 - If spitting the movie up is the way to go, I'm thinking
I need to replace the movie clips in the "pages" MC with swfs. How
do I tell each individual page to go back to the main (intro) swf
and load a different page? The main timeline contains animations
that "overlay" the sub-pages, creating a transision effect when
going from one page to the next.
Thanks for your help - you guys (and gals) have been a great
source of aid for me!
joeYes, _root is the wrong thing to use, and _global is never
good practice. I
don't use loadMovieNum - I'd use MovieClipLoader and it's
loadClip method to
load other swf's into target clips. You can then use
something like
this._parent to get to the timeline of the clip 'containing'
the loaded
clip.
However, I think your best bet is to probably use a singleton
class. That
way you have your main movie instantiate and set variables
within the
singleton - then any other movies can easily create an
instance (which will
be the same instance since it's a singleton) and get the
values you need.
Simple example:
class VariableHolder{
private static var instance:VariableHolder;
private var myA:Number;
private function VariableHolder(){}
public static function getInstance():VariableHolder{
if(instance == undefined){
instance = new VariableHolder();
return instance;
public function setVariableA(newA:Number){
myA = newA;
public function getVariableA():Number{
return myA;
So, in your main movie you'd do:
var myVariables = VariableHolder.getInstance();
myVariables.setVariableA(50);
And then in another movie you do:
var myVariables = VariableHolder.getInstance();
var myA = myVariables.getVariableA();
//will set myA = 50;
Because you're using a singleton - the second getInstance()
call returns
just the one class instance - held in the class' instance
variable. You can
have any/all movies instance the class, and only one instance
is ever
returned... Once you wrap your head around this it's a very
efficient way to
pass stuff around between various movies.
Dave -
Head Developer
http://www.blurredistinction.com
Adobe Community Expert
http://www.adobe.com/communities/experts/ -
Passing variables among Jframe classes
I have 2 Jframes and i want one frame to read a variable in the other frame..
How can i do that?It's better practice, really, handle the data from a frame in a more abstracted form, and keep the details of the form elements etc. within the extended frame object.
Say, for instance, one frame has a text account number field then.
public class AccountFrame extends JFrame {
private JTextField accountField;
public String getAccountNumber() {
return accountField.getText();
public String setAccountNumber(String newAccount) {
accountField.setText(newAccount);
...Where there's a whole bunch of fields, then you should consider a "data transfer object", a separate class, usually a bean, which holds the values from the frame as Strings etc.. -
How to access variables from other classe through getter ?
Hi !
I have 10 classes
Cau_1.java containing char Cau_1_Answer;
Cau_2.java... Cau_2_Answer;
Cau_10.java... Cau_10_Answer;
and another class Resume_grammar.java with char[] AnswerList = new Char[10] used to hold cau_1_Answer, Cau_2_Answer...Cau_10_Answer.
but I don't success to get them.
In Cau_1.java, I do :
private static char Cau_1_Answer;
static char getCau_1_Answer() {
return Cau_1_Answer;
static void setCau_1_Answer(char cau_1_Answer) {
Cau_1_Answer = cau_1_Answer;
if (a.isChecked()) {Cau_1_grammar.setCau_1_Answer('a');}
if (b.isChecked()) {Cau_1_grammar.setCau_1_Answer('b');}
if (c.isChecked()) {Cau_1_grammar.setCau_1_Answer('c');}
if (d.isChecked()) {Cau_1_grammar.setCau_1_Answer('d');}
Cau_2, Cau_3...are the same way.
in Resume_grammar.java :
static char[] AnswerList = new char[10];
AnswerList[0] = Cau_1_grammar.getCau_1_Answer();
AnswerList[9] = Cau_10_grammar.getCau_10_Answer();
When I make AnswerList display, all is null (nothing displayed).
Please help ! What I do wrong ?
Thank you !Johnny.vn wrote:
Cau_1 is Question_1 (Vietnamese).
I am developing a academic test application with many question and finally display the result of the test.
Thank you.Back to the original question: why do you need to define different classes for different questions? Do they really behave differently in a way that can't be captured by a single class? -
Using the "this" operator to pass variable references among classes and met
Hi guys still trying to understand how to use the "this" operator
can some one tell what I am doing wrong or just make this work for me to see how it works.
public class ReferencePassing
public static void main(String[]args)
ReferencePassing rp = new ReferencePassing();
System.out.println(rp);
public ReferencePassing()
HelperObject ho = new HelperObject(this);
System.out.println(this);
class HelperObject
private ReferencePassing MyReferencePassingBuddy;
public HelperObject (ReferencePassing theRp);
MyReferencePassingBuddy = theRp;
print();
public void print()
System.out.println(MyReferencePassingBuddy);
}Hi guys still trying to understand how to use the "this" operatorYou're still trying to understand how to write methods and constructors.
public HelperObject (ReferencePassing theRp);Syntax error at ';'.
MyReferencePassingBuddy = theRp;
print();
public void print()Syntax error: '}' expected. -
Pass variable from URLLoader() between classes
I have two classes. See below.
What I want to do is pretty simple but I must not know how to do it. I want the URLFactory to create the Array and store it in the variable "dataArray" and use the Array in the Main class by calling the GetList() of the URLFactory class. What I have returns nothing....please help
Basically I need to set a variable equal to URLLoader.data (var something:String = URLLoader.data) so I can use this variable in other classes. WHY IS THIS NOT MORE SIMPLE??? Please. A solution would be very much appriciated.
package classFiles
import flash.display.MovieClip;
import classFiles.URLFactory;
public class MainClass extends MovieClip {
private var _UrlDriver:URLFactory;
public function MainClass() {
_UrlDriver = new URLFactory("a url");
var temp:Array = _UrlDriver.GetList();
package classFiles
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.sampler.Sample;
public class URLFactory extends MovieClip {
private var loader:URLLoader;
public var textData:String;
public var dataArray:Array;
public function URLFactory(url:String) {
textData = "";
this.dataArray = new Array();
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, HandleComplete);
loader.load(new URLRequest(url));
temp = CreateDataArray();
function HandleComplete(e:Event):void{
textData = loader.data;
trace(dataArray);
function CreateDataArray():void{
trace(dataArray);
dataArray = textData.split("\n");
dataArray = textData.split('","');
public function GetList():Array{
return dataArray;you have a couple of errors. the most serious is trying to retrieve data before it's ready. use:
package classFiles
import flash.display.MovieClip;
import classFiles.URLFactory;
public class MainClass extends MovieClip {
private var _UrlDriver:URLFactory;
public function MainClass() {
_UrlDriver = new URLFactory("a url");
_UrlDriver.addEventListener("dataReadyE",dataReadyF);
private function dataReadyF(e:Event):void{
// it's not likely you want to make temp local.
var temp:Array = _UrlDriver.GetList();
package classFiles
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.display.MovieClip;
import flash.events.Event;
import flash.sampler.Sample;
public class URLFactory extends MovieClip {
private var loader:URLLoader;
public var textData:String;
public var dataArray:Array;
public function URLFactory(url:String) {
textData = "";
this.dataArray = new Array();
loader = new URLLoader();
loader.addEventListener(Event.COMPLETE, HandleComplete);
loader.load(new URLRequest(url));
function HandleComplete(e:Event):void{
textData = loader.data;
temp = CreateDataArray();
dispatchEvent(new Event("dataReadyE"));
function CreateDataArray():void{
trace(dataArray);
dataArray = textData.split("\n");
dataArray = textData.split('","');
public function GetList():Array{
return dataArray;
Maybe you are looking for
-
In bpm I trying to bundle messages. In the loop, in container step I append messages to multiline element "list". In the monitoring I see some entries in the "list", but in transformation step take part only one message. In sxi_cache there is an info
-
How to execute java batch file in JSP
Kindly give a solution. I want execute a batch file which gives a preview window ,. I want call that batch file in my jsp, .I am using Tomcat 5.5, I have tried that using a Process object and Runtime.getRuntime().exec(path) , where path is location o
-
While upgrading, Hold option key on restart abd receive a imagine of a lock
While upgrading or replacing OS 10.2 to 10.4, I Hold option key on restart and receive a imagine of a lock. Haven't the password to unlock. WHAT TO DO? Please. Any work around, or does anyone know a boss password. The usual haven't worked. Thanks in
-
When I copy and paste the weblink to a particular website I wish to paste into an email I'm sending it just pastes it in 'black & white' and after I send it it will not allow you to open it up in the email...It does not create a 'weblink.' You have t
-
Appropriate Phase for Conversions - JSF 1.1 Spec. Contradiction?
It seems that the JSF 1.1 Specification has contradictions: From Section "3.3.2 Converter" it reads: +This method [getAsObject] is used to convert the presentation view of a components value+ +(typically a String that was received as a request param