Accessing Members in Another Class
How would I access a member from another class? In the actionPerformed method, I want to be able to access objects such as filemenu in the Main class. Here's most of my code:
class fileEvent implements ActionListener
{ public void actionPerformed(ActionEvent e,JMenuItem& item)
public class Main extends JFrame implements ActionListener, ItemListener {
/** Creates a new instance of Main */
public Main() {
this.setTitle("Cross-platform Map Editor");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JInternalFrame drawingframe;
JDesktopPane desk;
JPanel drawingpanel = new JPanel();
JMenuBar menubar = new JMenuBar();
JMenu filemenu = new JMenu("File");
JMenu editmenu = new JMenu("Edit");
JMenu mapmenu = new JMenu("Map");
JMenu tilesmenu = new JMenu("Tiles");
JMenu toolsmenu = new JMenu("Tools");
JMenu windowmenu = new JMenu("Window");
JMenu aboutmenu = new JMenu("Help");
JMenuItem fileItem1 = new JMenuItem("New...",KeyEvent.VK_N);
fileItem1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.ALT_MASK));
fileItem1.addActionListener(new fileEvent(),fileItem1);
JMenuItem fileItem2 = new JMenuItem("Open...");
JMenuItem fileItem3 = new JMenuItem("Save");
JMenuItem fileItem4 = new JMenuItem("Save As...");
JMenuItem fileItem5 = new JMenuItem("Exit");
JMenuItem editItem1 = new JMenuItem("Undo");
JMenuItem editItem2 = new JMenuItem("Redo");
JMenuItem editItem3 = new JMenuItem("Cut");
JMenuItem editItem4 = new JMenuItem("Copy");
JMenuItem editItem5 = new JMenuItem("Paste");
JMenuItem editItem6 = new JMenuItem("Select All");
filemenu.add(fileItem1);
filemenu.add(fileItem2);
filemenu.add(fileItem3);
filemenu.add(fileItem4);
filemenu.add(fileItem5);
editmenu.add(editItem1);
editmenu.add(editItem2);
editItem2.add(new JSeparator());
editmenu.add(editItem3);
editmenu.add(editItem4);
editItem4.add(new JSeparator());
editmenu.add(editItem5);
menubar.add(filemenu);
menubar.add(editmenu);
menubar.add(mapmenu);
menubar.add(tilesmenu);
menubar.add(toolsmenu);
menubar.add(windowmenu);
menubar.add(aboutmenu);
this.setJMenuBar(menubar);
JButton drawingbutton1 = new JButton("Pencil");
JButton drawingbutton2 = new JButton("Line");
JButton drawingbutton3 = new JButton("Paint Pucket");
JButton drawingbutton4 = new JButton("Recntangle");
JButton drawingbutton5 = new JButton("Filled Rectangle");
drawingpanel.add(drawingbutton1);
drawingpanel.add(drawingbutton2);
drawingpanel.add(drawingbutton3);
drawingpanel.add(drawingbutton4);
drawingpanel.add(drawingbutton5);
drawingframe = new JInternalFrame("Drawing", true,true,true,true);
drawingframe.add(drawingpanel);
drawingframe.setSize(200,300);
drawingframe.setVisible(true);
desk = new JDesktopPane();
desk.add(drawingframe);
this.add(desk);
this.setSize(500,500);
this.setVisible(true);
/code]
You don't want your Main class to have accessor methods or public variables... that's the worst dependency you can have.
Anyways, think in terms of objects. When one object has a reference to another object, it can access all of its public data and methods.
I'd recommend reading up on the basics:
http://java.sun.com/docs/books/tutorial/java/index.html
Similar Messages
-
Accessing label in another class?
I'm trying to learn Java so sorry for the very simple question but I'm trying to change the text of a label in another class. I think I need to create a new instance of this label to access it from the second class but I just can't seem to get it to work. I don't know how to create the instance, which class to create the instance in why I want to create this instance and what this instance does really?
import java.awt.*;*
*import javax.swing.*;
import java.util.*;*
*import java.awt.event.*;
import java.lang.*;*
*public class StopWatch extends JFrame implements ActionListener*
* private JButton button1 = new JButton("Start");*
* private JButton button2 = new JButton("Stop");*
* private JButton button3 = new JButton("Lap");*
* private JButton button4 = new JButton("Clear");*
* public JLabel label1 = new JLabel("The time goes here!!!!!!!!!!");*
* public StopWatchConfig aConfig;*
* public StopWatch(String input)*
* button1.addActionListener(this);*
* button2.addActionListener(this);*
* button3.addActionListener(this);*
* button4.addActionListener(this);*
* displayGUI();*
* aConfig = new StopWatchConfig();*
* public void displayGUI()*
* Container c = getContentPane();*
* c.setLayout(new FlowLayout());*
* //c.setBackground(Color.black);*
* c.add(button1);*
* c.add(button2);*
* c.add(button3);*
* c.add(button4);*
* c.add(label1);*
* setSize(300,100);*
* setVisible(true);*
* public void actionPerformed(ActionEvent e)*
* Object source = e.getSource();*
* if ( e.getSource() == button1 )*
* aConfig.start();*
* if ( e.getSource() == button2 )*
* aConfig.stopp();*
* else if ( e.getSource() == button3 )*
* // timerSetup.lap();*
* } // end if/else*
* else if ( e.getSource() == button4 )*
* // timerSetup.clear();*
* } // end if/else*
* } // end method*
*import java.awt.*;
import javax.swing.*;*
*import java.util.*;
import java.awt.event.*;
import java.lang.System;
public class StopWatchConfig extends Thread
public void start()
public void stopp()
aStopWatch.label1.setText("CHANGED!");
public void lap()
public void clear()
}You don't want a new instance -- that would be an entirely different label, and not have any effect on what you're doing. What you want is a reference to the object you're changing.
What I would suggest is that you make sure only StopWatch can change its own label, say, with a method setTime(). Then, any other object that has a reference to that instance of StopWatch can call that method, and StopWatch will control the changing of its own components.
However, you're dealing with multithreading issues here, too, which is another beast. When you have two threads talking to each other you've got some things you need to take into account, such as synchronization. I'd say try to get this to work within a single thread first -- maybe have a button inside StopWatch that sets its own time. -
Accessing variable from another class
Say I want to access String ABC from class XYZ from my main class. I have already created the object for the class I just don't know the syntax for accessing the variable.
This is just an example. I figured this is just a problem of finding the right syntax so I didn't bother creating a compiling code.
public class test{
public static void main(String[]args){
XYZ xyz = new XYZ ();
String a = abc.XYZ(); // this is where i want to directly access the variable abc. i know this isn't correct and it's what im trying to find out how to do.
public class XYZ{
String abc = "hi";
}Edited by: aznprdgy on Nov 3, 2009 2:13 PMNo, that isn't possible.
abc is said to be a local variable. And it's only useable within method().
It's part of the job of the class Xyz to control the access to its state. As an example:
public class Test {
public static void main(String[] args) {
Xyz xyz = new Xyz()
String a = xyz.getSpecialValue();
public class Xyz {
private String a;
public String getSpecialValue() {
return a;
public void method() {
a = "hi";
}Note that a won't be reference to the string "hi" until after method() has been called. -
How do I access data from another class?
I have a class RailNetwork which extends Datastore. DataStore contains a vector filelines which I need to access from RailNetwork. How do I do this? What do I put infront of filelines.get(i); ?
public abstract class DataStore
{ Vector<String> fileLines = new Vector<String>(); }
public class RailNetwork extends DataStore
{ ...main(){ .......filelines.get(i);....... }
}This is the code from RailNetwork class:
public static void main(String[] args) {
String templine;
int i = 0;
int vectorlength = super.filelines.size();
for( i = 0 ; i < vectorlength ; i++ )
templine = (String) super.filelines.get(i);
setStations(templine); }The errors (for both lines, only 1 shown):
RailNetwork.java:49: non-static variable super cannot be referenced from a static context
templine = (String) super.filelines.get(i);
^
RailNetwork.java:49: cannot find symbol
symbol : variable filelines
location: class DataStore
templine = (String) super.filelines.get(i);
^ -
Enums as members of another class????
Hi ,
I have the following example on the server side
public Enum Colors
RED,
ORANGE,
UNKNOWN,
the above enum is in a separate file/class
Now the webservice class.
@WebService
public class A
Colors myColor =Colors.UNKNOWN
public void setMyColor(Colors newValue)
MyColor = newValue;
public Colors getMyColor()
return myColor;
Now On the client side...(Using .NET WebReference)
if I say
A MyServer = new A();
A.setMyColor(Color.RED)
A.getMyColor(). returns UNKNOWN...I still get this as UNKNOWN?????
Please let me know what is the best way to achieve this?
Regards,
VijayI tried the following using JAX-WS on both the client and the server and it worked fine using the latest build.
@WebService(name="Echo", serviceName="echoService", targetNamespace="http://echo.org/")
public class EchoImpl {
// Enum tests
public enum Color { RED, ORANGE, UNKNOWN};
Color color = Color.UNKNOWN;
@WebMethod
public void setColor(Color color) {
this.color = color;
@WebMethod
public Color getColor() {
return color;
Client:
stub.setColor(Color.RED);
assertTrue(stub.getColor().equals(Color.RED)); -
Strange Error When Accessing Members Of A Class
I'm having a problem referencing a member of an interface I've just created.
I've created a UIView ( TestView ) in IB and had it write out the class definition and add it to my project. Within this view are two UILabels that I've named and have references to them by means of IBOutlet from within my TestView interface.
Here is the TestView interface:
TestView.h:
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
@interface TestView : UIView {
IBOutlet UILabel *Text1;
IBOutlet UILabel *Text2;
@end
TestView.m:
#import "TrashView.h"
@implementation TrashView
@end
I then have a reference via IBOutlet to my TestView from within my main window:
MyAppDelegate.h:
#import <UIKit/UIKit.h>
@class TestView;
@interface MyAppDelegate : NSObject <UIApplicationDelegate> {
IBOutlet UIWindow *window;
IBOutlet TestView *testView;
@property (nonatomic, retain) UIWindow *window;
@end
MyAppDelegate.m:
#import "LSAppDelegate.h"
#import "TestView.h"
@implementation MyAppDelegate
@synthesize window;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
// Adjust text lables
[ testView.Text1 setText:@"Hello World!" ];
- (void)dealloc {
[window release];
[testView release];
[super dealloc];
@end
However I get a strange compiler error from the line where I'm trying to set the text of the label:
error: request for member 'Text1' in 'testView', which is of non-class type 'UIView'
Anyone know what this means?
Thanks!It not only depends on where the field is added but also on which fields were selected at the time of variant creation. In other words, the screen on which you are providing variant has now an extra field. You can try by just restricting that field from being displayed ont he screen by through Settings->Fields for selection.
Try hiding the new field or any fields and make sure the structure is the same as before.
For example.. there are 5 fields in your table...
fld1
fld2
fld3
fld4
fld5
You have created variant when the structure was like this:
fld1
fld2
fld4
Now, you have added fld6 at the bottom and the screen is given as:
fld1
fld2
fld3
fld4
fld5
fld6...
Now it gives error for sure... but if you try hiding fld3 and fld5... this solves the problem... fld6 will not affect as it is placed at last...
Hope this solves your problem.
Edited by: Srinivas Kalluri on Aug 5, 2011 3:46 PM
Edited by: Srinivas Kalluri on Aug 5, 2011 3:49 PM -
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. -
Easy question: Give access to a class in another class.
Stupid title, but dont know how to express myself :P Sorry for that.
To the problem. Never had this problem before, and I know its a really easy solution to this.
I have my Main class, which creates a MyView class. Inside this class, I make to new classes(or instances of classes i've already made), MyPanel and MyToolsPanel. Now I want to add buttons inside the MyToolsPanel class, and add actionlisteners to these buttons inside MyPanel.
What I'v always done to grant access to MyToolsPanel inside of MyTools, is to simply add a
//this is the MyPanel class
MyToolsPanel mtp;
public void setMtp(MyToolsPanel mtp){
this.mtp = mtp;
}and then in the MyView class which create these to classes, I put a command: mp.setMtp(mtp);
When I run this it doesnt work.. Why? Should be easy to solve, since it obviously is a stupid problem that I just dont see. :P Feeling kind of stupid to ask this question, but this is how it is...
EDIT: I might have to implement actionListener inside the MyToolsPanel class?
Edited by: Stianbl on Sep 28, 2008 4:59 PMone way:
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTextField;
* Subclasses JPanel, can send text out via the getText() method
* can hook into button press via addActionListener
* @author Pete
public class PanelCommSender extends JPanel
private JTextField sendingField = new JTextField(12);
private JButton sendButton = new JButton("Send");
public PanelCommSender()
add(sendingField);
add(sendButton);
public void addActionListener(ActionListener al)
// attach this listener to the button
sendButton.addActionListener(al);
* call this to get the text currently in the textfield
* @return String text
public String getText()
return sendingField.getText();
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
* Subclasses JPanel, receives text from another class
* @author Pete
public class PanelCommReceiver extends JPanel
private JTextField showResultsField = new JTextField(12);
public PanelCommReceiver()
showResultsField.setEditable(false);
add(new JLabel("Results from other panel: "));
add(showResultsField);
* call this to set text of textField
* @param text
public void setText(String text)
showResultsField.setText(text);
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class PanelCommControl
private static void createAndShowUI()
// create new instances of the receiving and sending panels:
final PanelCommReceiver receivePanel = new PanelCommReceiver();
final PanelCommSender sendPanel = new PanelCommSender();
// let the communicate w/ each other
sendPanel.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
receivePanel.setText(sendPanel.getText());
// place the receiving JPanel into a JFrame
JFrame frame = new JFrame("Receiving Panel");
frame.getContentPane().add(receivePanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(new Dimension(300, 300)); // make it bigger so it can be seen
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
// place the sending JPanel into a JDialog
JDialog dialog = new JDialog(frame, "Sending Panel", false);
dialog.getContentPane().add(sendPanel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
public static void main(String[] args)
java.awt.EventQueue.invokeLater(new Runnable()
public void run()
// run the whole show in a thread-safe manner
createAndShowUI();
} -
How can I access another class in a MembershipRule's Expression
Hello,
I want to create an InstanceGroup using Module Microsoft.SystemCenter.GroupPopulator.
I need to collect all Logical Disks which contain an MS SQL DB Log File.
I would start as follows:
<DataSource ID="DS" TypeID="SC!Microsoft.SystemCenter.GroupPopulator">
<RuleId>$MPElement$</RuleId>
<GroupInstanceId>$Target/Id$</GroupInstanceId>
<MembershipRules>
<MembershipRule>
<MonitoringClass>$MPElement[Name="Windows!Microsoft.Windows.LogicalDisk"]$</MonitoringClass>
<RelationshipClass>$MPElement[Name="MSIL!Microsoft.SystemCenter.InstanceGroupContainsEntities"]$</RelationshipClass>
<Expression>
<And>
<!--
First Expression
-->
<Expression>
<SimpleExpression>
<ValueExpression>
<Property>$MPElement[Name="Windows!Microsoft.Windows.LogicalDevice"]/Name$</Property>
</ValueExpression>
<Operator>Equal</Operator>
<ValueExpression>
<!--
How can I access another class's properties ?
-->
<GenericProperty>$MPElement[Name="SQL!Microsoft.SQLServer.2008.DBLogFile"]/Drive$</GenericProperty>
</ValueExpression>
</SimpleExpression>
</Expression>
<Expression>
<SimpleExpression>
<ValueExpression>
<HostProperty>
<MonitoringClass>$MPElement[Name="Windows!Microsoft.Windows.Computer"]</MonitoringClass>
<Property>PrincipalName</Property>
</HostProperty>
</ValueExpression>
<Operator>Equal</Operator>
<ValueExpression>
<GenericProperty>$MPElement[Name="SQL!Microsoft.SQLServer.2008.DBLogFile"]/Drive$</GenericProperty>
</ValueExpression>
</SimpleExpression>
</Expression>
</And>
</Expression>
</MembershipRule>
</MembershipRules>
</DataSource>
In the first expression you "see" my question:
I want to compare the LogicalDisk's Name Property with the DB Log File's Drive property.
But how can I access the DB Log File's Drive property in this MembershipRule ?
Furthermore LogicalDisk and DB Log File must be hosted on the same Windows Computer.
Would be great if somebody could help.
Thanks
SebastianHi Niki,
thanks for the idea, but that will not work. $Target/Id$ refers always to the group to be discovered.
On last week end I was given following idea, hope it will work:
Step 1
Collect all the DB SQL Logfile Objects and write computername (PrincipalName?) and Driveletter into a textfile, line by line. Shouldn't be a problem, PowerShell is your friend.
Step 2
Read the file from Step 1, build discovery data for each disk drive as object of class "Logical Disk (Server)",
and then discover the containment-relationships from those Logical Drive(Server) Objects to the InstanceGroup.
Perhaps I must do it for the OS-Version related Disks, because I need the target classes of the Logical Disk Freespace monitors. Some more work. "Risks": I donot know the discovery algorithm for the Logical Disk(Server) Objects, but a "deep
dive" into the MPs should help.
Thanks to all, who have read.
I will inform you about progress and success
sebastian -
Access Another Class' Property Value That is Defined in the faces-config?
I have a private property "dataTransferType" with public getter and setter in the DataFile class. The initial value of the "dataTransferType" is defined in the faces-config.xml file. I want to get the "initial value" of the "dataTransferType" in another class and the compiler does not like the way I access this property.
Here is the snippet of the DataFile class, which shows the declaration and the getter and setter for the property:
public class DataFile implements java.io.Serializable
private String dataTransferType;
public DataFile(){}
public DataFile( String aDataTransferType )
this.dataTransferType = aDataTransferType;
public String getDataTransferType()
return dataTransferType;
public void setDataTransferType( String dataTransferType )
this.dataTransferType = dataTransferType;
}Here is the way that the initial value of the "dataTransferPropery" is set in the faces-config.xml file:
<managed-bean>
<managed-bean-name>dataFile</managed-bean-name>
<managed-bean-class>propertyBeans.DataFile</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>dataTransferType</property-name>
<property-class>java.lang.String</property-class>
<value>importFile</value>
</managed-property>
</managed-bean>Now, in another class FileManagementBean, I first instantiate the DataFile class
private DataFile datafile;and then in the constructor of the FileManagementBean I tried to access the initial value of the property "dataTransferType":
this.recordItems = this.getRecordsList( datafile.dataTransferType );The compiler did not like it at all.
But, if I arbitrary introduced a String in the FileManagementBean:
String defaultSelectedDataTransferType = "importFile";
this.recordItems = this.getRecordsList( defaultSelectedDataTransferType );My code worked as I had expected without any problem.Thanks for all your attention.
The runtime error is rather strange:
>
javax.servlet.ServletException: javax.faces.FacesException: javax.faces.FacesException: Can't instantiate class: 'actions.DataManagementBean'.. class actions.DataManagementBean : java.lang.NullPointerException
The DataManagementBean is the class that accesses the property "dataTransferType" in the DataFile class. And the initial value of the "dataTransferType" is defined in the faces-config.xml file.
If I arbitrarily introduced a String value in the DataManagementBean:
String defaultSelectedDataTransferType = "importFile"and in the DataManagementBean's constructor, I use this statement:
this.recordItems = this.getRecordsList( defaultSelectedDataTransferType );Things worked as I had expected without problem. But, I think this is not an elegant way of coding it. Because there is a pre-defined value of dataTransferType in the faces-config.xml file, I should access it from there.
But, when I specify:
this.recordItems = this.getRecordsList( datafile.getDataTransferType() );The DataManagementBean cannot even be instantiated!
In my faces-config.xml file, I have:
<managed-bean>
<managed-bean-name>dataManagementBean</managed-bean-name>
<managed-bean-class>actions.DataManagementBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>datafile</property-name>
<property-class>propertyBeans.DataFile</property-class>
<value>#{dataFile}</value>
</managed-property>
</managed-bean>
<managed-bean>
<managed-bean-name>dataFile</managed-bean-name>
<managed-bean-class>propertyBeans.DataFile</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
<managed-property>
<property-name>dataTransferType</property-name>
<property-class>java.lang.String</property-class>
<value>importFile</value>
</managed-property>
</managed-bean>
...... -
How to access an attribute(this is referencing to another class) in a class
Dear Gurus,
I have to read an attribute of a class and that attributes type another class.
I have intantiated the class and my question is how to read the attribute. I know I can not dirrectly read the attribute since this is another class. I think I have to first reference the attribute right? Please advise me.
My code looks like below:
data: lo_fpm type ref to if_fpm.
data: lo_msg_mgr type ref to if_fpm_message_manager.
data: lo_component_manager type ref to cl_fpm_component_manager.
lo_fpm = cl_fpm_factory=>get_instance( ). " cl_fpm_factory is a class which has a static method get_instance
lo_msg_mgr = lo_fpm->mo_message_manager.
lo_component_manager = lo_fpm->mo_component_manager.
The above statement is giving syntax error. I do not know why.
The basic difference b/n the two methods is if_fpm~mo_message_manager type ref to if_fpm_message_manager and
mo_component_manager type ref to cl_fpm_component_manager.
Any help would be appreciated.
Thanks,
GSMHello
I cannot test the following coding because I do not get the singleton instance yet it should work:
*& Report ZUS_SDN_CL_FPM_FACTORY
*& Thread: How to access an attribute(this is referencing to another class) in a class
*& <a class="jive_macro jive_macro_thread" href="" __jive_macro_name="thread" modifiedtitle="true" __default_attr="1398429"></a>
REPORT zus_sdn_cl_fpm_factory.
DATA: go_fpm TYPE REF TO cl_fpm. " class implements if_fpm.
DATA: go_msg_mgr TYPE REF TO if_fpm_message_manager.
DATA: go_component_manager TYPE REF TO cl_fpm_component_manager.
START-OF-SELECTION.
BREAK-POINT.
go_fpm ?= cl_fpm_factory=>get_instance( ). " cl_fpm_factory is a class which has a static method get_instance
CHECK ( go_fpm IS BOUND ).
go_msg_mgr = go_fpm->mo_message_manager.
go_component_manager = go_fpm->mo_component_manager.
END-OF-SELECTION.
Regards
Uwe -
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(); -
Accessing Enclosing Class Members From Inner Class Subclass
I have the following scenario that I cannot get to work. Notice the comments in B.doWork() for the problem code. In B.doWork(), how do I access m_strA?
* A.java
* Created on July 5, 2002, 2:20 PM
package Projects.InnerTrouble.Files;
public class A {
public abstract class InnerA {
public abstract void doWork ();
public String m_strA;
/** Creates new A */
public A ()
new InnerA() {
public void doWork ()
System.out.println("A$InnerA$1's doWork() called!");
m_strA = "Annonymous subclass of InnerA's doWork did this";
}.doWork();
* @param args the command line arguments
public static void main (String args[])
A oTemp = new A();
System.out.println(oTemp.m_strA);
B.getB(oTemp).doWork();
System.out.println(oTemp.m_strA);
class B extends A.InnerA {
public B (A a)
a.super();
public void doWork ()
System.out.println("B's doWork() called!");
// How do I access m_strA within B's doWork() method? The following is what I would expect to be the answer, but it does not compile
// A.this.m_strA = "B's doWork did this";
private static A.InnerA sm_oInnerA;
public static A.InnerA getB (A a)
if (sm_oInnerA == null)
sm_oInnerA = new B(a);
return (sm_oInnerA);The whole point is that B is not an inner class of A
so it does not have access to A's member variables.
Eventhough B extends an inner class of A, that does
not make B an inner class of A. That is in the JLS,
but not so elegantly as I have put it, hehe.
If B were an innerclass of InnerA, then it would
qualify to access A's member variables.OK, I think that you are finally getting through to my thick skull on this one. Let me restate and get your check-off on my understanding of the situation.
The only classes with access to A's this reference are A and inner classes of A that are found within the definition of A. So, despite the fact that A and B are in the same package (and B should have access to A's non-private members because B and A are in the same package), and despite the fact that we would normally state that B "is a" InnerA (which is an inner class of A and would have access to a reference to the A.this reference), B is not allowed access to A.this (because B "is not really a" InnerA in the same way that the anonymous implementation of InnerA "is a" InnerA). However, nothing would prevent me from giving B access to a reference of the enclosing A as long as it was done via a method of InnerA, and as long as the implementation of that method is contained in A's implementation.
Does this "access" rule realy make sense? Are you aware of the justification for this rule? Or is the justification stated in the JLS? I would think that the compiler ought to be able to figure this kind of thing out and allow it. It seems to me the fact that I defined B in the way that I did, and the fact that B "is a" InnerA, implies that I desired a fairly tight relationship to A. In fact, I desired the exact relationship that exists for the anonymous implementation of InnerA.
The following is a modified version of my original example that runs as I originally wanted it to, but works around the access rules discussed on this forum thread:
* A.java
* Created on July 5, 2002, 2:20 PM
package Projects.InnerTrouble.Files;
public class A {
public abstract class InnerA {
public abstract void doWork ();
/** added to allow implementors of InnerA that are not enclosed in A's class definition to have access to the enclosing class */
public A myEnclosingInstance ()
return (A.this);
public String m_strA;
/** Creates new A */
public A ()
new InnerA() {
public void doWork ()
System.out.println("A$InnerA$1's doWork() called!");
m_strA = "Annonymous subclass of InnerA's doWork did this";
}.doWork();
* @param args the command line arguments
public static void main (String args[])
A oTemp = new A();
System.out.println(oTemp.m_strA);
B.getB(oTemp).doWork();
System.out.println(oTemp.m_strA);
class B extends A.InnerA {
public B (A a)
a.super();
public void doWork ()
System.out.println("B's doWork() called!");
// The following is what I would expect to be the answer, but it does not compile
// A.this.m_strA = "B's doWork did this";
// added myEnclosingInstance() to get functionality desired above
myEnclosingInstance().m_strA = "B's doWork did this";
private static A.InnerA sm_oInnerA;
public static A.InnerA getB (A a)
if (sm_oInnerA == null)
sm_oInnerA = new B(a);
return (sm_oInnerA);
} -
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()) -
Hey,
I am trying to access another class function. I have 2 Classes and my main menu features are in my Main Class and I want to call that function from my Level Class
What is a good idea to approach this, some how I need to import it in a way but I don't know how I could do that.
Thanks,
McbainGames11Fixed it myself
Answer:
public static var instance:Main;
public function Main()
instance = this;
And I called a function from Main Class in my Level Class using:
Main.instance.function();
Maybe you are looking for
-
Creating a new line for a row layout
Hi i am building a web service based OA page... For this i have a created a VO with transient variables which holds the values from webservice. Now i have a row layout region where i key in some values which are required to call webservice.. using th
-
Picture has noise after export to JPEG
Hey guys, I am using Lightroom 5.2 64bit version on my windows. After I export my raw in to the jpeg it has noise. But in the develop module it hasn´t. Also it has got a little bit noise in the library, but it´s the same picture. Where is the sense?
-
Unmatching Zipcodes and charges without purchases
So, the other day I decide and try to purchase the Crash Bandicoot game for my iPhone which is $9.99. I go through the usual buying process and then it says there is a problem with a past purchase and to click on something to solve it. I click on it
-
Problem of openning the queries.
Dear experts, I have a problem in openning the existant queries. The BEX analyse shows the infomation as "No entry" when i tried to open a query. And then i did some tests. I found that when i delete a query, (ex: Name: BtoB: Search for the new mater
-
Help plz just for a project...
can some1 explain this? public class Grading System{ public void get_GradeEquivalent(String temp_grade){ int grade= Integer.parse.Int(temp.grade); String remarks= ""; if ((grade>=90)&&(grade<=95)){ remarks= "Exellent"; e