Setting native code from a class of a class passed in...

I hope this makes sense, and its probably a stupid question but here it goes.
I have a native function that takes in a java class. I can call the getters of this class from the native code to get values to fill out my c structure just fine, but conceptually I am not 100% how to call the getters of a class that is part of the other class I passed in. Basically i have something like this:
the java call to the native being:
public native void setJSource(JSource theSource);
JNIEXPORT void JNICALL Java_AbfaRegion_setJSource
  (JNIEnv *env, jobject thisObj, jobject someVarsObj)
          jclass clazz;
          jmethodID mid;
          jint val;
          clazz = (*env)->GetObjectClass(env,someVarsObj);
          mid = (*env)->GetMethodID(env,clazz, "GetHeight", "I");
          val = (*env)->CallIntMethod(env,someVarsObj, mid);
          //put val into my struct
          mid = (*env)->GetMethodID(env,clazz, "GetWidth", "I");
          val=(*env)->CallIntMethod(env,someVarsObj, mid);
          //put val into my struct
}I know how to do this...but what if I had a class say:
class myClass
    JSource theSource; //has its own getters and setters like GetHeight
    int someVal;
    double anotherVal;
    public native void setMyClass(myClass theClass)
    int GetSomeVal()
      return this.someVal;
    int GetAnotherVal()
      return this.anotherVal;
    void SetSomeVal(int iSomeVal) 
      this.someVal=iSomeVal;
    void SetAnotherVal(double dAnotherVal)
      this.anotherVal=dAnotherVal;
}and then suppose in the native setMyClass I would like to get the height of the jsource of myclass, how can i do that in native code, do I have to use findclass or something?
Thanks for any help here, sorry if its a dumb question..
-Shane

For any class whose methods you are going to call, you need to first get a reference to the "class" record. So if you have an outer class, and have looked up its class record, and called a getter, and been returned an object (phew!):
You need to now look up the class for the inner object; you can then look up the the methods and call them.
JNI supports two ways to look up class:
FindClass, where the key argument is the fully-qualified class name.
GetObjectClass, where the key argument is an object reference.

Similar Messages

  • Calling native code from Flex

    I was wondering, is there any way to call native code from Flex?
    Currently, we're writing browser plugins in order to call native code from a Flex application. However, it would be nice to be able to call native code directly from Flex, so that we could write it only per-platform, as opposed to currently per-platform-per-browser.

    In general, the sandbox does not allow you to access native code from Flex.
    I believe you can use Merapi, but perhaps only for AIR:
    http://www.merapiproject.net/
    You might be able to code around the Flex sandbox, but it would be a ton of work.
    If this post answers your question or helps, please mark it as such.

  • How do I get the java code from a class file ?

    I want to know how to findout the java code from a .class file . Is there any utility or any way to get the java code from a .class file. If so , please let me know the step by step procedure .
    Thanks
    Shiva

    Check out Mocha (http://www.brouhaha.com/~eric/computers/mocha.html)
    It's free!

  • Creating java code from a class diagram in JDeveloper

    I have created a class diagram in JDeveloper 11.1.1.3.0. When I generated java code from the class diagram by right clicking on the class diagram->transform->same diagram->UML to Java, a .java file is generated with attributes and getters/setters, and also a .uml_cla file is generated. What is this .uml_cla file exactly and what is it used for? Also I have a package.uml_pck file that was created 3 times. I have a package of com.xxx.xxxx, and it put this package.uml_pck file in "com", in "xxx", and in "xxxx". Do I need to retain all 3 of these files in my project?
    One more question related to this. When I change something in the java representation of the class diagram (i.e. a datatype), it updates the .java file that was generated from the class diagram, and it also works the other way...change the .java file and the java representation of the class diagram changes. However, the class diagram that the code was generated from does not change, nor does the mysterious .uml_cla file I asked about in the above paragraph.

    This did work for me, with an exception. I have put the .java files generated from the class diagram in a different package from the .class_diagram file, the package.uml_pck file, and the .uml_cla file to keep the actual source code separate. When I modified the .java file and transformed the class diagram from java to UML, it created the package.uml_pck file and the .uml_cla files again in the same package as the .java file, and they show the update. The package.uml_pck file, and the .uml_cla file that were originally created and are in the separate package from the .java files were untouched, thus the class diagram displayed does not reflect the change either. Does this mean I should not, or cannot, separate these files, and that they all must be left in the same package? (the purpose of separating it in the first place was for ease of deployment since we don't want to deploy any of the class diagram files) Thanks!

  • How move code from one class to other?

    I have a .fla file.
    There i have some keyframes with labels.
    On .fla file in property in Class field i adde MyMatching class.
    Also i have main code:
    package
         import flash.display.MovieClip;
         import flash.events.MouseEvent;
         import flash.text.TextField;
         public class MyMatching extends MovieClip
              var play_btn:MyButton = new MyButton();
              var kyky:MyTimer;
              public function MyMatching():void
                   welcomeScreen();
              public function welcomeScreen():void
                   stop();
                   trace("working");
                   play_btn.x = 210;
                   play_btn.y = 300;
                   addChild(play_btn);
                   play_btn.addEventListener(MouseEvent.CLICK, goToLevel_1);
              public function goToLevel_1(event:MouseEvent)
                   trace("level 1");
                   play_btn.visible = false;
                   gotoAndStop('Level1Screen');               
                   if (kyky==undefined) {
                        kyky = new MyTimer();
    And i have other class:
    package
         import flash.display.MovieClip;
         import flash.display.Stage;
         import flash.utils.getTimer;
         import flash.text.TextField;
         public class MyTimer extends Stage
              import flash.utils.getTimer;
              var gameStartTime:uint;
              var gameTime:uint;
              var gameTimeField:TextField;
              function mainFunction():void
                   gameTimeField = new TextField();
                   addChild(gameTimeField);
                   gameStartTime=getTimer();
                   gameTime=0;
                   addEventListener(Event.ENTER_FRAME,showTime);
              function showTime(event:Event)
                   gameTime=getTimer()-gameStartTime;
                   gameTimeField.text="You plaing: "+clockTime(gameTime);
              function clockTime(ms:int)
                   var seconds:int=Math.floor(ms/1000);
                   var minutes:int=Math.floor(seconds/60);
                   seconds-=minutes*60;
                   var timeString:String=minutes+":"+String(seconds+100).substr(1,2);
                   return timeString;
    Ho i can play code from class MyTimer in goToLevel_1 function(this function stand in my main class MyMatching) ?
    Thank you.

    First of all your MyTimer class is written wrong and sloppy.
    Why does it extend Stage? The most compact class to extend under the circumstances is Sprite.
    Also, it is very important to get into habit of datatype declarations. Not only it is good practice, in your case good compiler will throw error because although you return String, function doesn't return anything.
    In addition, it is important to declare namespaces like private public and protected inside classes. Not function clickTime():String but private function clockTime():String or public function clickTime():String.
    As for how to show your time elsewhere - you just need to create instnace of it and add it to disaply list:
    var myTimer:MyTimer = new MyTimer();
    addChild(myTimer);
    With that said, your class should look like this:
    package 
         import flash.display.Sprite;
         import flash.events.Event;
         import flash.display.MovieClip;
         import flash.utils.getTimer;
         import flash.text.TextField;
         public class MyTimer extends Sprite
              private var gameStartTime:uint;
              private var gameTime:uint;
              private var gameTimeField:TextField;
              public function MyTimer()
                   gameTimeField = new TextField();
                   addChild(gameTimeField);
                   gameStartTime = getTimer();
                   gameTime = 0;
                   addEventListener(Event.ENTER_FRAME,showTime);
              private function showTime(event:Event):void
                   gameTime = getTimer() - gameStartTime;
                   gameTimeField.text = "You playing: " + clockTime(gameTime);
              private function clockTime(ms:int):String
                   var seconds:int = Math.floor(ms / 1000);
                   var minutes:int = Math.floor(seconds / 60);
                   var timeString:String = minutes + ":" + String(seconds + 100).substr(1, 2);
                   return timeString;

  • Setting private fields from Parent class.

    Hi all, I have what seems to be a weird situation to me.
    Basically I have two classes:
    import java.lang.reflect.Field;
    public class Parent {
         protected void ensureDefaults() {
              Field[] declaredFields = getClass().getDeclaredFields();
              for (Field field : declaredFields) {
                   Object fieldValue = getDefaultValueForType(field.getType());
                   try {
                        System.out.println("defaulting field - name: " + field.getName() + " | this: " + this);
                        field.set(this, fieldValue);
                   } catch (Exception e) {
                        e.printStackTrace();
         private Object getDefaultValueForType(Class<?> type) {
              Object defaultValue = null;
              if (type.isAssignableFrom(String.class)) {
                   defaultValue = "default";
              } else if (type.isAssignableFrom(int.class)) {
                   defaultValue = -100;
              return defaultValue;
    public class Child extends Parent {
         private String name;
         private int age;
         public Child() {
              ensureDefaults();
         public String getName() {
              return name;
         public void setName(String name) {
              this.name = name;
         public int getAge() {
              return age;
         public void setAge(int age) {
              this.age = age;
    // Test Case
    import junit.framework.TestCase;
    public class ChildTest extends TestCase {
         public void testEnsureDefaults() {
              Child child = new Child();
              assertEquals("default", child.getName());
              assertEquals(-100, child.getAge());
    }The odd thing to me is that the output looks like:
    defaulting field - name: name | this: Child@7431b9
    java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
    ... more exception ...
    defaulting field - name: age | this: Child@7431b9
    java.lang.IllegalAccessException: Class Parent can not access a member of class Child with modifiers "private"
    ... more exception ...
    As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private. However, if you look it's saying that "this" is a Child, so shouldn't those fields be accessible? Shouldn't ensureDefaults be executed as if it was being called by the Child instance?
    Obviously, I can try to use the accessor methods, but that means creating strings for method names, and then looking for the methods. I'd like to avoid this and it seems to me this should work, no?
    Another odd thing is that if I change the fields in Child to protected, it works fine.
    Also, I'm not sure if this is important (I don't know enough about security managers to know if they're different platform to platform, version to version), I'm on a Mac OSX 10.4.11 and:
    java version "1.5.0_13"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_13-b05-241)
    Java HotSpot(TM) Client VM (build 1.5.0_13-121, mixed mode, sharing)
    Any help with this would be greatly appreciated.
    Thanks,
    Eric

    jschell wrote:
    As you can see, it doesn't like me setting (or getting for that matter - tried that) these fields because they're private.Myself I don't like it because it suggests a design problem which is associated with understanding that although a child is a parent that doesn't mean that a parent is a child.
    I understand that, but I don't see how this actually breaks that. The Child is executing a method that is passed down to it from it's Parent, but it's executing it as itself - by that I mean it's not looking at anything that it can't already look at, or at least I thought it was.
    Shouldn't ensureDefaults be executed as if it was being called by the Child instance?No.Ok, I thought it was. Can you please explain this a bit more, I want to understand it.
    >
    Another odd thing is that if I change the fields in Child to protected, it works fine.If you messed with reflection some more you could get to to work even with private. How exactly? I really don't want to bypass any security measures (by settings accessible or using a different security manager, or anything like that). As I mentioned in my last post, what I want to do really is nothing more than a nice way to have a generic toString or hashCode method, if it's not possible to do it nicely - within java's default constraints, I'd rather not.
    >
    However in general the idiom would still be wrong.I'm moving more towards using beans anyway, so I plan on just calling accessor methods which corrects the "wrong idiom" right?
    Thanks for all the help,
    Eric

  • How to hide the source code from the .class file

    Hi,
    By some jad tool we can recompile the .class files and get the java file corresponding to it. How to protect it?
    Anyone please help me..
    Thanks & Regards,
    N.Ravasankar

    An obfuscator can for example rename classes, variables to meaningless names, like one-letter names. And it can make some bytecode that is hard to decompile or just makes the code less readable when decompiled. Some obfuscators might even be able to do something to the code that makes decompilers not work or incorrect decompile code.

  • How get method source code from a class

    We developed a model generator tool that get a �base model� as an input and generated rich model.
    The �base model� is collection of POJO classes and the model generator analyzed the base model (with reflection) and with �ftl� generates �rich model� , which is the base model with additional annotations and logics.
    Some classes in the �base-model� may contain additional method and I need to copy those methods as they are to the �rich-model� generated sources.
    I need a way to copy those methods from the base-model (I work on it with reflection, but I have also the source) to the rich-model.
    I think to do this by decompile. Are there any better way?
    Is there any simple utility that decompile method?
    Thank you

    There is a big differnet between the input and the output.
    for example:
    input:
    @Key(indexs = { "name" })
    @SuppressWarnings(value = { "serial", "unused" })
    @Observers(observers = { @Observer(type = ObserverType.INSTANCE_INHERITANCE) })
    public class Device extends Segment {
         // ********************** Class Members: ********************** //
         private DeviceTypeEnum type;
         protected DeviceSetup deviceSetup;
         protected Networking networking;output:
    * model-project class. generated by ModelGenerator. *
    @Entity
    @Key(indexs={"name"})
    @NamedQueries(value={@NamedQuery(name="Device.FilterByIndex", query="SELECT d FROM Device d WHERE d.name=:name")})
    @Observers(observers={@Observer(type=ObserverType.INSTANCE_INHERITANCE)})
    public class Device extends Segment implements ObservableIfc
         private static final long serialVersionUID = -7782418163128836178L;
        // ********************** Class Members: ********************** //
        @Column(name="type_column")
        @Type(type="com.radware.insite.modelhelpers.utils.GenericEnumUserType", parameters = {@Parameter(name = "enumClass" , value = "com.radware.insite.modelhelpers.constants.ImConstants$DeviceTypeEnum")})
        private DeviceTypeEnum type;
        private FieldMetadata typeMD = new RefMetadata();
        @OneToOne(cascade={CascadeType.PERSIST, CascadeType.REFRESH, CascadeType.REMOVE}, fetch=FetchType.LAZY)
        @JoinColumn(name="dev_setup_2_dev")
        protected DeviceSetup deviceSetup = new DeviceSetup();
        private FieldMetadata deviceSetupMD = new RefMetadata();

  • Not able to access the native c code from servlet

    I want to call c function from servlet using JNI . I created the .so file and gave the library path . But when i try to load the library it says "Unsatisfied link error ". I am using tomcat on linux .. any more setting has to be done in order to call native code from servlets ?

    You need to post a little bit of code. What does your LoadLibrary() call look like?

  • How to set classpath from java class ??

    I have tried to use System.setProperty("java.class.path", "my class path string ") to set classpath dynamically. But it is not working. How to set it dynamically from java class ?? Thanks , gary

    Look into the java.net.URLClassLoader. You can't set the classpath after the fact but you can specify URL's that will checked when you try to load a class with that loader.

  • Access native methods from an applet

    hi all
    I am developping a applet which has to access the native method which is c++ code. but it does not work at all, even though it can be compiled well.
    it returns
    java.lang.ExceptionInInitializerError
         at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
         at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
         at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
         at java.lang.reflect.Constructor.newInstance(Unknown Source)
         at java.lang.Class.newInstance0(Unknown Source)
         at java.lang.Class.newInstance(Unknown Source)
         at sun.applet.AppletPanel.createApplet(Unknown Source)
         at sun.plugin.AppletViewer.createApplet(Unknown Source)
         at sun.applet.AppletPanel.runLoader(Unknown Source)
         at sun.applet.AppletPanel.run(Unknown Source)
         at java.lang.Thread.run(Unknown Source)
    Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission loadLibrary.MemoInfo)
         at java.security.AccessControlContext.checkPermission(Unknown Source)
         at java.security.AccessController.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkPermission(Unknown Source)
         at java.lang.SecurityManager.checkLink(Unknown Source)
         at java.lang.Runtime.loadLibrary0(Unknown Source)
         at java.lang.System.loadLibrary(Unknown Source)
         at InfoShow.<clinit>(InfoShow.java:24)
         ... 11 more
    who can give me some suggestions on accessing native method from applet! thx
    regards
    beginner

    you don't have access to native code from an applet unless you've modified your policy file or you're using a signed applet.

  • Delete scroller from other class

    Hi.
    I have FlashSite class where after clicking to button i see page with text and with scroll.
    If i click to 'close' button i want removeChild this page, text and scroll.
    But for scroll i use code from other class. (i insert this class like: import classes.Scroller.*;)
    So, how i can remove this scroller?
    code:
    public function lilyContent():void
                   // create a sample pane
                   addChild(lilyPageScroll);
                   lilyPageScroll.x = 360;
                   lilyPageScroll.y = 400;
                   // then attach a new scroller to the pane
                   var lilyScroller = new Scroller(lilyPageScroll, lilyPageScroll.width, 540, new scrollerFace(),"vertical");
    i use this line:
    var lilyScroller = new Scroller(lilyPageScroll, lilyPageScroll.width, 540, new scrollerFace(),"vertical");
    to add scroller.
    all code for FlashSite class:
    package
         import flash.display.*;
         import flash.text.*;
         import flash.events.*;
         import classes.Scroller.*;
         public class FlashSite extends MovieClip 
              var lilyDeskBack:LilyDescriptionBackground = new LilyDescriptionBackground();
              var lilyPageScroll = new LilyContent();
              //constructor
              public function FlashSite()
                   stop();
                   addEventListener(Event.ENTER_FRAME, flashSiteLoading);
              public function flashSiteLoading(event:Event)
                   var mcBytesLoaded:int=this.root.loaderInfo.bytesLoaded;
                   var mcBytesTotal:int=this.root.loaderInfo.bytesTotal;
                   var mcKLoaded:int=mcBytesLoaded/1024;
                   var mcKTotal:int=mcBytesTotal/1024;
                   flashSiteLoading_txt.text="Loading: "+mcKLoaded+"Kb of "+mcKTotal+"Kb";
                   if (mcBytesLoaded>=mcBytesTotal)
                        removeEventListener(Event.ENTER_FRAME, flashSiteLoading);
                        gotoAndPlay('welcomeSite');
                        lilyBtn.addEventListener(MouseEvent.CLICK, lilyDescription);
                        roseBtn.addEventListener(MouseEvent.CLICK, roseDescription);
                        jasmineBtn.addEventListener(MouseEvent.CLICK, jasmineDescription);
                        irisBtn.addEventListener(MouseEvent.CLICK, irisDescription);
              public function lilyDescription(event:MouseEvent):void
                   trace("Lily description goes here.");
                   roseBtn.visible = false;
                   jasmineBtn.visible = false;
                   irisBtn.visible = false;
                   addChild(lilyDeskBack);
                   lilyDeskBack.x = 350;
                   lilyDeskBack.y = 330;
                   lilyContent();
                   lilyDeskBack.LilyDesckClose_btn.addEventListener(MouseEvent.CLICK, closeLilyDescription);
              public function closeLilyDescription(event:MouseEvent):void
                   trace("close Lily description");
                   removeChild(lilyDeskBack);
                   removeChild(lilyPageScroll);
                   lilyScroller.visible = false;
                   roseBtn.visible = true;
                   jasmineBtn.visible = true;
                   irisBtn.visible = true;
              public function roseDescription(event:MouseEvent):void
                   trace("Rose description goes here.");
              public function jasmineDescription(event:MouseEvent):void
                   trace("Jasmine description goes here.");
              public function irisDescription(event:MouseEvent):void
                   trace("Iris description goes here.");
              public function lilyContent():void
                   // create a sample pane
                   addChild(lilyPageScroll);
                   lilyPageScroll.x = 360;
                   lilyPageScroll.y = 400;
                   // then attach a new scroller to the pane
                   var lilyScroller = new Scroller(lilyPageScroll, lilyPageScroll.width, 540, new scrollerFace(),"vertical");
    Thanks for help

    Make the lilyScroller object a class level object.
    Add to 'closeLilyDescription' method 'removeChild(lilyScroller);'
    package
         import flash.display.*;
         import flash.text.*;
         import flash.events.*;
         import classes.Scroller.*;
         public class FlashSite extends MovieClip 
              var lilyDeskBack:LilyDescriptionBackground = new LilyDescriptionBackground();
              var lilyPageScroll = new LilyContent();
              var lilyScroller;
              //constructor
              public function FlashSite()
                   stop();
                   addEventListener(Event.ENTER_FRAME, flashSiteLoading);
              public function flashSiteLoading(event:Event)
                   var mcBytesLoaded:int=this.root.loaderInfo.bytesLoaded;
                   var mcBytesTotal:int=this.root.loaderInfo.bytesTotal;
                   var mcKLoaded:int=mcBytesLoaded/1024;
                   var mcKTotal:int=mcBytesTotal/1024;
                   flashSiteLoading_txt.text="Loading: "+mcKLoaded+"Kb of "+mcKTotal+"Kb";
                   if (mcBytesLoaded>=mcBytesTotal)
                        removeEventListener(Event.ENTER_FRAME, flashSiteLoading);
                        gotoAndPlay('welcomeSite');
                        lilyBtn.addEventListener(MouseEvent.CLICK, lilyDescription);
                        roseBtn.addEventListener(MouseEvent.CLICK, roseDescription);
                        jasmineBtn.addEventListener(MouseEvent.CLICK, jasmineDescription);
                        irisBtn.addEventListener(MouseEvent.CLICK, irisDescription);
              public function lilyDescription(event:MouseEvent):void
                   trace("Lily description goes here.");
                   roseBtn.visible = false;
                   jasmineBtn.visible = false;
                   irisBtn.visible = false;
                   addChild(lilyDeskBack);
                   lilyDeskBack.x = 350;
                   lilyDeskBack.y = 330;
                   lilyContent();
                   lilyDeskBack.LilyDesckClose_btn.addEventListener(MouseEvent.CLICK, closeLilyDescription);
              public function closeLilyDescription(event:MouseEvent):void
                   trace("close Lily description");
                   removeChild(lilyDeskBack);
                   removeChild(lilyPageScroll);
                   removeChild(lilyScroller);
                   lilyScroller.visible = false;
                   roseBtn.visible = true;
                   jasmineBtn.visible = true;
                   irisBtn.visible = true;
              public function roseDescription(event:MouseEvent):void
                   trace("Rose description goes here.");
              public function jasmineDescription(event:MouseEvent):void
                   trace("Jasmine description goes here.");
              public function irisDescription(event:MouseEvent):void
                   trace("Iris description goes here.");
              public function lilyContent():void
                   // create a sample pane
                   addChild(lilyPageScroll);
                   lilyPageScroll.x = 360;
                   lilyPageScroll.y = 400;
                   // then attach a new scroller to the pane
                   lilyScroller = new Scroller(lilyPageScroll, lilyPageScroll.width, 540, new scrollerFace(),"vertical");

  • 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);
                                                     ^

  • 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];
    }

  • Accessing a native method from within a packaged class

    I have seen some very useful information from RPaul. However, I can not quite get it to work.
    I have a class "JNIGetUserId" that is in a package "com.services.localoptions". I am trying to call a native method from a dll. it works fine at the default package level. But not in the package. I have tried adding the "_" between each level of the directory in the h and c++ files. I also found that doing a javah at the top of the package structure it includes some information in the h file. A "_0005" shows up between each level.
    This is on Windows XP. I am also using VisualAge for Java. I also am using JDK 1.3.1.
    The source files:
    package com.services.localoptions;
    * This class provides the JNI Interface to call the
    * AD User Maintainence routines.
    * These routines are stored in the JNIGetUserIdLibrary.dll.
    * The routines are:
    * <ul>
    * <li>getUser - returns a string containing the User Id
    * <eul>
    * @author: Ray Rowehl
    * @date (10/15/2003 10:30:59 AM)
    public class JNIGetUserId
         // Load the library
         static
         try
              System.out.println("loading dll");
         System.loadLibrary("JNIGetUserIdLibrary");
         System.out.println("loaded dll");
         catch (UnsatisfiedLinkError ue)
              System.out.println("Link Error");
    * native C++ method to call getUserId routine
    public native String getUser() throws Exception;
    * This method allows us to test standalone..
    * Creation date: (10/16/2003 2:08:58 PM)
    * @param args java.lang.String[]
    public static void main(String[] args)
         try
              System.out.println("Trying method 3");
              JNIGetUserId lGUD = new JNIGetUserId();
              System.out.println(lGUD.getUser());
         catch (Exception e)
              System.out.println("Got an exception " + e);
              e.printStackTrace();
    /* DO NOT EDIT THIS FILE - it is machine generated */
    #include <jni.h>
    /* Header for class JNIGetUserId */
    #ifndef IncludedJNIGetUserId
    #define IncludedJNIGetUserId
    #ifdef __cplusplus
    extern "C" {
    #endif
    * Class: JNIGetUserId
    * Method: getUser
    * Signature: ()Ljava/lang/String;
    JNIEXPORT jstring JNICALL Java_com_localoptions_JNIGetUserId_getUser
    (JNIEnv *, jobject);
    #ifdef __cplusplus
    #endif
    #endif
    // Implements method to return a string to Java
    // C++ core header
    #include <iostream.h>
    // header from Java Interface
    #include "JNIGetUserId.h"
    #include "JNIGetUserId2.h"
    // returns a string back to Java for package structure
    JNIEXPORT jstring JNICALL Java_com_services_localoptions_JNIGetUserId_getUser
    ( JNIEnv * env, jobject thisObject )
         // set up constant user id for testing return
         char* userid = "RROWEHLP";
         // return userid to caller
         return env->NewStringUTF( userid );     
    // returns a string back to Java for flat structure
    JNIEXPORT jstring JNICALL Java_JNIGetUserId_getUser
    ( JNIEnv * env1, jobject thisObject1 )
         // set up constant user id for testing return
         char* userid1 = "RROWEHL1";
         // return userid to caller
         return env1->NewStringUTF( userid1 );     
    }

    Ok. A co-worker figured it out for me. The key thing is to do "javah com.services.localoptions.JNIGetUserId". Note the use of "." instead of "\". Running on windows, I was used to doing "\". That was part of the problem. Another key is doing the javah at the top of the package structure. This was mentioned in a post over at IBM.
    We got our JNI stuff working now. thanks, ray.

Maybe you are looking for