Defining variables from a class gives errors
Hi,
I'm trying to create a questionnaire, that can hold an array
of questions.
The questions can be of different types, like single punch,
multi punch, open text etc.
Much of the code below is copied from examples I've found and
I am definitely in the beginning
of my learning process when it comes to Flex, but I think
Flex can solve a problem I have at work.
So, I'm trying to cut corners...
I created this class called Questions, which contains all
properties any question can have.
When I'm trying to define a variable (myQuestion) based on
that class, I the following error.
(actually I get it on all properties...)
Error:
1120: Access of undefined property Qtype.
This is the class definition:
package Mycomponents
//import other classes needed
//import Mycomponents.Codeframe
public class Question {
// Define properties and methods.
// Define public vars.
public var Qtype:String="";
public var Condition:String="";
public var Qnumber:String="";
public var Qheading:String="";
public var Pretext:String="";
public var Qtext:String="";
public var Posttext:String="";
public var Codeframe:String;
public var Reserved:String="";
public var EditableFrom:String="";
public var EditableTo:String="";
public var Decimal:String="";
public var SetQfactor:String="";
public var Logic_if:String="";
public var Logic_then:String="";
// Public constructor.
public function Question(
Qtype:String,
Condition:String,
Qnumber:String,
Qheading:String,
Pretext:String,
Qtext:String,
Posttext:String,
Codeframe:String,
Reserved:String,
EditableFrom:String,
EditableTo:String,
Decimal:String,
SetQfactor:String,
Logic_if:String,
Logic_then:String )
this.Qtype=Qtype;
this.Condition=Condition;
this.Qnumber=Qnumber;
this.Qheading=Qheading;
this.Pretext=Pretext;
this.Qtext=Qtext;
this.Posttext=Posttext;
this.Codeframe=Codeframe;
this.Reserved=Reserved;
this.EditableFrom=EditableFrom;
this.EditableTo=EditableTo;
this.Decimal=Decimal;
this.SetQfactor=SetQfactor;
this.Logic_if=Logic_if;
this.Logic_then=Logic_then;
This is the part of the code that generates the error:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="
http://www.adobe.com/2006/mxml"
layout="absolute">
<mx:Script>
<![CDATA[
import mx.states.State;
import mx.controls.Alert;
import mx.events.CloseEvent;
import flash.events.KeyboardEvent;
import Mycomponents.Codeframe;
import Mycomponents.Question;
public var myQuestion:Question = new Question(
Qtype,
Condition,
Qnumber,
Qheading,
Pretext,
Qtext,
Posttext,
Codeframe,
Reserved,
EditableFrom,
EditableTo,
Decimal,
SetQfactor,
Logic_if,
Logic_then
....more code...
...what am I missing in defining this variable?
If you have a link to a good book on Flex...let me know.
Regards
/Acke
When you create your local variable myQuestion, where are the
parameters (used in the constructor) declared and initialized?
var _qType = "some value";
var myQ:Question = new Question(_qType,"","" etc);
Also good OO practice is to declare your variables as private
and add getters and setters for the values. Sometimes you may want
to manipulate the values when getting or setting.
If you use the standard AS3 get and set then declare your
vars with an _
so as not to conflict with the getter and setter. For exampe:
public class MyClass
private var _var1:String;
public function get var1():String
return _var1;
public function set var1(v:String):void
_var1 = v;
This may seem like extra work, but in a complex application
with lots of classes
encapsulating updating of members will save you lots of
headaches.
Similar Messages
-
Error when defining a variable from a class
Hi,
I'm getting this error message when trying to define a
variable from a class:
'1086: Syntax error: expecting semicolon before left paren.'
I can't see where the error is.
The scripts Question.as and Codeframe.as is located int the
folder Mycomponents under the project.
Regards
/Acke
**** Main app *****
<mx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.events.CloseEvent;
import myComponents.*;
var Question():myComponents.Question=new Question(); // !!
This line causes the error !!
other code goes here....
]]>
</mx:Script>
**** The class definition ******
package myComponents
//import other classes needed
import Mycomponents.Codeframe
public class Question {
// Define properties and methods.
// Define public vars.
public var Qtype:string;
public var Condition:string;
public var Qnumber:string;
public var Qheading:string;
public var Pretext:string;
public var Qtext:string;
public var Posttext:string;
public var Codeframe():string;
public var Reserved:string;
public var EditableFrom:string;
public var EditableTo:string;
public var Decimal:string;
public var SetQfactor:string;
public var Logic_if():string;
public var Logic_then():string;
// Public constructor.
//public function Question(){
// do stuff to set initial values for properties
public function Question(Type:string,
Condition:string,
Qnumber:string,
Qheading:string,
Pretext:string,
Qtext:string,
Posttext:string,
Codeframe():string,
Reserved:string,
EditableFrom:string,
EditableTo:string,
Decimal:string,
SetQfactor:string,
Logic_if():string,
Logic_then():string,
):Void
this.Type=Type;
this.Condition=Condition;
this.Qnumber=Qnumber;
this.Qheading=Qheading;
this.Pretext=Pretext;
this.Qtext=Qtext;
this.Posttext=Posttext;
this.Codeframe()=Codeframe();
this.Reserved=Reserved;
this.EditableFrom=EditableFrom;
this.EditableTo=EditableTo;
this.Decimal=Decimal;
this.SetQfactor=SetQfactor;
this.Logic_if()=Logic_if();
this.Logic_then()=Logic_then();
}1.
It should be
var theQuestion:Question = new
Question(sType,sCondition:string,sQnumber,sQheading,sPretext,sQtext,sPosttext,
sCodeframe,sReserved,sEditableFrom,sEditableTo,sDecimal,sSetQfactor,sLogic_if,sLogic_then )
As you don't have default values in the constructor - you
should specify the parameters.
2. why do use type "string" ? It should be "String" if you
refer to a standard type
3. What are you trying to say by this:
public var Codeframe():string;
public var Logic_if():string;
public var Logic_then():string;
There should not be any parenthesis in the variable
declaration.
4.
this is wrong
var Question():Question=new Question();
this even wronger
var Question():Array=new Question(); // I'm trying to create
an array here anyway...could this be the problem??
no parenthesis!
var Qs():Question=new Question();
hmmmm....
.var Qs()=new Question();
I think you should start reading from the following link to
get more understanding of the variables, types & declarations:
http://livedocs.adobe.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDo cs_Parts&file=00001863.html
Cheers,
Dmitri. -
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 -
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? -
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) -
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. -
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. -
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! -
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. thanksyarkehsiow,
> 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." -
Instead of using session How to pass the variable from action class to JSP
Im using Struts1.2 version.Created the Sample application to get the username.Upto action class im getting the username then i have to display the username in the JSP.Is there any options rather than using session variable to display the username.
did you check the answer in your previous thread
Passing Variable from Javascript to Controller -
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. -
How to get variable from another class?
I have 2 classes. In first I have int variable. In second class I need to get this variable value. How I can make it?
import javax.microedition.lcdui.*;
import java.io.*;
import java.util.*;
public class ChooseLessons extends Form implements CommandListener, ItemStateListener
ChoiceGroup lessons; // Choice Group of preferences
Dictionary dictionary;
int volumeSize;
ChooseLessons(Dictionary dictionary)
int volumeSize = 15;
public void commandAction(Command c, Displayable s)
if (c == Dictionary.BEGIN_CMD) {
new TeachForm(dictionary, this);
import javax.microedition.lcdui.*;
import java.util.*;
public class TeachForm extends Form implements CommandListener
Dictionary dictionary;
ChooseLessons lessons;
TeachForm(Dictionary dictionary, ChooseLessons lessons) {
super(Locale.WORD);
this.dictionary = dictionary;
this.lessons = lessons;
lessons.volumeSize(); // HERE I NEED VARIABLE VALUE FROM PREVIOUS CLASS
}Edited by: Djanym on Mar 16, 2009 4:43 PMThis is a classic problem that coders run into when trying to get their head around object-oriented programing. Since you have a class that should be modeled after a real world object, as far as that object is concerned, no one else needs to know the details of it - without asking nicely. This is where you should set up some getters and setters, which are methods that allow fields in a class to reveal themselves or allow their states to be changed in a orderly fashion.
There are a number of fields that never need to be known outside of the class. Then there are some fields you would like to let people know about, but don't want them to have the ability to change them. In the example below, there are to getter methods allow return of the necessary fields. If you made these public, there is a possibility that someone utilizing this field may change it outside of its intended use, or access them without them being ready for public consumption.
Class test {
//These private variables are only visible from the class
private int grade1 = 0;
private int grade2 = 0;
private int grade3 = 0;
private float average = 0;
private int gradeboost = 0;
//This method sets the gradeboost field to one desired by the instructor
void setboost(int boost) {
gradeboost = boost;
//These methods accept test scores and compute the average for three test
//Notice that the calculated average may not be the true average of the three test scores
//because of the possibility of gradeboost calculation being greater than 1
void test1(int score) {
grade1 = score;
average = (grade1 + grade2 + grade3 + gradeboost)/3;
void test2(int score) {
grade2 = score;
average = (grade1 + grade2 + grade3 + gradeboost)/3;
void test3(int score) {
grade3 = score;
average = (grade1 + grade2 + grade3 + gradeboost)/3;
//This is a getter method, which provides read access to the private variable average
//If someone just had public access to the grades and wanted to take their own average
//They would miss how the gradeboost field affects the final outcome.
float getAverage() {
return average;
//Here is a getter method, which accepts an argument to determine which test score to return
//Notice that this isn't the true testscore, but it has been modified by the gradeboost field.
//If the user had public access to the true testscore, it wouldn't take into account the gradeboost calculation!!
//This is how a getter can control exactly what a user has access to.
float get testScore(int test) {
float testresult = 0;
if (test = 1) {
testresult = (grade1+ gradeboost) / 3;
if (test = 2) {
testresult = (grade2+ gradeboost) / 3;
if (test = 3) {
testresult = (grade3+ gradeboost) / 3;
return testresult;
} -
Passing a variable from one class to another
Hello:
I am new to java programming. I am developing an application in Java
At a particular JTextField call it jtf3, I am invoking Calendar application by clikcing a jbutton.
I would like to set text in jtf by obtaining the date clicked by the user. I am storing complete date string in the Calendar application during ActionPerformed event at Calendar Application level.
I do not know how to pass this string to calling frame as it does not listen to the button event happening at the Calendar Application.
Much appreciated
Thanks a lot for your time
regardsThis is the application from which the I am calling the calendar application.
The method setDate set the date obtained from calendar class during actionperformed event.
The actionperfomed event from CalendarClass is pasted below as well.
Much appreciated
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
public class TestDrive
public static void main(String[] args) {
DatePanelFrame dpf = new DatePanelFrame();
dpf.addWindowListener(new WindowAdapter( ) {
public void windowClosing(WindowEvent we) { System.exit(0); }
dpf.pack();
dpf.setVisible(true);
class DatePanelFrame extends JFrame {
JTextField djtf;
String dateInput;
public DatePanelFrame() {
setTitle("Date Panel");
setSize(100, 800);
setLocation(300, 100);
Container content = getContentPane();
JPanel datePanel = new JPanel();
JButton calButton = new JButton(".....");
datePanel.add(calButton, BorderLayout.SOUTH);
djtf = new JTextField(" ");
datePanel.add(djtf, BorderLayout.NORTH);
content.setLayout(new BorderLayout());
content.add(datePanel, BorderLayout.CENTER);
calButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
JFrame fr = new CalendarClass();
fr.setSize(400, 400);
fr.setLocation(600, 100);
ObjCal oc = new ObjCal();
fr.setVisible(true);
public void setDate(String d)
djtf.setText(d);
repaint();
System.out.println(djtf.getText());
The ActionPerformed event from CalendarClass
jbtArray.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent event)
if (event.getActionCommand() != " ")
daySelected = event.getActionCommand();
yearSelected = jtfYear.getText();
int intYearSelected = Integer.valueOf(yearSelected).intValue();
monthSelected = jtfMonth.getText();
intDaySelected = Integer.valueOf(daySelected).intValue();
int intMonthSelected = getMonthNum(monthSelected);
dateSelected = getDate(intYearSelected, intMonthSelected, intDaySelected);
TestDrive td = new TestDrive();
DatePanelFrame dpf = new DatePanelFrame();
dpf.setDate(dateSelected);
Maybe you are looking for
-
Can connect to wireless on Windows but not Mac OS?
I can connect to my wireless network on my newly boot camped Windows XP. However, now I cannot connect to it on my Mac OS X. I have 10.6.8. I can see my wireless network, it doesn't have a password and everytime I try to connect it attempts but then
-
Making a Quiz in Flash. Need help with input time
Hi Flash Community, I'm making currently a quiz using Flash Pro CS5. What I want to implent is a time bar which will load once the bar is loaded it will go to the next frame. So what I need is first a timer which will start immediately when the user
-
I just purchased the iPad2 with wi-fi and need to know if I can connect in hotels.
I just purchased an iPad 2 with wi-fi and will be traveling to Europe and wanted to know if I will be able to connect to the Internet from hotel rooms and Internet cafes?
-
Hi all, This has probably been covered before but I couldn't find it by searching. I can't find my Nik Color Efex pro in my elements 9. I have it in Lightroom and Elements 7. So I have to use it in 7 save and then open again in 9. What am I doing wro
-
Oracle Change and Configuration Management packs
Hi, We are looking at implementing the Oracle Change and Configuration Management packs. I would be very interested to hear from anybosy who is currently using these packs. I have done some preliminary tests, and am getting what seems like a very sim