Subsitute drawImage by nativa drawing code

Hi,
I'm not quite sure this is the right forum to post my question. It's been a while since I visited these fora and there used to be a forum specifically for Java 2D topics, but I can't seem to find it. So I'll post it here and hope I guessed right.
I was wondering about some drawing issue I had some time ago. I made an application using a custom, rather complex, backgroundimage and it started up pretty slow because it needed to load and draw the image. And I was wondering if it would be faster and more memory-efficient if in stead of using the drawImage()-method one used 'native' drawing code. You could make a program that reads an image and, using the provided array of data, puts together a sequence of drawing instructions like drawPoint with specified color or drawLine with the correct color so that the image generated from this block of code is exactly the same as the image from the resourcefile. And so my question is if this would be preferable to using the drawImage-method, if it would be faster and more memory-efficient (seeing that the code to do this would probably be a lot smaller than the actual imagefile and you also wouldn't need a load-buffer)?
Thanks in advance,
Sam

Thanks for all your help so far.
However, having changed gameLoop to:
    public void gameLoop() {
        long startTime = System.currentTimeMillis();
        long currTime = startTime;
        while (isRunning) {
            long elapsedTime = System.currentTimeMillis() - currTime;
            currTime += elapsedTime;
            update(elapsedTime);
            screen.repaint();
            screen.update();
    }and paintComponent to:
    public void paintComponent(Graphics g){
     game.draw(getGraphics());
    }I now get a NullPointerException which traces back to GameCore.draw then Screen.paintComponent, then JComponent.paint, etc. (it's a long one, and i don't know how to copy it here from the command prompt). Why's that happening?
Thanks
Edit: you can actually continue playing after the nullpointerexception has reared its head - it doesn't affect anything, but the screen is now ALL flickering, whereas in the original problem the background image was fine, but the images that made up the tiles in the map were flickering. Now, everything in the JFrame flickers.
Edited by: Pulkse.co.uk on Jun 19, 2009 2:58 AM

Similar Messages

  • Function return value == -10. Native error code -2146824584 ADOBD.Recordset: Operation is not allowed when object is closed

    I want to call Stored Procedure that return records and output parameter, from CVI
    I can get output parrameter but when I want to get records stream I recieve following wrror:
    function return value == -10. Native error code -2146824584 ADOBD.Recordset: Operation is not allowed when object is closed

    in Stored procedure I create table variable and and insert into string values
    when I remove usage of table variable the error desappear

  • Compile a Java code to a native machine code

    Hi Everyone,
    What tool do I need to compile a Java code to a native machine code? Is there any free tool?
    Cecilia

    google.com is a good place to start

  • ConcurrentModificationException in drawing code

    Hi all,
    I'm getting a ConcurrentModificationException and I'm having a bit of a hard time figuring out how to prevent it - I can't even really understand why it happens yet.
    I'm running a simulation of moving bodies in some world, and am using a Swing Timer to fire drawing events. The events fired by the timer are handled by a class WorldView, which draws the world and in turn uses BodyView objects to draw the bodies in the world. The exception occurs in the following code:
    public class SimAgentBodyView extends AgentBodyView {
      @Override
      public void draw( Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setColor(Color.red);
        //cam is a simulated camera object mounted on the agent body               
        List<ISimBody> visBodies = cam.getVisibleObjects();
        for ( Body b : visBodies ) //Exception occurs in this loop
         g2d.draw(b.getFigure().getBounds2D());So apparently the visBodies list is being modified somewhere else while the drawing occurs. I don't really get this since I only use a single thread for the simulation which executes in the even-dispatching thread. The Timer runs in a separate thread but according to the API the event handler for the timer executes in the event-dispatching thread; i.e. both the simulation and the drawing mechanism are executing in the event-dispatching thread, so how can the simulation modify the list while the drawing happens?
    I'm rather short on time and the drawing is usually switched off to speed up the simulation anwyay, so even if it is not obvious what the problem is, is there a quick way to fix this? E.g. adding a synchronized block to the drawing code?
    Thanks
    Matt

    jverd wrote:
    CME is thrown on a best effort basis. There's no guarantee when it will be thrown, or even that it will be at all.I understand, thanks.
    Before you avoid the clear and simple solution for performance reasons, have you actually tested and found a performance problem with it?Good point, I haven't. But from profiling the app I know that during a standard run the list will be modified around 400 million times, and read (a loop through the entire list) about 200k - 800k times, depending on how long the run takes. From what I've read it seems that a concurrent collection will take significantly longer in this case. But you're right, maybe I should just try.
    I only posted a tiny bit of the code because at the time I did think that was the relevant bit, since I was under the impression that there was just a single thread accessing the list. The complete code follows, although again I'll take out parts that do not involve the list to make it clearer.
    public class LineCamera implements PhysicalSensor {
         public List<ISimBody> getVisibleObjects() {
              return visibleObjects;
         @Override
         public double[] getReading() {
              List<Body> objectsInRange = world.getIntersectingObjects(visionArea);
              visibleObjects.clear(); //<--- List is cleared here
              calcImage(objectsInRange);
              return image;
            public void calcImage( List<Body> objects ) {
              Set<BodyDistance> sortedObjs = sortObjectsByDistance(objects);
              for ( Path2D.Double slice : slices ) {
                   for ( BodyDistance obj : sortedObjs ) {
                        if ( slice.intersects(obj.bounds) ) {
                             visibleObjects.add(obj.body); //<--- List is modified here
                                            ...The code that reads the list is just the code that I posted earlier. The quick and dirty solution that I adopted now is just to clone the list in the code that does the drawing. Since the drawing is mainly for testing and seeing what's going on, speed is not so important there. Plus this avoids having to synchronize the modifications on the list; since this code is always executed (even when drawing is switched off), speed is of the essence. However it's quite nasty of course so if you know of anything better please let me know. Thanks!

  • Native error code -214721788​7 0x80040e21 Microsoft OLE DB Provider for ODBC Drivers: ODBC driver does not support the requested properties​.

    I configured MySQL in TestStand and making a query in TestStand like this:
    Command :=> "SELECT *  FROM crc_table ; " or  "SELECT CRC_Value  FROM crc_table ; " returns the total number of records without any errors.
    But when I add the "where" clause
    "SELECT crc_table.CRC_Value  FROM crc_table where crc_table.File_ID= Locals.File_ID and crc_table.Version_ID = Locals.Version_ID and crc_table.Link_ID = Locals.Link_ID; "
    I get the error as:
    Error, The following SQL command failed: 'SELECT crc_table.CRC_Value FROM crc_table where crc_table.File_ID= Locals.File_ID and crc_table.Version_ID = Locals.Version_ID and crc_table.Link_ID = Locals.Link_ID; ...' Native error code -2147217887 0x80040e21 Microsoft OLE DB Provider for ODBC Drivers: ODBC driver does not support the requested properties. [Error Code: -10, User-defined error code.]
    I tried the same syntax in MySQL Query Browser and got the correct result:
    SELECT crc_table.CRC_Value  FROM crc_table where crc_table.File_ID= "FID1" and crc_table.Version_ID = "VID1" and crc_table.Link_ID = "L1";
    I would appreciate your help.
    Thank you,
    Vidula

    Vidula,
    I am not completely sure if this is the cause of the error but it is something that will cause problems if it is not fixed.  In your SQL statement you must properly concatenate your strings with your variables.  In the statement you posted you were simply putting the variable names in the string, not actually pulling their values.  To do so properly your query should look something like this:
    "SELECT crc_table.CRC_Value  FROM crc_table where crc_table.File_ID='"+Locals.File_ID+"' and crc_table.Version_ID = '"+ Locals.Version_ID+"' and crc_table.Link_ID = '"+Locals.Link_ID+"' ;"
    This way we are using the values of the variables in conjunction with the text strings.  In this case the usage of single quotes (') casts the variables as strings so you may need to change this character sequence, but from the second example you gave I think that your variables are of type string so this should work fine.
    Message Edited by herosphro on 04-01-2008 03:52 PM
    John B.
    Applications Engineer
    National Instruments

  • Sun One & mySQL: Native Error Code: 2013

    This one's really starting to get me down. I've found many forums of programmers with the same problem, but no real solution in sight.
    The error only occurs periodically and when I refresh the page a few times it loads fine. Here's the code:
    Dim conn, rs, query
    set conn = createobject("ADODB.Connection")
    conn.open = "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=db_server; DATABASE=my_db; UID=user; PWD=pwd; OPTION=35;"
    query = "SELECT * FROM tblFranchise ORDER BY Franchise"
    set rs = conn.Execute( query )
    'display some data
    Call rs.Close()
    Call conn.Close()
    and here's that awful error message:
    Error Type:
    ADODB.Recordset.1 (0x80004005)
    SQLState: S1000 Native Error Code: 2013 [TCX][MyODBC]Lost connection to MySQL server during query
    /home.asp, line 127
    Any help much appreciated.

    Actually you can just forget about the OPTION setting, I was trying something else, but it's not present in the code that's giving me the error. I'm hosting the site with a third party, but I believe they're using Apache 1.3.26
    As for the Sun One version, I'm not sure, but I recieved the following message with the above error:
    HTTP 500.100 - Internal Server Error - ASP error
    Apache/1.3.26 (Unix) Sun-ONE-ASP/4.0.0 mod_gzip/1.3.26.1a mod_auth_pam/1.0a PHP/4.3.8 PHP/3.0.18 mod_ssl/2.8.10 OpenSSL/0.9.6g mod_perl/1.27 mod_jk/1.1.0 FrontPage/5.0.2.2510

  • EXCEPTION_ACCESS_VIOLATION in native zipping code on Class Load

    Afternoon gents:
    So I'm kind've excited by this since I'm an undergrad, and I'm hoping this is actually a bug, such that I've actually found a bug in the JVM!
    So, the scary message that showed up in standard error:
    # A fatal error has been detected by the Java Runtime Environment:
    #  EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000005ec13ae1, pid=328, tid=68
    # JRE version: 7.0_25-b17
    # Java VM: Java HotSpot(TM) 64-Bit Server VM (23.25-b01 mixed mode windows-amd64 compressed oops)
    # Problematic frame:
    # C  [zip.dll+0x3ae1]  Java_java_util_zip_ZipFile_getZipMessage+0x1749
    # Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
    # If you would like to submit a bug report, please visit:
    #   http://bugreport.sun.com/bugreport/crash.jsp
    # The crash happened outside the Java Virtual Machine in native code.
    # See problematic frame for where to report the b
    I've got 6 or 7 of those log files generated, I've uploaded the most recent one as a gist here:
    https://gist.github.com/Groostav/6446505
    I can reliably create this crash (though the stack frame would change slightly every time, though it is always caused either by OptimizerNode.run() or one of its spawned threads). Our application flow is one in which that you as a user navigate around our program through various dialogs and popups setting up variables and configuring our program for a run. When you hit the button to start the run, a huge chunk of memory is allocated, a bunch of threads are spawned and delegates are run. Our program consumes an order of magnitude more system resources, both in CPU time and in memory, when you hit our "run" button.
    Shortly after hitting the run button, you'd get our spinner, sometimes you'd get a peek at the processing PApplet doing some UI work, and then the program would hard-crash with the above message in std:err.
    the good news is that I've found at least a work around for our dev team, and possibly for your (reader who also has this error) production:
    increasing the default heap size (by passing -Xms128m to the JVM at runtime, --I believe the default is 64m) results in the program running just fine.
    This is a work-around for us, because we wrote this program with the expectation of being able to scale nicely from reasonably small problems (order 200 megs) up to huge problems (order dozens of gigs) of memory. We don't have the hardware or the problems in our development environment to test our code on multi-gig data sets, but I suspect it'll fail in the same way there, even with 128m or even up to 1024m as the default size. There is no realistic flow we can have the user go through to know ahead of time how big his data will balloon to when he hits the run button before we start the JVM. (ie, for us, this is not a production-ready workaround).
    This leads me to believe there's a bug in memory allocation code in and around the the class loaders.
    Thoughts? Can (or should) I post this to the Java Community Process page as a bug?
    cheers,
    -Geoff

    if don't know if this is the case but it is not a good idea to
    have a table open in Access and then insert a row into that table from
    a java application. this is really more of an Access and ODBC locking
    problem. i think you would have the same problem if you were inserting
    the row from a VB application using just ODBC.

  • 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?

  • JNI native drawing - Double Buffering issue

    Hi,
    I use JNI to paint from a C++ DLL onto a canvas, which works fine.
    The problem is that double buffering is not working though.
    In C++ I create an offscreen HDC, draw something on it and finally i bitblit the offscreen HDC to the parent window HDC.
    That is how double buffering is supposed to work. But each time i repaint my Canvas in Java, i see flickering:
    the background color is displayed first, then the C++ paintings are drawn.
    Since i already do double buffering in my C++ drawings, i don't know why there still is flickering.
    Should i do double buffering on my canvas also?
    How would this work, since my paint method looks like;
         private native void drawChart(Graphics g);
         public void paint(Graphics g)
              drawChart(g);
         }

    this is my lucky day :)
    the following thread on http://forum.java.sun.com/thread.jspa?threadID=562392&messageID=2767046 suggested to override the update method on the canvas, which works.
         // overridden to eliminate flicker
        public void update(Graphics g)
            paint(g);
        }

  • Native machine code

    Do anyone know of a decent native compiler that can complie
    my java source code into an exe , or is it possblie

    a search on java to exe returns almost 40,000 matches. it seems this question has been asked before....
    http://search.java.sun.com/search/java/index.jsp?col=javaforums&qp=%2Bforum%3A31&qt=java+to+exe&x=7&y=6

  • How to make TRACE work in native C++ code for a C# Univeral apps project

    I am playing the
    real-time communication sample project.  It works as expected but writing to the Output console does not work for the C++ code.  I have tried the TRACE macro,  and also tried the Trace() function of the project. Nothing is shown in
    the Output console. I am using the Debug configuration and running the app in the debug mode.
    Could anyone shed some light on this?
    Hong

    Thanks for the response.  Here is the Trace method of the project which uses OutputDebugString:
    void Trace(DWORD dwLevel, LPCWSTR pszFormat, ...)
    if (g_dwLogLevel > dwLevel)
    return;
    WCHAR szTextBuf[256];
    va_list args;
    va_start(args, pszFormat);
    StringCchVPrintf(szTextBuf, _countof(szTextBuf), pszFormat, args);
    OutputDebugString(szTextBuf);
    It does not work. It does not generate any error either.
    Hong

  • How to deal with Native Code?

    Is there any way to view or modify the source code of native code?

    Check jawt.h file in the include subdirectory of your JDK. It contains sample of native drawing to the canvas.

  • How to include 3rd party jar package in the native code aiming to generate ane for android

    in my native java code,i need to reference a class in another jar package.Simply to say,i want to make use of member functions of a class of some jar package A in the call function of the native class which have implemented the FREFunction class.To generate the native extension,native java code needs to be compiled to a jar package B.i have tried serveral methods to compile jar package A into B.Howerver my flex project failed to proceed when calling function of package A in the call function of native java code.To be sure of the correctness of the package A and B,i referenced them in a java project with main function and succeeded. at the same time my other call functions of classes impemented FREFunction work well,Then, why did i fail referencing package A?
    in the discussion http://forums.adobe.com/message/3965757, i found the same problem,but i was unable to get a workaround,can anybody give me same help?

    Standard Java does not support jars within other jars.
    Either re-architect your stuff so jars in jars is eliminated, or write a custom classloader that can load from them, or look into 3rd-party solutions, which you can find by searching the net and these forums.

  • Any bad side-effects to lengthy blocking in native code? (Win32,Linux,Solar

    1) Are there any negative side-effects to having one (or maybe a few) Java threads block for an extended period (e.g. hours) in native code? Naturally the thread would NOT be one of the "special" threads (such as the Swing event dispatcher, etc).
    2) Does the answer vary by platform? I'm interested in Win32, Linux and possibly Solaris (in that order).
    3) What if I scale the number of threads blocked in JNI code up to 100 threads. Does that change any of the answers? This is perhaps a silly number, I'm just trying to understand if more resources are consumed by blocking in the JNI as opposed to blocking in Java.
    4) Do modern JVM's use one native thread per Java thread? If so, then I would guess there is really nothing special about blocking in native code.
    Motivation for query -- In my application I need to interface with legacy C++ code that blocks (mostly on socket and i/o selects). I'm not thrilled about native code, but if there are no serious side-effects to extended blocking, it may be a viable approach.

    1) Are there any negative side-effects to having one
    (or maybe a few) Java threads block for an extended
    period (e.g. hours) in native code? Naturally the
    thread would NOT be one of the "special" threads (such
    as the Swing event dispatcher, etc).As far as I know the native code is loaded dynamic when a thread will use it.
    So if the thread 1 needs the code written in the native.dll the thread 1 will use
    the first instance of native.dll. So let's say this is blocked.
    Then after 2 hours another thread called thread2 calls the native.dll code. Then
    java ask the OS to create another instance of the native.dll and so on.
    So now there are 2 threads and 2 instances of the dll in the memory.
    All these apply to the Win32 OSs.
    >
    2) Does the answer vary by platform? I'm interested
    in Win32, Linux and possibly Solaris (in that order).
    3) What if I scale the number of threads blocked in
    JNI code up to 100 threads. Does that change any of
    the answers? This is perhaps a silly number, I'm just
    trying to understand if more resources are consumed by
    blocking in the JNI as opposed to blocking in Java.
    If your machine could suffer 100 pure java threads then it is not a problem to be some of them JNI ones.
    4) Do modern JVM's use one native thread per Java
    thread? Yes. Exactly as far as I know and experienced.
    If so, then I would guess there is really
    nothing special about blocking in native code.Exactly.
    >
    >
    Motivation for query -- In my application I need to
    interface with legacy C++ code that blocks (mostly on
    socket and i/o selects). I'm not thrilled about
    native code, but if there are no serious side-effects
    to extended blocking, it may be a viable approach.Yes it is. That is actually why Native methods are existing for.

  • GUI crashes when calling native code..

    Hi,
    I have interfaced to an existing C program using the Java Native Interface and I am controlling the C program using a GUI. The problem is that everytime I click on the button to call the native method, the GUI crashes... The bizarre thing is that the C code seems to actually execute properly and no exceptions are thrown..
    Anyone come across this problem?
    /john

    Hi,
    Thanks for the replies...
    The GUI completely disappears. No error file is generated. No exceptions are thrown. Here it is in more detail..
    The C code is invoked using the java native interface. The C code converts a MIDI file to a text file. It is normally run in DOS and accepts two parameters. You would run it in DOS normally as follows:
    mf2t Example1.mid Example1.txt.
    In the GUI I select the MIDI file and specify the output file (Example1.txt). I then pass these two parameters to the C code. The C code originally used argc and argv to accept the parameters. I replaced these with "fileArray" and "parameter"... "mf2t" replaces "main" in the native code...
    On the java side the code looks like this:
    static public native boolean mf2t(String s6, String s7);
    public String infile; // Input MIDI file
    public String textOut; // Output text file
    private void MIDIButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Object target=evt.getSource();
    if(target == MIDIButton) {
    if(mf2t(infile,textOut)){
    InfoLabel.setText("MIDI to text conversion complete");
    The code is built on the C side into a DLL using MS Visual Studio.
    On the C side the code looks something like this:
    static char *fileArray[5];
    static int argument=3;
    static char midiArray[25];
    static char txtArray[25];
    void mf2t(int argument,char * fileArray[]);
    // Entry point to native C code is here
    JNIEXPORT jboolean JNICALL
    Java_MainWindow_mf2t (JNIEnv *env, jobject j1, jstring midi, jstring txt)
    const jbyte *midiFile;
    const jbyte *txtFile;
    midiFile=(*env)->GetStringUTFChars(env,midi, NULL);
    txtFile=(*env)->GetStringUTFChars(env,txt, NULL);
    // The lines above just convert the java string into a C equivalent..
    strcpy(midiArray,midiFile);
    strcpy(txtArray,txtFile);
    fileArray[0]="mf2t.exe"; // Here I get fileArray to point to the converted strings
    fileArray[1]=midiArray;
    fileArray[2]=txtArray;
    mf2t(argument,fileArray); // Then I pass this to a native method
    (*env)->ReleaseStringUTFChars(env,midi, midiFile);
    (*env)->ReleaseStringUTFChars(env,txt, txtFile);
    return 1;
    void mf2t(int argument,char * fileArray[]){
    // native code in here
    I think it may have something to do with threads.. I'm not sure though.. It's impossible to know whats going on in the C code when the GUI crashes. If anything looks strange it's because I left out some code here for the sake of brevity... Still if you see anything that stands out let me know..
    Thanks,
    John

Maybe you are looking for

  • Need help on how to add a delimeter into a text file

    Actually, this program reads a textfile. After reading, i need to put certain delimeters after certain characters and print them out to a new file. this is how it works : for example... 471117-01-5179052004 VENUE SECURITIES SDN. BHD. This is wat the

  • Issue in setup of Streams (DBMS_STREAMS_ADM.MAINTAIN_CHANGE_TABLE) to replicate data changes in table

    Hi Team, i am facig an issue in setting up of change replications in emp table. My requirement is made generic and is as below : desc scott.emp Name     Null Type         EMPNO         NUMBER(4)    ENAME         VARCHAR2(10) JOB           VARCHAR2(9)

  • WL 7.0 SP3 - No BEA HOME directories found.

    I am trying to install sp3 on wl7.0 on solaris 8 sparc. The environment is set but can anyone enlighten me why it cannot find any BEA home directories even after BEAHOME, WL_HOME,...... are all set ? Attached is the log. Thank you. regards, arjun [sp

  • Can someone clarify all these keys for me, please?

    I'm new to Macs and have tried experimenting with the fn, ctrl, atl/option, and command/apple keys and am all confused about which one does what. From what I've read (and learned on my own), the command key seems to function like the CTRL key on a PC

  • Dropdown data from WebDynpro Java

    Hi Experts, Is it possible to dynamically populate dropdown items from the Java WebDynpro context which are in turn populated using an aRFC from SAP R/3? If so, how do i go about in doing this? Cheers, Alfonso