Instantiating an Array declared in a class from another class
Hi Guys,
I am working on a project for University and I'm stuck with this thins, which I'm sure is pretty easy when you know how...
I have a first class "Courses" in which I declare my Array, here is the code:
import java.util.*;
public class Courses
private String[][] Listing;
Courses(String[][] l)
l = Listing;
}This class compiles just fine but I have 2 problems:
1/ Can I make sure that this array will be [3][4] ?
When I try : "private String[3][4] Listing;" or "Courses(String[3][4] l)" the class doesn't compile anymore...
FYI: I want to store the followings in my array:
French Language, 250, 130, 70
Painting, 270, 140, 70
Yoga, 250, 130, 70
2/ How can I instantiate this from another class?
From a class "Booking" I want to be able to create a new array "Listing" by calling my constructor from the Courses class and populate it with the above data (course,full-time price, part-time price, Concessions price )
How do I do that?
Thanks, I've modofied my code as follows:
import java.util.*;
public class Courses
private String[][] Listing = new String[3][4]; //create array 3 rows * 4 columns
Courses(String[][] l)
l = Listing;
int i;
int j;
int p;
String t;
String p1;
String getTitle(int i) //return Course Title
t=Listing[0];
return t;
int getPrice(int i, int j) //return Price (Full-Time, Part-Time, Concessions)
p1=Listing[i][j];
p=Integer.parseInt(p1);
return p;
now from my nex class Booking I want to instantiate Courses:
public class Booking
Courses c = new Courses()
}How do I actually pass the data to this...what's the syntax so that my instance will be:
c[0][0]="French Language"
c[0][1]="250"
c[0][2]="130"
c[0][3]="70"
c[1][0]="Painting"
c[1][1]="270"
c[1][2]="140"
c[1][3]="70"
c[2][0]="Yoga"
c[2][1]="250"
c[2][2]="130"
c[2][3]="70"
Thanks in advance,
Tom
Similar Messages
-
How to kill one class from another class
I need to dipose one class from another class.
So that first i have to find what are all threads running in that class and then to kill them
Assist me.Subbu_Srinivasan wrote:
I am explaining you in clear way
No you haven't been.
>
In my application i am handling many JInternalFrame.Simultaneously i am running working on more than one frame.
Due to some poor performance of some thread in one JInternalFrame,the thread is keeps on running .
i could not able to proceed further on that screen.
So i have to kill that JInternalFrame.Yoinks.
To be begin with your problem sounds like you are doing everything in one thread. So stop doing that. Second when you get it split up and if a task is taking too much time then interrupt it. No kill. Interrupt. This means the worker thread needs to check sometimes if it has been interrupted. -
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(); -
How Do I Run A Class From Another Class?
Hiya everyone, id like to know how to run a class from another class.
Ive got a Login class which extends a JFrame and a Personnel class which also extends a JFrame. When i press the login button (in Login class), ive got it to decide if password/login are acceptable and if they are, I want the Login class to close then run the Personnel class.
Im just after the code which says to close this class and run the Personnel class. How do i do that?
Ive researched this but couldnt get an understandable answer!
Help would be much appreciated, Ant...This is the Login Class:
public class MainMenu extends javax.swing.JFrame {
Statement statement = null;
int currentRecord;
ResultSet rs = null;
String name = null, job = null, mission = null, login = null, password = null;
String loginVal;
String passwordVal;
/** Creates new form MainMenu */
public MainMenu() {
initComponents();
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = System.getProperty("user.dir") + "/src/Personnel.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=" + filename;
Connection conn = DriverManager.getConnection( database , "","");
statement = conn.createStatement();
System.out.println("Connected...ok");
} catch (Exception e) {
System.err.println("Got a connection Problem!");
System.err.println(e.getMessage());
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
loginVal = txtLogin.getText();
passwordVal = txtPassword.getText();
String name = null, job = null, mission = null, login = null, password = null;
try{
rs = statement.executeQuery("SELECT Login,Password FROM Personnel WHERE Login = '" + loginVal + "' ");
System.out.println("TRYING SELECT CLAUSE");
if(rs.next()){
System.out.println("THERE IS A NEXT RECORD");
login = rs.getString(1);
password = rs.getString(2);
System.out.println("GOT THE NEXT RECORD");
System.out.println(login + password);
System.out.println("Query Complete");
}catch(Exception s){
//s.printStackTrace();
System.out.println("NO RECORDS EXIST FOR THIS LOGIN ID");
if(passwordVal.equals(password)){
System.out.println("Access Granted"); //CLOSE MAIN AND RUN CONTROL CLASS
} else{
System.out.println("Access Denied"); //RE-RUN CLASS
} -
Refer to the document class from another class?
There is a function in my document class that I need to call from inside another class. How can I call myFunction from inside OtherClass? Or refer to myVariable from inside OtherClass?
package {
import flash.display.Sprite;
public class DocumentClass extends Sprite {
public function DocumentClass():void {
_init();
private function _init():void {
var myVariable:int = 0;
function myFunction():void {
//The function I need to access
var myClass = new OtherClass();There's many ways to do it. On a case by case basis a strategy has to be chosen.
In your case, is there literally just one child class that's trying to ask the root class to run the function? Are a bunch of other classes also trying to get at this same function? Flesh out a really good description of what you want to do for a few suggestions.
For fun I'm going to assume other classes may want to call this function and at the same time be really simplistic in the approach by assuming the project is simple and bubbled events won't hurt performance. It doesn't sound like this is a particle situation.. In that case I'd send a simple bubbled event Main can read.
e.g.:
Main:
package
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
private var _a:Sprite;
public function Main():void
addEventListener(Event.ENTER_FRAME, onEF);
// Called from BClass after added to stage (for event to propagate)
public function SomeFunction():void
// now that this is called, do what you want..
// I'm just going to remove _a (for no special reason)
trace("Main.SomeFunction() - called, removing _a (_b will GC eventually as well)");
removeChild(_a);
_a.removeEventListener("OMGEvent", _handleOMGF);
_a = null;
private function onEF(e:Event):void
removeEventListener(Event.ENTER_FRAME, onEF);
trace("Main.onEF() - Instantiating AClass");
// instantiate a new child, which also will load a child
_a = new AClass();
// listen for events bubbling
_a.addEventListener("OMGEvent", _handleOMGF);
// add to stage
addChild(_a);
// listen to _a to invoke function
private function _handleOMGF(e:Event):void
trace("Main._handleOMGF() - child sent OMG to Main, running Main.SomeFunction()");
SomeFunction();
AClass:
package
import flash.display.Sprite;
import flash.events.Event;
public class AClass extends Sprite
private var _b:BClass;
public function AClass():void
addEventListener(Event.ADDED_TO_STAGE, _onAddedF);
addEventListener(Event.REMOVED_FROM_STAGE, _onRemovedF);
private function _onAddedF(e:Event):void
removeEventListener(Event.ADDED_TO_STAGE, _onAddedF);
trace("AClass._onAddedF() - Instantiating BClass");
// first child on stage, load second child, which
// after it hits the stage will dispatch an event
_b = new BClass();
// we'll listen here for the event just for fun
_b.addEventListener("OMGEvent", _handleOMGF);
// trigger the ADDED_TO_STAGE
addChild(_b);
// listen to _b just for fun
private function _handleOMGF(e:Event):void
trace("AClass._handleOMGF() - Just heard OMG!");
// clean up
private function _onRemovedF(e:Event):void
removeEventListener(Event.REMOVED_FROM_STAGE, _onRemovedF);
removeChild(_b);
_b.removeEventListener("OMGEvent", _handleOMGF);
_b = null;
trace("AClass._onRemovedF() - I cleaned up");
BClass:
package
import flash.display.Sprite;
import flash.events.Event;
public class BClass extends Sprite
public function BClass():void
addEventListener(Event.ADDED_TO_STAGE, _onAddedF);
private function _onAddedF(e:Event):void
removeEventListener(Event.ADDED_TO_STAGE, _onAddedF);
trace("BClass._onAddedF() - Created, dispatching 'OMGEvent' with bubbles");
// dispatch (I extend Sprite, it supports events)
// Note: I set bubbles to true to bubble back to Main (default is false)
dispatchEvent(new Event("OMGEvent", true));
For ease, Example Source (saved down to CS5).
All parents of that child will receive the dispatched event. To use that tactic you'd need to be sure your event is unique (hence using 'OMGEvent') and not have a fiercly complex display list because all those parents of this child will receive this event as well. I find in 99% of the non-particle usage of this, it really just doesn't matter. It's quick and simple.
If you wanted to really direct it rather than bubble, you'd just remove the 'true' parameter from the dispatchEvent() and then each parent of that child would need to be told to listen for the event so it can keep relaying it up the display chain.
I do the latter quite often when a child affects the display of each parent in some way all the way up the display list, capturing custom events at each level, doing what's necessary.
Trace:
Main.onEF() - Instantiating AClass
AClass._onAddedF() - Instantiating BClass
BClass._onAddedF() - Created, dispatching 'OMGEvent' with bubbles
AClass._handleOMGF() - Just heard OMG!
Main._handleOMGF() - child sent OMG to Main, running Main.SomeFunction()
Main.SomeFunction() - called, removing _a (which marks _b for cleanup as well)
AClass._onRemovedF() - I cleaned up
Man, Adobe really needs to get a <pre lang="as3"> with some color coding/formatting. -
How to call a static method of a class from another class?
Hello,
I have two classes in a package. The first one
package my package;
public class class1
protected static ImageIcon createIcon(String path)
The second one
package my package;
public class class2
private ImageIcon image1;
image1 = class1.createIcon("/mypath");
This does not work since class2 cannot load the appropriate image. Where do I have to define the ImageIcon variables in class one or two and do they have to be static variables?
Thanks in advance
ChristosIf the two classes are in the same package, that will work, in fact. A trivial example:
package foo;
public class Foo1 {
protected static String getString() {
return "World";
// Note: Member of the same package
package foo;
public class Foo2 {
public static void main(String[] argv) {
System.out.println("Hello "+ foo.Foo1.getString());
}However, if they are in different packages that won't work - the protected keyword guarantees that only classes derived from the class with the protected method can access it: Therefore this will not work:
package foo;
public class Foo1 {
protected static String getString() {
return "World";
package foo.bar;
public class Foo2{
public static void main(String[] argv) {
System.out.println("Hello "+ foo.Foo1.getString());
}But this will:
package foo;
public class Foo1 {
protected static String getString() {
return "World";
package foo.bar;
public class Foo2 extends foo.Foo1 {
public static void main(String[] argv) {
System.out.println("Hello "+ foo.Foo1.getString());
}I think you should read up a bit more about packages and inheritance, because you're going to have a lot of trouble without a good understanding of both. Try simple examples first, like the above, and if you hit problems try to produce a simple test case to help you understand the problem rather than trying to debug your whole application.
Dave. -
How to add objects to panel in one class from another class
Hi this is what i am trying to do. I have a drag and adrop tool working where the users and select objects on a small panel and drag them to another panel called the tpan. What i want to do is create another class, which creates objects and now i want to display these objects on the tpan. So say i have a class DisplayTpan(), this class is used to display the objects which have been dragged from the small panel, and objects on this panel have mouselisteners attached, so that these objects can be moved around on the tpan. I have created another class called creatObj(), and from this class i want to add objects to the tpan. The DisplayTpan class extends a Jpanel, would this be he case for the CreateObj() class? In the CreateClass i have made a call to DisplayTpan t = new DisplayTPan();
t.add(object);
But this does not add the object to the panel, any ideas on how it should be done?
Problem number two i have is say, I have two objects created on that oanel, i now want to draw a line t connect the two objects, this is just simply a call to the drawLine function but how would it be possible to add a ,mouselistener to that line, so it can be extended moved around etc? Any help much appreciated thanks.Try to convert the PL/SQL code from Forms trigger into a PL/SQL library(.PLL),
and then attach that PLL in your forms.
Note that all Forms objects should be referenced indirectly, for example,
you have to rewrite
:B1.DEPT_CODE := :B2.DEPT_CODE;
:B3.TOTAL_AMOUNT := 100;
==>
copy('B2.DEPT_NO','B1.DEPT_NO');
copy('100','B3.TOTAL_AMOUNT');
This is the best way to share PL/SQL code among Oracle Forms. -
Access data of one class from another class
Hi,
I am creating one class say ClassA with some data members,the same class has main() method on execution of which the data members will b assigned a value.
now i have another class say ClassB with main() method and i want to use the data in ClassA in ClassB do i have any way by which i can have access to that data.
The instance of ClassA created in ClassB is not showing any values in data members.
Can u help me find a solution for this.
Thank you.
Parag.I have tried by making one data member public so that it can have direct access from other class.But it shows null value.
The problem is that ClassA class data members are assigned values when it completes the execution of function main() so does it retains the values.
c sample code below.
public classA{
int a,b;
p s v m(String [] args)
setab();
public void setab()
//set values of a and b by doing some manipulations.
public classB{
p s v m(string []args)
classA aclass = new classA();
/* now what should i do to access the values of a & b in
aclass object*/
i strictly need to follow this way do i have a way out. -
Referencing a function in a class from another class
For example : I got the following situation
class main {
classOne one;
classTwo two;
public main {
one = new classOne();
two = new classTwo();
class classone {
private int i = 5;
public classone {
public count() {
System.out.println(i+ getJ());
class classtwo {
private int j = 15;
public classtwo {
public int getJ() {
return J;
Is this possible to reference a method from the same instance to which main is pointer, because when i do
classTwo two = new classTwo();
two.getJ();
in classOne, i'm referencing another instance.
I know there exist something like friends in java, but i'm seeking for a more "nice" solution
thxI wasn't sure if I understand what you're looking for. But if I understand well...
Well, that won't work that way. However, you may use nested classes. But that brings you to a development question. Nested classes are supposed to help the embedding class. Anyhow, here's a way it might work:
class MainClass {
ClassOne one = new ClassOne();
ClassOne two = new ClassTwo();
void methodOfMain() {
class ClassOne {
public void oneMethod() {
two.twoMethod();
methodOfMain();
class ClassTwo {
public void twoMethod() {
methodOfMain();
}Alternatively, you may consider passing the instance of ClassTwo to the method of ClassOne, which will use this instance to access the methods, if you cannot use nested classes.
But you cannot use the methods of another class directly, unless that another class is the embedding class (calling of methodOfMain in the code above). You must use an instance of the class (or the class name, in case of static methods) to reach the methods.
Is this what you're seeking for? -
How to call main method in one class from another class
Suppose i have a code like this
class Demo
public static void main(String args[])
System.out.println("We are in First class");
class Demo1
public static void main(String args[])
System.out.println("We are in second class");
In the above program how to call main method in demo calss from Demo1 class......???????No, i dont know how to call other than main methods from other classes
And one more doubt i have i.e. Like in C can we see the execution of the program like how the code is being compiled step by step and how the value of the variable changes from step to step like(Add Watch)......... -
Compiling a class from another class
is it possible to compile a class from the code in another class?
i.e I want to check whether code in a .java file will compile before I use it.
Is there any methods that I could use to do this and could anyone give me advice on HOW to use the methods suggested?
thanks in advance
davidi was looking at that but it seems to only run files, not commands
is there a way to use it with command.com or cmd.exe or something to send commands to it?
also if i used a readline on an inputstream it only returned the first line (i tried running a batch file so the only line it returned was ..> javac testscript.java but i spose if i put
@echo off
javac testscript.java
if exist testscript.class (
echo compiled correctly
) else (
echo compiled incorectly
so the first line returned would either be "compiled correctly" or the compile error, but this would be compiling it to see if it compiles so im not sure if this answers the first question anyway =p -
How to call a method of a class from another class
Hi,
Can some one explain me this? I want the label from the Label class to be displayed in the JFrame. I understand to do this, I have to call "label" to the ABC() and createAndShowGUI().
I am novice. It will be really helpful if you could explain me what you did.
class Label {
public Label() {
public JTextField label;
label = new JTextField("Hi");
public ABC() { //Constructor
Container c = getContentPane();
c.setLayout(new FlowLayout());
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600, 400));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}Will it be some thing like this?
public ABC() { //Constructor
Container c = getContentPane();
c.setLayout(new FlowLayout());
Label label = new Label();
label.add
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600, 400));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.add(new Label());
//Display the window.
frame.pack();
frame.setVisible(true);
}merit wrote:
Hi,
Can some one explain me this? I want the label from the Label class to be displayed in the JFrame. I understand to do this, I have to call "label" to the ABC() and createAndShowGUI().
I am novice. It will be really helpful if you could explain me what you did.
class Label {
public Label() {
public JTextField label;
label = new JTextField("Hi");
public ABC() { //Constructor
Container c = getContentPane();
c.setLayout(new FlowLayout());
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600, 400));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
//Display the window.
frame.pack();
frame.setVisible(true);
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}Will it be some thing like this?
public ABC() { //Constructor
Container c = getContentPane();
c.setLayout(new FlowLayout());
Label label = new Label();
label.add
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension(600, 400));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.add(new Label());
//Display the window.
frame.pack();
frame.setVisible(true);
You know it maybe that it's just too late at night for me, but I see you complete Label class, but I don't see a class definition for ABC; you have a constructor for it, but not a class definition for it.
In any case, when you define a class, you use it in the same way any other class is used...
MyClass myObjectRef = new MyClass(); -
Call a class from another class from JSP?
I was wondering if anyone could tell me where Im going wrong with this one. Why is the result different if I uses a class, than a jsp page. Returning a regular string is fine, but a string I read from a file...
I have an application that is structured like so:
The class "packClass1" in app
package "TestPackage" simply |
calls a method in class jspPage1.jsp
"packClass2". "packClass2" reads |
a Properties type from a WEB-INF
file and returns it. Then |
packClass1 just passes a string classes
using getProperty back to the |
caller. normalClass1.java
|
If the caller is normalClass1.java TestPackage
(from the console) then it responds |
as expected, returning the string packClass1.java
from the file. BUT - if the caller is packClass2.java
the jspPage1.jsp, then it returns
"null". Here is the code (names have
been changed to protect the innocent...)jspPage1.jsp (this outputs: "result is: null"):<%@ page import="TestPackage.*" %>
<jsp:useBean id="testOne" scope="page" class="tpack.packClass1" />
<% out.println(testOne.getAString()); %>normalClass1.java (this outputs: "result is: gotFromFile"):import TestPackage.*;
public class two{
public static void main(String args[]){
packClass1 testOne = new packClass1();
System.out.println(testOne.oneOne(getAString()));
three.load();
}packClass1.java:package TestPackage;
import java.util.Properties;
public class packClass1{
public packClass1(){}
public String packClass1(){
Properties props = packClass2.load();
return props.getProperty("aStringValue");
}packClass2.java:package TestPackage;
import java.util.Properties;
import java.io.*;
public class three{
public three(){};
public static Properties load(){
Properties p = new Properties();
//skipped out exception handlin' for brevity
p.load(new java.io.FileInputStream("test.prop"));
return p;
}I am VERY new to all this, and I (obviously) havent figured out differences between servlets and beans etc... I am reseaching! But in the mean time... any ideas?!public String packClass1(){ Properties props = packClass2.load(); return props.getProperty("aStringValue"); }
this function name is bit dodgy coz it has same name as the class name??????
its confusing -
Calling a method of one class from another withing the same package
hi,
i've some problem in calling a method of one class from another class within the same package.
for eg. if in Package mypack. i'm having 2 files, f1 and f2. i would like to call a method of f2 from f1(f1 is a servlet) . i donno exactly how to instantiate the object for f2. can anybody please help me in this regard.
Thank u in advance.
Regards,
FazliThis is what my exact problem.
i've created a bean (DataBean) to access the database. i'm having a servlet program (ShopBook). now to check some details over there in the database from the servlet i'm in need to use a method in the DataBean.
both ShopBook.java and DataBean.java lies in the package shoppack.
in ShopBook i tried to instantiate the object to DataBean as
DataBean db = new DataBean();
it shows the compiler error, unable to resolve symbol DataBean.
note:
first i compiled DataBean.java, it got compiled perfectly and the class file resides inside the shoppack.
when i'm trying to compile the ShopBook its telling this error.
hope i'm clear in explaining my problem. can u please help me?
thank u in advance.
regards,
Fazli -
Accessing an Array List from another class
Hi, I was a member on here before, but I forgot my password and my security question is wrong.
My question is how do I access a private arraylist from a different class in the same package?
What I am trying to do is the following (hard to explain).
Make a picking client for a shop, so that when an order is recieved, the picker can click on the orders button, and view all of the current orders that have not been completed. This Pick client has its own user interface, in a seperate class from where the BoughtList array is created, in the cashier client. The boughtlist is created when the cashier puts in the product number into the cashier client and clicks buy. I seem to be having trouble accessing the list from another class. Once the order is completed the cashier clicks bought and the list is reset. There is another class in a different pagage that processes some of the functions of the order, eg newOrder().
Yes it is for Uni so I dont need / want the full answers, jist something to get started. Also please dont flame me, I have done many other parts of this project, just having trouble getting started on this one.
Here is the code for the cashier client. The code for the Pick client is almost the same, I just need to make the code that displays the orders.
package Clients;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.NumberFormat;
import java.util.Locale;
import Catalogue.*;
import DBAccess.*;
import Processing.*;
import Middle.*;
class CashierGUI
class STATE // Cashier states
public static final int PROCESS = 0;
public static final int CHECKED = 1;
class NAME // Names of buttons
public static final String CHECK = "Check";
public static final String BUY = "Buy";
public static final String CANCEL = "Cancel";
public static final String BOUGHT = "Bought";
private static final int H = 300; // Height of window pixels
private static final int W = 400; // Width of window pixels
private JLabel theAction = new JLabel();
private JTextField theInput = new JTextField();
private JTextArea theOutput = new JTextArea();
private JScrollPane theSP = new JScrollPane();
private JButton theBtCheck = new JButton( NAME.CHECK );
private JButton theBtBuy = new JButton( NAME.BUY );
private JButton theBtCancel= new JButton( NAME.CANCEL );
private JButton theBtBought= new JButton( NAME.BOUGHT );
private int theState = STATE.PROCESS; // Current state
private Product theProduct = null; // Current product
private BoughtList theBought = null; // Bought items
private Transaction theCB = new Transaction();
private StockReadWriter theStock = null;
private OrderProcessing theOrder = null;
private NumberFormat theMoney =
NumberFormat.getCurrencyInstance( Locale.UK );
public CashierGUI( RootPaneContainer rpc, MiddleFactory mf )
try //
theStock = mf.getNewStockReadWriter(); // DataBase access
theOrder = mf.getNewOrderProcessing(); // Process order
} catch ( Exception e )
System.out.println("Exception: " + e.getMessage() );
Container cp = rpc.getContentPane(); // Content Pane
Container rootWindow = (Container) rpc; // Root Window
cp.setLayout(null); // No layout manager
rootWindow.setSize( W, H ); // Size of Window
Font f = new Font("Monospaced",Font.PLAIN,12); // Font f is
theBtCheck.setBounds( 16, 25+60*0, 80, 40 ); // Check Button
theBtCheck.addActionListener( theCB ); // Listener
cp.add( theBtCheck ); // Add to canvas
theBtBuy.setBounds( 16, 25+60*1, 80, 40 ); // Buy button
theBtBuy.addActionListener( theCB ); // Listener
cp.add( theBtBuy ); // Add to canvas
theBtCancel.setBounds( 16, 25+60*2, 80, 40 ); // Cancel Button
theBtCancel.addActionListener( theCB ); // Listener
cp.add( theBtCancel ); // Add to canvas
theBtBought.setBounds( 16, 25+60*3, 80, 40 ); // Clear Button
theBtBought.addActionListener( theCB ); // Listener
cp.add( theBtBought ); // Add to canvas
theAction.setBounds( 110, 25 , 270, 20 ); // Message area
theAction.setText( "" ); // Blank
cp.add( theAction ); // Add to canvas
theInput.setBounds( 110, 50, 270, 40 ); // Input Area
theInput.setText(""); // Blank
cp.add( theInput ); // Add to canvas
theSP.setBounds( 110, 100, 270, 160 ); // Scrolling pane
theOutput.setText( "" ); // Blank
theOutput.setFont( f ); // Uses font
cp.add( theSP ); // Add to canvas
theSP.getViewport().add( theOutput ); // In TextArea
rootWindow.setVisible( true ); // Make visible
class Transaction implements ActionListener // Listener
public void actionPerformed( ActionEvent ae ) // Interaction
if ( theStock == null )
theAction.setText("No conection");
return; // No connection
String actionIs = ae.getActionCommand(); // Button
try
if ( theBought == null )
int on = theOrder.uniqueNumber(); // Unique order no.
theBought = new BoughtList( on ); // Bought list
if ( actionIs.equals( NAME.CHECK ) ) // Button CHECK
theState = STATE.PROCESS; // State process
String pn = theInput.getText().trim(); // Product no.
int amount = 1; // & quantity
if ( theStock.exists( pn ) ) // Stock Exists?
{ // T
Product pr = theStock.getDetails(pn); // Get details
if ( pr.getQuantity() >= amount ) // In stock?
{ // T
theAction.setText( // Display
pr.getDescription() + " : " + // description
theMoney.format(pr.getPrice()) + // price
" (" + pr.getQuantity() + ")" // quantity
); // of product
theProduct = pr; // Remember prod.
theProduct.setQuantity( amount ); // & quantity
theState = STATE.CHECKED; // OK await BUY
} else { // F
theAction.setText( // Not in Stock
pr.getDescription() +" not in stock"
} else { // F Stock exists
theAction.setText( // Unknown
"Unknown product number " + pn // product no.
if ( actionIs.equals( NAME.BUY ) ) // Button BUY
if ( theState != STATE.CHECKED ) // Not checked
{ // with customer
theAction.setText("Check if OK with customer first");
return;
boolean stockBought = // Buy
theStock.buyStock( // however
theProduct.getProductNo(), // may fail
theProduct.getQuantity() ); //
if ( stockBought ) // Stock bought
{ // T
theBought.add( theProduct ); // Add to bought
theOutput.setText( "" ); // clear
theOutput.append( theBought.details()); // Display
theAction.setText("Purchased " + // details
theProduct.getDescription()); //
// theInput.setText( "" );
} else { // F
theAction.setText("!!! Not in stock"); // Now no stock
theState = STATE.PROCESS; // All Done
if ( actionIs.equals( NAME.CANCEL ) ) // Button CANCEL
if ( theBought.number() >= 1 ) // item to cancel
{ // T
Product dt = theBought.remove(); // Remove from list
theStock.addStock( dt.getProductNo(), // Re-stock
dt.getQuantity() ); // as not sold
theAction.setText(""); //
theOutput.setText(theBought.details()); // display sales
} else { // F
theOutput.setText( "" ); // Clear
theState = STATE.PROCESS;
if ( actionIs.equals( NAME.BOUGHT ) ) // Button Bought
if ( theBought.number() >= 1 ) // items > 1
{ // T
theOrder.newOrder( theBought ); // Process order
theBought = null; // reset
theOutput.setText( "" ); // Clear
theInput.setText( "" ); //
theAction.setText( "Next customer" ); // New Customer
theState = STATE.PROCESS; // All Done
theInput.requestFocus(); // theInput has Focus
catch ( StockException e ) // Error
{ // Of course
theOutput.append( "Fail Stock access:" + // Should not
e.getMessage() + "\n" ); // happen
catch ( OrderException e ) // Error
{ // Of course
theOutput.append( "Fail Order process:" + // Should not
e.getMessage() + "\n" ); // happen
}(disclaimer: I did not read through your Swing code, as I find that painful)
My question is how do I access a private arraylist from a different class in the same
package?Provide a public accessor method (getMyPrivateArrayList())
Maybe you are looking for
-
How do I transfer playlists from itunes to my ipad?
I have several custom playlists that I have made and they are in itunes on my computer under the playlist section. They are underneath the four standard playlists: classical, music videos, my top rated and 90s music that come already set up. These ha
-
Hi All, Getting the below adapter error while deploying a new BPEL process, <2005-08-16 15:15:58,850> <ERROR> <default.collaxa.cube.activation> <AdapterFramework::Inbound> ORABPEL-11622 Could not create/access the TopLink Session. This session is use
-
Proxy Runtime Error in RWB.
Hi All, I am getting following error, Please, help me to solve this problem Message: Neither the messager server nor the application server can be reached for system DSM Stacktrace: com.sap.aii.rwb.exceptions.OperationFailedException: Neither the mes
-
A few years ago I converted my old analog video tapes to digital. Each file are approximatly 90 minutes and in mpg format. I have two challenges I hope you can give me some advices: Lightroom will not read this files but I can play them with Windows
-
To sign together with signature image
I want to sign conventionally by including my signature image. However, when I choose to configure signature appearance, Adobe Reader XI cannot import graphics in jpg, only choice is pdf and signature image came out truncated! So, is it confirm that,