Sending Variables To a Class
Hi;
I have a package with (naturally) one class in it. A function in this class repeatedly calls another class in the same *.as file (after the package). However, on each call I need to change a number of variables. How do I do this? My background is python. In python I'd just pass values to the variables of the class. It doesn't look like I can do that here. Please advise.
TIA,
beno
yes. check getter and setter functions.
Similar Messages
-
Sending a variable from one class to another?
Dear Java Users - please can you help me out here... I know that what I am asking should be straight forward BUT I just don't understand any of the responses people have put on the web....
Here is what I am trying to do:
This piece of code - creates a window with a simple textbox on it to enter a word...
The button then calls another class file to open a new window...
All I want to do is to take the word from the text box and print it in the new window....
The first .java file I have is this:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class FrontPageGUI extends JFrame implements ActionListener
//declare all instance variables for THIS per class
JLabel lblInfoOne;
JLabel lblButtonPopUp;
JTextField txtName;
JButton close;
JButton popUp;
public FrontPageGUI()
//set characteristics of the JFrame object
super("Title Bar");
setSize(600,600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
//we need to define a Container to place objects onto the frame - this is inside the JFrame Object Above
Container ca = getContentPane( );
ca.setSize(600,600);
ca.setBackground(Color.white);
ca.setLayout(null);
//define all other objects and set thier characteristics
lblInfoOne = new JLabel("Enter a word in the box above to send:");
lblButtonPopUp = new JLabel("Click Here:");
txtName = new JTextField("");
//create Button components
close = new JButton("Close");
popUp = new JButton("Click Me");
//now add all objects to the container
//Labels
addXY(ca,lblInfoOne, 30, 160, 550,45);
addXY(ca,lblButtonPopUp, 30, 210, 550,45);
//TextField
addXY(ca,txtName, 120, 100, 200,30);
//Buttons
addButtonXY(ca, popUp, 30, 260, 200, 45);
addButtonXY(ca, close, 30, 310, 80, 30);
// add the Container to the Frame
setContentPane(ca);
void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
cp.addActionListener(this);
c.add(cp);
void addXY(Container c, Component cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
c.add(cp);
public void actionPerformed(ActionEvent event)
if (event.getSource()== popUp)
//This is WHERE THE PROBLEM IS...
//Here I want to send to contents of the textfield - txtName
String temp = txtName.getText();
new PopUpGUI(temp);
if (event.getSource()==close)
closeUp();
void closeUp()
System.exit(0);
//dispose();
//we need a driver program - this is the only time MAIN is used.
public class FrontPage
//create an instance of the GUI and showit
public static void main(String args [])
new FrontPageGUI();
The second .java file I have is this:
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class PopUpGUI extends JFrame implements ActionListener
//declare all instance variables ie per class
JLabel headerLabel;
JLabel sentLabel;
JButton close;
public PopUpGUI(String Sent)
//set characteristics of the JFrame object
super("Pop Up Window");
setSize(320,450);
setVisible(true);
//need to define a Container to place objects onto the frame
Container ca = getContentPane( );
ca.setSize(320,450);
ca.setLayout(null);
//define all other objects and set characteristics
headerLabel = new JLabel("New Window!"); //heading label
sentLabel = new JLabel(Sent);
close = new JButton("Close");
//now add all objects to the container
addXY(ca,headerLabel,10,10,380,80);
addXY(ca,sentLabel,10,100,380,80);
addButtonXY(ca, close, 50, 200, 100, 30); //Bottom Left
// add the Container to the Frame
setContentPane(ca);
//We need these 2 methods - EVERY TIME
void addButtonXY(Container c, JButton cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
cp.addActionListener(this);
c.add(cp);
void addXY(Container c, Component cp, int x, int y, int w, int h)
cp.setBounds(x,y,w,h);
c.add(cp);
//What to do when the click happens
public void actionPerformed(ActionEvent event)
if (event.getSource()==close)
dispose();
//closeUp(); - Doesn't run CLOSEUP this time (i.e. exit program) - instead just DISPOSEs of the window
//Driver class is in FrontPage.javaThis seems to work... but is it the best way to do it????
Tony.Well,
Using the constructor is the way to go. Otherwise create a method that takes the string as parameter. -
What Class/Method/Object's would I use to send variable form data to BradySoft? I have a basic label setup in BradySoft and I want to send it variable form data (a serial number) from Labview ActiveX. I have attached Brady's ActiveX programmers guide but can't figure out what to use for this. P.S. I would call Brady or TekLynx tech support about this but they have a strict policy whereas BradySoft supports ActiveX but their tech support doesn't provide programming help with it. I figured I'd try the NI Forums.
Aaronb, I presume by publishing an ActiveX programmers manual the BradySoft software installs Active X objects. You may choose to interact with these objects within LabVIEW using Active X controls. The following link will provide a starting point for LabVIEW help topics on Active X communication: Select ActiveX Object Dialog Box
http://zone.ni.com/reference/en-XX/help/371361F-01/lvdialog/insert_active_x_object/
Building a Simple Web Browser Using ActiveX (Example of ActiveX arcitecture)
http://zone.ni.com/devzone/cda/epd/p/id/81 Hope this helps provide a bit of guidance. Cheers! -
Sending variables between classes
hi,
I have a question, in one class, not the main class, I have several data readed from a file and I want to send it to another class for processing.
Any one can give an example how to do it?if (event.getSource()==search)
ID = txtID.getText();
name = txtName.getText();
if (ID.equals("Client"))
FileReader rf=new FileReader("Client.txt");
ds =new BufferedReader(rf);
String namas = ds.readLine();
int i = Integer.parseInt(namas);
int ananasas = i*4;
for(int kaminas = 0; kaminas < ananasas; kaminas++)
String lyginam = ds.readLine();
if (lyginam.equals(name))
String a = ds.readLine();
String b = ds.readLine();
double ba = Double.parseDouble(b);
break;
if (ID.equals("Employee"))
FileReader rf=new FileReader("Employee.txt");
ds =new BufferedReader(rf);
String namas = ds.readLine();
int i = Integer.parseInt(namas);
int ananasas = i*4;
for(int kaminas = 0; kaminas < ananasas; kaminas++)
String lyginam = ds.readLine();
if (lyginam.equals(name))
String c = ds.readLine();
double a = Double.parseDouble(c);
String ba = ds.readLine();
double b = Double.parseDouble(ba);
break;
new Search();
}The data(double a, double b, String a, double b) needs to be sent to class called Search in here (depending on what "if" will it fall)
Edited by: ErnestasAbra on May 5, 2009 8:30 AM -
Sending variables to other programs
im trying to send variables to another program called math_problems
however, im getting an error that says 'cannot resolve symbol'
here's my code:
public class Event_Listener implements ActionListener
private control_panel idunno;
public Event_Listener (control_panel t)
idunno = t;
public void actionPerformed(ActionEvent ev)
if(ev.getSource() == idunno.done)
String operation, position;
String min = idunno.minField.getText();
String max = idunno.maxField.getText();
String digit = idunno.digitsField.getText();
String number = idunno.numberField.getText();
if(addBtn.isSelected())
operation = addString;
else if(subBtn.isSelected())
operation = subString;
else if(multiBtn.isSelected())
operation = multiString;
else if(divBtn.isSelected())
operation = divString;
else operation = addString;
if(vertBtn.isSelected())
position = "Vertical";
else if(horBtn.isSelected())
position = "Horizontal";
else position = "Vertical";
System.out.println("Min = " + min);
System.out.println("Max = " + max);
System.out.println("# of digits = " + digit);
System.out.println("# of problems = " + number);
System.out.println("Operation = " + operation);
System.out.println("Position = " + position);
math_problems mp = new math_problems(operation, position, min, max, digit, number);
}dont worry about it.
i solved it -
I am loading swf with a Loader class. I also send variable to
the swf like that:
var request:URLRequest = new URLRequest("../Top/Top.swf")
var variable:URLVariables = new URLVariables();
variable.myVar= "self";
request.data = variable;
request.method = URLRequestMethod.POST;
topLoader = new Loader()
topLoader.contentLoaderInfo.addEventListener(Event.COMPLETE,
onLoadComplete)
topLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,
onLoadError)
topLoader.load(request)
In the loaded swf I am trying to get the myVar variable like
that but I am getting undefined value:
root.loaderInfo.parameters.myVar
What do I do wrong????quote:
Originally posted by:
shikozel
request.method = URLRequestMethod.POST;
Hi. You want to go a GET, not a POST request. So eliminate
that line.
Jak sie masz -
How to call a variable in another class????
if i have two classes in a package. From one class, how do i get the value of one of the variable in the other class.
For example;
Class A have a variable call totalNum which have a value initialise.
Class B wan to get the value variable totalNum in class A.
So do i go abt calling it?
CheersFor example;
Class A have a variable call totalNum which have a
value initialise.
Class B wan to get the value variable totalNum in
class A.Your explanation is far from clear. Is the variable in class A a field? If yes, is it a static field? Is it declared public, private, etc.?
If you don't understand the above questions, you should do the following:
1) Learn the basics of the Java language from the Java Tutorial and/or from an entry-level book: http://java.sun.com/docs/books/tutorial/
2) Post future question in the New To Java Technology forum. -
Is there a way to reference a private variable from one class in another?
My first class starts off by declaring variables like so:
class tStudent {
// declare student name, id, grades 1 & 2, and gpa
private String fname, lname, g1, g2;
private int id;
private double gpa;
// define a constructor for a new student
tStudent () {fname=lname=g1=g2=null; id=-1; gpa=0.0;}
// define methods for manipulating the data members.
// readStudent: reads information for just one student
public void read (Scanner input) {
fname = input.next();
lname = input.next();
id = input.nextInt();
g1 = input.next();
g2 = input.next();
}And the second class:// tStudentList: for a list of students
class tStudentList {
private int nStudents;
private tStudent[] list;
// constructor for creating student list
tStudentList() {
list = new tStudent[36];
for (int i=0; i < 36; i++) list=new tStudent();
// read the individual students into the student list
public void read(Scanner scan) {
nStudents=0;
while (scan.hasNext()) {list[nStudents++].read(scan);}
// display the list of all students - fname, lname, id, g1, g2 and gpa
// with an appropriate header so the output matches my sample //output
public void print() {
Is there a way to reference the variables in the first class to use in the second? Specifically in the last section of code where I am going to print the list.Not without resorting to reflection hackery. If the fields are private (and are supposed to be), then that means "don't allow access to these to outsiders of this class" by design.
So if you really meant them to be accessible, then don't use private, or provide public accessors for them. -
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! -
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) -
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. -
Moving Variable from one class to another.
I need to get a Variable from one class to another how would I do this?
Well this is a very tipical scehario for every enterprise application. You always create logger classes that generate log files for your application, as that is the only way to track errors in your system when its in the production enviorment.
Just create a simple class that acts as the Logger, and have a method in it that accepts a variable of the type that you are are trying to pass; most commonly a String; but can be overloaded to accept constom classes. e.g.
class Logger
public void log(String message)
writeToFile("< " + new Date() + " > " + message);
public void log(CustomClass queueEvent)
log("queue message was: " + queueEvent.getMessage() + " at: " + queueEven.getEventTime());
}Hope this makes things clearer
Regards
Omer -
Send mail through CL_BCS class with normal priority
Hello guys!!!
I'm trying to send email through CL_BCS class, and it's work fine!
But, always sent with high priority, and I need to send whith normal priority.
I tried this:
DATA: o_send_request TYPE REF TO cl_bcs,
o_document TYPE REF TO cl_document_bcs.
o_document = cl_document_bcs=>create_document(
i_type = 'HTM'
i_text = msgbody
i_subject = subject
i_importance = '5' ).
And this:
CALL METHOD o_send_request->send_request->setu_priority
EXPORTING
i_priority = o_send_request->cp_priority_normal.
Unfortunately, don't works.
Any idea?
Thanks!!!
Kleber S. KieferHi,
Please try the following solution:
* set mail importance to normal
TRY.
lo_document ?= lo_send_request->document( ).
lo_document->set_importance( i_importance = '5' ).
CATCH cx_sy_move_cast_error.
ENDTRY.
In addition, in the Alert framework, which send emails with high priority, it controls the document's importance and then send out the emails with high priority.
* create send request, document etc..
TRY.
lo_document = cl_document_bcs=>create_document(
i_type = l_texttype
i_text = lt_text
i_importance = '1'
i_language = ls_langu_recipient-langu
i_subject = l_subject_short
i_length = l_so_obj_len ). -
Make a variable in a class av ail. to main tl
I thought putting public in front of a variable made it
available to the main timeline, but it doesnt. How do you make it
available to the main tl? Should I just put it on the main
tl?You are accessing the variable through the class name
"Class", that is a flash built-in class.
If you copy and paste the code as I wrote it it doesn't give
any problem... Anyway, can you paste your code here? -
How to update and use the values of variables of another class
I can we update or use the values of the variables of another class. For example, if we have class A
public class A //(situated in package view)
public s0,s1;
public void runFunction()
...some coding and proceedings
s0="Hi";s1"Hello";
......some coding
RequestDispatcher dispatcher = request.getRequestDispatcher("/MainUser.jsp?alert=F");
dispatcher.forward(request, response);
ARunner.jsp
<jsp:useBean id="a" class="view.A" scope="session"/>
<%
a.runFunction();
%>
MainUser.jsp
<jsp:useBean id="a" class="view.A" scope="session"/>
<%
System.out.println("S0:"+a.s0+" S1:"+a.s1); //should print S0:Hi S1:Hello, but printing S0:null S1:null
%>
A.class has some procedures and String variables which can be updated and later can be used in JSP pages. The project starts with ARunner.jsp which uses the A.class and updates the values of string variables s0 and s1of A to hi and hello respectively.And then redirects the page to MainUser.jsp.
Now what I want is ,when I call those string variables(s0 & s1 of A.class) in any another jsp likeMainUser.jsp it should give me the value of hi and hello respectively not null as it is giving right now. Could you refine the coding for this one?public class A //(situated in package view)
public String s0,s1;
public void runFunction()
...some coding and proceedings
s0="Hi";s1"Hello";
......some coding
RequestDispatcher dispatcher = request.getRequestDispatcher("/MainUser.jsp");
dispatcher.forward(request, response);
ARunner.jsp
<jsp:useBean id="a" class="view.A" scope="session"/>
<%
a.runFunction();
%>
MainUser.jsp
<jsp:useBean id="a" class="view.A" scope="session"/>
<%
System.out.println("S0:"+a.s0+" S1:"+a.s1); //should print S0:Hi S1:Hello, but printing S0:null S1:null
%>
giving code again to remove the typing errors. Please guide.
Maybe you are looking for
-
As above. Additional point my previous trial was still active on my defunct computer. Would this prevent it opening on my new computer.
-
Using Mt. Lion 8.2. Trash is requiring a password all of a sudden for no apparent reason. I already ran disk utilities and permissions repair with no positive effect on the problem. Any suggestions?
-
Simple select stmt in Procedure (?) - with example
I am having problems getting the following code example to work. CREATE OR REPLACE PROCEDURE Portdev.Show_One_Record v_record_question quiz.quest_num%ROWTYPE AS BEGIN CURSOR c_records IS -- will get all records ordered randomly, matching category as
-
Website needs Microsoft Data Access - Active X Data Objects
I have a number of websites for work that are seem to be built around Internet Explorer. When I try to open them on my Mac at home with Safari, I get message that I pasted below. I'm thinking this might be related to the fact that when I open them on
-
Roxio Media error "the certificate file is missing or has been corrupted."
Hi, ive had my blackberry since earlier this year. I am now getting an error message when i try to open up media manager. I am getting an error which states: "the certificate file is missing or has been corrupted." can someone help me figure this one