MovieClip references from a class
I have a files that has movie clips and nested movie clips on the stage. I am now writing a class and want to give the MCs event handlers and other properties.
When I do something like the following:
myMC_mc.MyOtherMC_mc.mouseEnabled = false;
I get the error:
1120: Access of undefined property myMC_mc.
I added this to the top of my class and it seems to take away the error, but I thought this was not needed in AS3 anymore.
private var myMC_mc:MovieClip;
private var myMC_mc.MyOtherMC_mc:MovieClip;
What do I have to do to not get the error? How is this done right?
Thanks a lot for any help!
you can't access/reference objects until they exist.
if your class is the document class and myMC_mc doesn't exist on frame 1 of the main timeline, you'll have a problem.
Similar Messages
-
Nulling a movieclip made from a class - does it make it trashable?
Hi
I instantiate a class that makes some movieclips within it, and from the class that instatiated it, I add some event listeners to the moveiclips...
(simplified)
var myClip:MCClass = new MCClass();
myClip.mc1.addEventListener(MouseEvent.CLICK, doSomething);
If at some stage I state myClip = null, does that make the event listeners eligible to be garbage collected, or do I need to removeEventListener them prior to myClip = null?
Cheers!You have to both remove MyClip from the stage and also make it null to make the object that has the functions that are being used as event listeners available for garbage collection.
For example:
public class Obj1 {
protected var _obj2:Obj2;
public function get obj2():Obj2 {
return _obj2;
public function set obj2(value:Obj2):void {
if (value != _obj2) {
//should do this so the event listeners don't fire after obj2 nulled in larger context
if (_obj2) {
_obj2.child.removeEventListener('someEvent', listener);
_obj2 = value;
if (_obj2) {
_obj2.child.addEventListener('someEvent', listener);
protected function listener(e:Event):void {
//do something
public class MainClass {
protected var _obj1:Obj1;
protected var _obj2:Obj2;
protected function init():void {
_obj2 = new Obj2();
addChild(_obj2);
_obj1 = new Obj1();
_obj1.obj2 = _obj2;
protected function tearDown():void {
removeChild(_obj2);
_obj2 = null;
//if you don't null _obj1.obj2, the listener will keep firing until it is garbage collected
//but obj1 will eventually get garbage collected
_obj1=null; -
Controlling MovieClip properties from a Class that it's linked to
Hi all,
I have a Moveclip with a Dynamic text field instance name of
"optionName". The movie clip is linked to my custom Class "Toggle".
Is there a way for me to access "optionName" from my class?
Basically I am getting this error:
Thanks.Thanks, much appreciated.
-
Reference Flex Stage From AS Class
I have an AS2 Class that I am converting to AS3. There are
several functions which used to reference _root to get a list of
objects from the main "stage". I am having trouble finding a
reference from the class to the main application.
Specifically, this is what I would like to do:
In the AS3 class, I want to reference the main application's
stage display list and parse through it. For example, if I were
using the following code from
http://livedocs.macromedia.com/flex/2/docs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=L iveDocs_Parts&file=00001853.html
in an AS3 class, and I wanted to parse through the DisplayList of
the main application's stage objects, how could I reference the
main application stage without having to pass the objects through
from the main application?
The following code works if it is part of the main
application, but using 'this' in the function call doesn't work,
nor does the use of 'stage' if this same code is moved to and AS
class and imported into the main application.
function traceDisplayList(container:DisplayObjectContainer,
indentString:String = ""):void {
var child:DisplayObject;
for (var i:uint=0; i < container.numChildren; i++) {
child = container.getChildAt(i);
trace (indentString, child, child.name);
if (container.getChildAt(i) is DisplayObjectContainer) {
traceDisplayList(DisplayObjectContainer(child), indentString
+ " ")
traceDisplayList(this);
Any suggestoins? Am I just approaching this the wrong way?
Thank you.Thank you Peter. This was exactly what I needed. To make it
work properly I just had to:
import mx.core.Application
var tempObj:Object = Application.application;
traceDisplayList(tempObj);
It works great! Thank you. -
Loading a movieClip from a class
Hello all,
I'm attempting to write an AS 2.0 class using Flash through
which I can load and control multiple movie clips in the library
and from external files. I've attempted multiple different ways,
don't quite seem to be able to get the images to show up on the
screen. After some time searching, I've been unable to find a good
example online. Please excuse my inexperience with AS classes.
I'd like to write a class that extends MovieClip and is used
to control multiple 'sub' movieClips, all from methods inside the
instantiated class.
From .fla file, I call instantiate my class as follows:
var theScene:sphere3D = new sphere3D();
In the constructor of my class file, I'm attempting to attach
or load a movie. I simply want to get it to show up on the screen,
when I test the .fla movie. I've tried using attachMovie and
loadMovie with not luck.
dynamic class sphere3D extends MovieClip {
function sphere3D() {
this.attachMovie("shadow","shadow",1); // shadow being a
movie clip in the .fla library with linkage
shadow._x = 100;
shadow._y = 100;
this.createEmptyMovieClip ("shadow2", 100);
shadow2._x = 100;
shadow2._y = 100;
shadow2.loadMovie("images/cube.png");
What am I doing wrong? Suggestions for stuff to test would be
welcome.
Thank you,
dana.Ah, thank you, that make sense now. The solution you
suggested worked great.
I did also find two other solutions, for anyone else who
might read this. One is to essentially create an empty movieclip on
your timeline. From the linkage window for the empty movieclip, I
made sure I set the Class field to the name of the class I'd
written, something I didn't do previously. This attaches all the
class actionscript to the empty movieclip, and even automatically
runs the constructor when the empty movieclip is placed on the
timeline. It also automatically provides a 'reference' to the main
timeline when I refer to this.attachMovie() from inside the class.
So it worked, but isn't as elegant as doing everything from the
actionscript (unless you are building a component).
The last reference I came across is the
Object.registerClass() method used to attach as class to an object,
similar to using the Linkage method above. But I haven't
successfully tried it yet.
Thanks again for the help kglad,
dana.
Dana Sheikholeslami
Art Institute of California -
Manipulate movieclip from custom class
Hello.
I have a movieclip (instance name preload), inside of it, I have another movieclip (bar) ... what i'm trying to do is a preloader for external files... i have a custom class and i what to manipulate my movieclip preload from it... you know verify the progress of the load:
Inside my class a have this function
public function loadProgress(e:ProgressEvent):void {
percent=e.bytesLoaded/e.bytesTotal*100;
rutaDos.preload.bar.scaleX=percent;
rutaDos is a reference to the stage... it works, I'm sure of it... the problem is:rutaDos.preload.bar.scaleX; I upload the files but it doesn't verify the progress of the load.
thanks for the helpthe complete class is:
package com.ludwing{
import flash.net.*;
import flash.events.*;
import flash.display.*;
import fl.transitions.*;
import fl.transitions.easing.*;
import flash.display.Stage;
import gs.TweenMax;
import gs.easing.*;
import gs.events.*;
public class Transiciones extends MovieClip {
public var url:URLRequest;
public var loader:URLLoader;
public var rutaDos:MovieClip;
public var imgLoader:Loader;
public var movie:MovieClip;
public var container:Sprite;
public var bg:Boolean;
public var porcentaje:Number;
public function Transiciones(mRuta:MovieClip, miRuta:String,isBG:Boolean,contain:MovieClip) {
rutaDos=mRuta;
bg=isBG;
movie=contain;
container=new Sprite();
url=new URLRequest(miRuta);
imgLoader=new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onLoaderComplete);
imgLoader.load(url);
public function onLoaderComplete(e:Event) {
imgLoader=new Loader();
imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imgComplete);
imgLoader.contentLoaderInfo.addEventListener(Event.INIT, imgInit);
imgLoader.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, loadProgress);
imgLoader.load(url);
public function loadProgress(e:ProgressEvent):void {
porcentaje=e.bytesLoaded/e.bytesTotal*100;
rutaDos.preload.bar.rotation=90;
public function imgInit(e:Event) {
movie.alpha=0;
rutaDos.preload.alpha=1;
public function imgComplete(event:Event) {
rutaDos.preload.alpha=0;
movie.addChild(imgLoader);
var myTween:TweenMax = TweenMax.to(movie, 1, {alpha:1, ease:Circ.easeOut});
myTween.addEventListener(Event.COMPLETE, onTransitionFinish);
public function onTransitionFinish(e:Event):void {
//MovieClip(root).gotoAndPlay(2);
//rutaDos.ext.gotoAndStop(2)
/*var my_parent:MovieClip=parent.parent as MovieClip;
my_parent.nextSection=2;
my_parent.gotoAndStop(my_parent.nextSection);*/
//rutaDos.stage.addEventListener(Event.RESIZE, resizeHandler);
if (bg==true) {
rutaDos.gotoAndStop(14);
I try to use an empty movieclip to load a external swf (instance name: ext) this way:
var transicion:Transiciones=new Transiciones(this, "welcome.swf",true,ext);
The external swf loads correctly, but when it is loading (i mean de progress load), the preload doesn't work.... -
How do I reference the stage from a class? I need to add eventlisteners to the
stage for mouse movement. I also need to add custom cursors. I always get an error when I try to reference stage
. anything. Or event if I do this:
var stageRef:Stage;
then later: stageRef.stage.addEventList.....
What am I missing or not understanding?I cannot get it to work. Here is my code:
package com {
// core
import flash.display.MovieClip;
import flash.display.Stage;
// import custom classes
import com.main.BuildStageClass;
import com.main.BootClass;
import com.utils.RotateClass;
import com.utils.ZoomClass;
import com.utils.PanClass;
import com.main.HotSpotClass;
// initialize class
public class DocClass extends MovieClip {
// custom classes
// variables
public static var build_stage_class:BuildStageClass;
public static var boot_class:BootClass;
public static var rotate_class:RotateClass;
public static var zoom_class:ZoomClass;
public static var pan_class:PanClass;
public static var hot_spot_class:HotSpotClass;
// stage containers
public static var main_stage:MovieClip;
public static var background_layer:MovieClip;
public static var content_layer:MovieClip;
public static var popup_layer:MovieClip;
// main constructor
public function DocClass() {
// initialize classes
build_stage_class = new BuildStageClass();
boot_class = new BootClass();
rotate_class = new RotateClass();
zoom_class = new ZoomClass();
pan_class = new PanClass(this.stage);
hot_spot_class = new HotSpotClass();
// add containers to stage
main_stage = new MovieClip();
addChild(main_stage);
background_layer = new MovieClip();
main_stage.addChild(background_layer);
content_layer = new MovieClip();
main_stage.addChild(content_layer);
popup_layer = new MovieClip();
main_stage.addChild(popup_layer);
==========================
Now inside the pan class:
package com.utils{
// import classes
import flash.display.MovieClip;
import flash.display.Stage;
import flash.events.MouseEvent;
import flash.geom.Point;
import flash.ui.Mouse;
// import main classes
import com.DocClass;
// initialize class
public class PanClass extends MovieClip {
// variables
public var do_pan:Boolean = true;
public var last_point:Number = 0;
public var cur_point:Number = 0;
public var hand_cursor:HandCursor;
public var grab_cursor:PanCursor;
private var myStage:Stage;
// main constructor
public function PanClass(docClassStage:Stage) {
// constructor code
myStage = docClassStage;
myStage.addEventListener(MouseEvent.MOUSE_MOVE, panHandler);
Ideas? -
How can i use class reference from an array effeciently?
Hi,
I made some test here with getting a class reference from an array and using the reference's methods or variables.
Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
Example #1----Strongly typed
Var reference:Person;
Var num:int;
//Assignation
reference=arrayEx[0];-----IT IS SLOW HERE
//Use
num=reference.number --- IT IS FAST HERE
Example #2---Not typed
Var reference:*;
Var num:int;
//Assignation
reference=arrayEx[0]; ---- IT IS FAST HERE
//Use
num=reference.number ---IT IS SLOW HERE
No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
If someone knows how, please tell me,
DominikHi,
I made some test here with getting a class reference from an array and using the reference's methods or variables.
Basically arrayEx is a container of type Array and it contains the Person's class instance in it. Num is a number extracted from the Person's instance
Example #1----Strongly typed
Var reference:Person;
Var num:int;
//Assignation
reference=arrayEx[0];-----IT IS SLOW HERE
//Use
num=reference.number --- IT IS FAST HERE
Example #2---Not typed
Var reference:*;
Var num:int;
//Assignation
reference=arrayEx[0]; ---- IT IS FAST HERE
//Use
num=reference.number ---IT IS SLOW HERE
No matter what i change in both code like casting Person on arrayEx, i cant seem to make them work both fast at the same time
If someone knows how, please tell me,
Dominik -
MovieClip not adding from my class
If I have the following on the timeline in my FLV, it works and attaches my movie from the library to the stage. If I do the same from my class, it does not. What could be the issue?
var myMC:ToolTipMc = new ToolTipMc();
addChild(myMC);
Thanks a lot for any help!Brian914,
You have added the ToolTipMc to the display list of you class but is your class added to the display list of the Stage or Document root. Check and see if your class is a display object like MovieClip and that it is added to the stage. bellow is an example.
package {
import flash.display.*;
public class MyToolTip extends MovieClip{
public function MyToolTip():void{
//code for your tool tip
package {
import flash.display.*;
import MyToolTip;
public class MyToolTipHolder extends MovieClip{
public var tTip:MyToolTip;
public function MyToolTipHolder():void{
tTip = new MyToolTip();
addChild(tTip);
Now if you are trying to put the tooltip on the screen you wil need to first add the MyToolTipHolder to the displaylist then it will add MyToolTip to its display list and it will show up. If you want to add the ToolTipHolder to any other display Object like flv, then add the myFLV.addChild(toolTipHolder);
Hope This Helps
Edithson Abelard
Passion 47 -
How can I assign image file name from Main() class
I am trying to create library class which will be accessed and used by different applications (with different image files to be assigned). So, what image file to call should be determined by and in the Main class.
Here is the Main class
import org.me.lib.MyJNIWindowClass;
public class Main {
public Main() {
public static void main(String[] args) {
MyJNIWindowClass mw = new MyJNIWindowClass();
mw.s = "clock.gif";
And here is the library class
package org.me.lib;
public class MyJNIWindowClass {
public String s;
ImageIcon image = new ImageIcon("C:/Documents and Settings/Administrator/Desktop/" + s);
public MyJNIWindowClass() {
JLabel jl = new JLabel(image);
JFrame jf = new JFrame();
jf.add(jl);
jf.setVisible(true);
jf.pack();
I do understand that when I am making reference from main() method to MyJNIWindowClass() s first initialized to null and that is why clock could not be seen but how can I assign image file name from Main() class for library class without creating reference to Main() from MyJNIWindowClass()? As I said, I want this library class being accessed from different applications (means different Main() classes).
Thank you.Your problem is one of timing. Consider this simple example.
public class Example {
public String s;
private String message = "Hello, " + s;
public String toString() {
return message;
public static void main(String[] args) {
Example ex = new Example();
ex.s = "world";
System.out.println(ex.toString());
}When this code is executed, the following happens in order:
1. new Example() is executed, causing an object to constructed. In particular:
2. field s is given value null (since no value is explicitly assigned.
3. field message is given value "Hello, null"
4. Back in method main, field s is now given value "world", but that
doesn't change message.
5. Finally, "Hello, null" is output.
The following fixes the above example:
public class Example {
private String message;
public Example(String name) {
message = "Hello, " + name;
public String toString() {
return message;
public static void main(String[] args) {
Example ex = new Example("world");
System.out.println(ex.toString());
} -
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." -
Calling a method and setting an ImageIcon with source from anoth class
I am trying to make a simple game, first I am trying to set up a game board, and make it possible to place units on the board. (This game will probably never be possible to play, I am just using it to try to understand Java, GUI, Swing, and using more than one class).
So far I have 4 classes: Board (extends JFrame, sets up a gameboard, on which to place the pieces), Unit (a class from which the specific units types will inherit), Horse (my only type of unit, which extends the Unit class), and Game (which calls methods from the other classes).
(These don't do much now.. this is what they will do, hopefully).
All these classes are in a package called Gamev1.
In the main method of Game, I do:
---code--
public static void main (String[]args){
new Board().show();
Horse horseUnits[] = new Horse[1];
horseUnits[0] = new Horse();
horseUnits[0].moveUnit(squares[0]);
end of code--
when I debug it I get:
myjava/FirstGraphics/Gamev1/Game.java [25:1] cannot resolve symbol
symbol: variable squares
location: class.myjava.FirstGraphics.Gamev1.Game
horseUnits[0].moveUnitsquares[0]);
1 error
---code----
moveUnit(JLabel moveTo)
is a method in Unit class:
public void moveUnit(JLabel moveTo){
target=moveTo;
target.setIcon(this.image);
if (this.position !=null)
this.position.setIcon(noUnit);
this.position=moveTo;
---end of code---------
squares[] is an array of JLabels which is set up in the Board class, whenever a new Board is created:
---code---
JLabel squares[] = new JLabel[100];
for (int s=0; s<100; s++){
squares[s] = new JLabel();
---end of code---
I tried changing the reference from squares[0] to Board.squares[0] but I got the same error message in debug.
Any idea what is wrong?
I have another problem, which is probably similar.
in the Board class I call:
squares[s].setIcon(Unit.noUnit);
and in the Unit class I have:
static ImageIcon noUnit = new ImageIcon("images//none.gif");
I don't get an error message mentioning it, but (without the attempt to place the horse on the board) the program compiles, but doesn't put this image on the labels. Any idea what is the porblem here?
If I have not given enough information for anyone to help me, please tell me what further information I should give.
Thanks to anyone who answers.I got it to work with
Board board = new Board();
horseUnits[0].moveUnit(board.squares[0]);To use Board.squares[0], squares would have to be static.
The ImageIcon seemed to work okay. I noticed that your post had two slashes in the url [/] - that might throw things off . . .
The code below has the icon call at the end of setLabeLProperties.
I got carried away playing with the graphics so the squares don't work very well.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class HumaniBlue {
public static void main(String[] args) {
Board board = new Board();
board.show();
JLabel label5 = board.getLabel(5);
//System.out.println("label5 name = " + label5.getText());
Horse[] horseUnits = new Horse[1];
horseUnits[0] = new Horse();
horseUnits[0].moveUnit(board.squares[0]);
class Unit {
static ImageIcon noUnit = new ImageIcon("images/bclynx.jpg");
public void moveUnit(JLabel square) {
class Horse extends Unit {
public Horse() {}
class Board {
JFrame f;
JPanel gameBoard;
int labelSize;
JLabel[] squares = new JLabel[16];
GridBagConstraints gbc = new GridBagConstraints();
public Board() {
gameBoard = new JPanel(new GridBagLayout()) {
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
double width = getSize().width;
double height = getSize().height;
g2.setPaint(Color.white);
g2.fill(new Rectangle2D.Double(0, 0, width, height));
g2.setPaint(Color.black);
Shape line;
double
gridSize = (width < height ? width : height) * 0.8,
gridUnit = (width < height ? width : height) / 5,
x = (width - gridSize) / 2,
y = (height - gridSize) / 2;
labelSize = (int)gridUnit;
for(int j = 0; j < 5; j++) {
line = new Line2D.Double(x, y, x, y + gridSize);
g2.draw(line);
x += gridUnit;
x = (width - gridSize) / 2;
for(int j = 0; j < 5; j++) {
line = new Line2D.Double(x, y, x + gridSize, y);
g2.draw(line);
y += gridUnit;
//System.out.println("width = " + width + "\theight = " + height + "\n" +
// "x = " + x + "\ty = " + y + "\n" +
// "gridSize = " + gridSize + "\tgridUnit = " + gridUnit);
f = new JFrame();
f.getContentPane().add(gameBoard);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400,400);
f.setLocation(600,200);
//f.setVisible(true);
setLabelProperties();
private void setLabelProperties() {
int
r = 30,
g = 30,
b = 0,
inc = 55;
//System.out.println("labelSize = " + labelSize);
for(int j = 0; j < squares.length; j++) {
squares[j] = new JLabel("Square " + j, JLabel.CENTER);
squares[j].setOpaque(true);
squares[j].setPreferredSize(new Dimension(73, 73));
// add labels
int index = 0;
gbc.gridx = 0;
gbc.gridy = 0;
for(int y = 0; y < 4; y++) {
for(int x = 0; x < 4; x++) {
index = y * 4 + x;
squares[index].setBackground(new Color(r,g,b,90));
gameBoard.add(squares[index], gbc);
gbc.gridx++;
r += inc;
gbc.gridy++;
gbc.gridx = 0;
r = 90;
g += inc;
squares[9].setIcon(Unit.noUnit);
public void show() {
f.setVisible(true);
public JLabel getLabel(int index) {
return squares[index];
} -
Calling method from another class problem
hi,
i am having problem with my code. When i call the method from the other class, it does not function correctly?
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class Dice extends JComponent
private static final int SPOT_DIAM = 9;
private int faceValue;
public Dice()
setPreferredSize(new Dimension(60,60));
roll();
public int roll()
int val = (int)(6*Math.random() + 1);
setValue(val);
return val;
public int getValue()
return faceValue;
public void setValue(int spots)
faceValue = spots;
repaint();
@Override public void paintComponent(Graphics g) {
int w = getWidth();
int h = getHeight();
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(Color.WHITE);
g2.fillRect(0, 0, w, h);
g2.setColor(Color.BLACK);
g2.drawRect(0, 0, w-1, h-1);
switch (faceValue)
case 1:
drawSpot(g2, w/2, h/2);
break;
case 3:
drawSpot(g2, w/2, h/2);
case 2:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
break;
case 5:
drawSpot(g2, w/2, h/2);
case 4:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
break;
case 6:
drawSpot(g2, w/4, h/4);
drawSpot(g2, 3*w/4, 3*h/4);
drawSpot(g2, 3*w/4, h/4);
drawSpot(g2, w/4, 3*h/4);
drawSpot(g2, w/4, h/2);
drawSpot(g2, 3*w/4, h/2);
break;
private void drawSpot(Graphics2D g2, int x, int y)
g2.fillOval(x-SPOT_DIAM/2, y-SPOT_DIAM/2, SPOT_DIAM, SPOT_DIAM);
}in another class A (the main class where i run everything) i created a new instance of dice and added it onto a JPanel.Also a JButton is created called roll, which i added a actionListener.........rollButton.addActionListener(B); (B is instance of class B)
In Class B in implements actionlistener and when the roll button is clicked it should call "roll()" from Dice class
Dice d = new Dice();
d.roll();
it works but it does not repaint the graphics for the dice? the roll method will get a random number but then it will call the method to repaint()???
Edited by: AceOfSpades on Mar 5, 2008 2:41 PM
Edited by: AceOfSpades on Mar 5, 2008 2:42 PMOne way:
class Flintstone
private String name;
public Flintstone(String name)
this.name = name;
public String toString()
return name;
public static void useFlintstoneWithReference(Flintstone fu2)
System.out.println(fu2);
public static void useFlintstoneWithOutReference()
Flintstone barney = new Flintstone("Barney");
System.out.println(barney);
public static void main(String[] args)
Flintstone fred = new Flintstone("Fred");
useFlintstoneWithReference(fred); // fred's the reference I"m passing to the method
useFlintstoneWithOutReference();
{code}
can also be done with action listener
{code} private class MyActionListener implements ActionListener
private Flintstone flintstone;
public MyActionListener(Flintstone flintstone)
this.flintstone = flintstone;
public void actionPerformed(ActionEvent arg0)
//do whatever using flinstone
System.out.println(flintstone);
}{code}
Edited by: Encephalopathic on Mar 5, 2008 3:06 PM -
Calling a non-static method from another Class
Hello forum experts:
Please excuse me for my poor Java vocabulary. I am a newbie and requesting for help. So please bear with me! I am listing below the program flow to enable the experts understand the problem and guide me towards a solution.
1. ClassA instantiates ClassB to create an object instance, say ObjB1 that
populates a JTable.
2. User selects a row in the table and then clicks a button on the icon toolbar
which is part of UIMenu class.
3. This user action is to invoke a method UpdateDatabase() of object ObjB1. Now I want to call this method from UIMenu class.
(a). I could create a new instance ObjB2 of ClassB and call UpdateDatabase(),
== OR ==
(b). I could declare UpdateDatabase() as static and call this method without
creating a new instance of ClassB.With option (a), I will be looking at two different object instances.The UpdateDatabase() method manipulates
object specific data.
With option (b), if I declare the method as static, the variables used in the method would also have to be static.
The variables, in which case, would not be object specific.
Is there a way or technique in Java that will allow me to reference the UpdateDatabase() method of the existing
object ObjB1 without requiring me to use static variables? In other words, call non-static methods in a static
way?
Any ideas or thoughts will be of tremendous help. Thanks in advance.Hello Forum:
Danny_From_Tower, Encephalatic: Thank you both for your responses.
Here is what I have done so far. I have a button called "btnAccept" created in the class MyMenu.
and declared as public.
public class MyMenu {
public JButton btnAccept;
//Constructor
public MyMenu() {
btnAccept = new JButton("Accept");
} I instantiate an object for MyMenu class in the main application class MyApp.
public class MyApp {
private MyMenu menu;
//Constructor
public MyApp(){
menu = new MyMenu();
public void openOrder(){
MyGUI MyIntFrame = new MyGUI(menu.btnAccept);
}I pass this button all the way down to the class detail02. Now I want to set up a listener for this
button in the class detail02. I am not able to do this.
public class MyGUI {
private JButton acceptButton;
private detail02 dtl1 = new detail02(acceptButton);
//Constructor
public AppGUI(JButton iButton){
acceptButton = iButton;
public class detail02{
private JButton acceptButton;
//Constructor
public detail02(JButton iButton){
acceptButton = iButton;
acceptButton.addActionListener(new acceptListener());
//method
private void acceptListener_actionPerformed(ActionEvent e){
System.out.println("Menu item [" + e.getActionCommand( ) + "] was pressed.");
class acceptListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
acceptListener_actionPerformed(e);
} I am not able to get the button Listener to work. I get NullPointerException at this line
acceptButton.addActionListener(new acceptListener());in the class detail02.
Is this the right way? Or is there a better way of accomplishing my objective?
Please help. Your inputs are precious! Thank you very much for your time! -
How do I create a runtime library reference from a J2EE library DC?
I've created a J2EE library DC that references some classes in an already deployed library. The referenced jar file has been correctly deployed, as it's successfully used by some other components. I can build the DC, since I've created created a compile-time reference to the local copy of the target jar file.
Unfortunately, I can't figure out how to create a runtime reference from my J2EE library to the already deployed library - there just doesn't appear to be any place to put the reference, at least using a gui-based function in NWDS. Unlike WebDynpro, which has a 'references' configuration option, J2EE lib's don't appear to have anything similar.
Where/How can I do this?
BTW, the Visual Administrator function 'ClassLoader Viewer ' is a very handy tool for diagnosing ClassDefNotFoundError errors....Hello Ken,
well it seems to be not a trivial thing.
1) Build your library DC.
2) Create folder "server" in root DC folder "_comp".
3) Extract provider.xml from generated SDA file to "server" folder.
4) Add references in provider.xml:
<references>
<reference type="library" strength="weak">
sapxmltoolkit
</reference>
<reference type="library" strength="weak">
com.sap.lcr.api.cimclient
</reference>
<reference type="service" strength="weak">
tc~sec~securestorage~service
</reference>
</references>
5) Rebuild DC. Deploy.
6) Enjoy!
Useful links:
http://help.sap.com/saphelp_webas630/helpdata/en/b5/22123b8d92294fac207283f3e8756e/content.htm
http://help.sap.com/saphelp_webas630/helpdata/en/09/5d963be736904c96cbdfe93793eb42/TEMPLATE_image002.gif
Best regards, Maksim Rashchynski
Maybe you are looking for
-
My ipad 3 has sound but no picture, what could it be
My ipad3 has sound, but no picture comes up. What can it be?
-
Why is my JTable row sort is not working?
Hey all, I wrote the following code for a JTable and I'm trying to use a table sorter to sort the first column content alphabetically, for now. Later, I'd like to use the third column and sort the table's rows based on ascending dates. For some reaso
-
Apache service doesnt start after clone
Hi we have a cloned environment and after clone finished successfully (as mentioned in logs ) , Apache service doesn't start at all while all other services are started successfully andwhen i issued adapcctl.cmd it resulted error status 2 . i think t
-
<script language="JavaScript"> function redirect(targetURL) alert("in redirect"); </script> <input name="aAct" type="button" value="Associate Activity" onClick="redirect(CED56.jsp?sysID=<%= request.getParameter("sysID") %>&sysName=<%= sys.getSystemNa
-
Error message when syncing new iphone
I am unable to sync my new i phone. every time I try an error message pops up and says you do not have the privilage to make changes. Any suggestions???