Applet - Thread - Vector problem.

Hi! I've an applet that loads some files in a Vector. Every time that I load the applet, I assign a random generated number to name the files in the vector. For example:
random = 7.1923E928
so the files will be
7.1923E928-1.txt
7.1923E928-2.txt
The method that creates the files and loads its routes in a vector, is a threaded method.
Then, I save all the files into a zip file. This is done perfectly the first time that I load the applet. When I load for a second time the applet, a new random number is generated ok, and the files are created with it. But, when I try to make the zip file, the vector has the past files, I mean, the vector has the routes of the previous applet. I don't know what is going on, don't know if maybe is some trouble with the Thread. Maybe it never finishes ... don't know.
I have other Threads in the applet (around 5 threads) for thoing other things, I belive they do not affect, but post it here just in case.
Regards,
Raul

As a (future) programmer the first thing you should learn is never just say "it doesn't work"
That's what first line support is for to get info out of "dumb" users who don't know better.
I suggested some code changes but you haven't re posted any code.
You think it might be the applet but I don't see any exception nor a trace from the applet.
To turn the full trace on (windows) you can start the java console, to be found here:
C:\Program Files\Java\j2re1.4...\bin\jpicpl32.exe
In the advanced tab you can fill in something for runtime parameters fill in this:
-Djavaplugin.trace=true -Djavaplugin.trace.option=basic|net|security|ext|liveconnect
if you cannot start the java console check here:
C:\Documents and Settings\userName\Application Data\Sun\Java\Deployment\deployment.properties
I think for linux this is somewhere in youruserdir/java (hidden directory)
add or change the following line:
javaplugin.jre.params=-Djavaplugin.trace\=true -Djavaplugin.trace.option\=basic|net|security|ext|liveconnect
for 1.5:
deployment.javapi.jre.1.5.0.args=-Djavaplugin.trace\=true -Djavaplugin.trace.option\=basic|net|security|ext|liveconnect
The trace is here:
C:\Documents and Settings\your user\Application Data\Sun\Java\Deployment\log\plugin...log
I think for linux this is somewhere in youruserdir/java (hidden directory)

Similar Messages

  • Vector problem... Please help!

    Hi,
    I searched the forum but I could not get a correct answer for a vector problem I am facing. I have 2 SQL queries that are nested. Initially I tried to nest them but realized that when I close the connection to one query I cannot nest the other since the first query is closed ( blazix web server does not let you open open a wuery if you have not closed one query) Somebody had suggested to include the infor on a Vector and then reuse it. However I am not sure of how to do this.
    The following is what I have so far.
    <%@ page import="java.util.Vector" %>
    <%
    <blx:sqlQuery id="Buttons">
    Select      ID, Ntive, ButtonLabel ButtonLink
    From Pages
    </blx:sqlQuery>
    <% } else { %>
    <blx:sqlQuery id="Project">
    Select      ID, ProjectName, PLongName
    From Projects
    </blx:sqlQuery>
    <% } %>
    // now both of these queries are nested within each other to get the output.
    <blx:sqlExecuteQuery resultSet="rs" queryRef="Buttons">
    <%
    int ID = rs.getInt("ID");
    int Ntive = rs.getInt("Ntive");
    String ButtonLabel=rs.getString("ButtonLabel");
    String ButtonLink=rs.getString("ButtonLink");
    %>
    <% if (ID != 1){
    if (Ntive ==1) {
         Link="index.jsp?Page="+ID;
         } else {
         Link= ButtonLink;
    %>
    <LI><a href="<%=Link%">> <%=ButtonLabel%></a></LI>     
    <% if (ID==2) {%>
    // then I start the second query projects.
    <blx:sqlExecuteQuery resultSet="rs" queryRef="Project">
    </blx:sqlExecuteQuery>
    <% if (ID==3) %>// this is again from the first query
    // here i start the second query again
    //now I close the first query.
    Please help me to write a Vector withnin here and to retrieve the information to be used again on the same JSP page.
    Thanks!

    I wonder why Blazix dosnt allow multiple queries.
    Here is the logic using Vectors.
    <%@ page import="java.util.Vector" %>
    Vector IDVector = new Vector();
    Vector NtiveVector = new Vector();
    Vector ButtonLabelVector = new Vector();
    Vector ButtonLinkVector = new Vector();
    if(whatever is the codition here)
         %>
         <blx:sqlQuery id="Buttons">
              Select ID, Ntive, ButtonLabel, ButtonLink
              From Pages
         </blx:sqlQuery>
         <%
    else
         %>
         <blx:sqlQuery id="Project">
         Select ID, ProjectName, PLongName
         From Projects
         </blx:sqlQuery>
         <%
    %>
    <blx:sqlExecuteQuery resultSet="rs" queryRef="Buttons">
    <%
         IDVector.add(rs.getInt("ID"));
         NtiveVector.add(rs.getInt("Ntive"));
         ButtonLabelVector.add(rs.getString("ButtonLabel"));
         ButtonLinkVector.add(rs.getString("ButtonLink"));
    %>
    //now I close the first query.
    </blx:sqlQuery>
    <%
    for(rec=0;rec<IDVector.size();rec++)
         int ID = (int) IDVector.elementAt(rec);
         int Ntive = (int) NtiveVector.elementAt(rec);
         String ButtonLabel = (String) ButtonLabelVector.elementAt(rec);
         String ButtonLink = (String) ButtonLinkVector.elementAt(rec);
         if (ID != 1)
              if (Ntive ==1)
                   Link="index.jsp?Page="+ID;
              else
                   Link= ButtonLink;
              %>
              <LI><a href="<%=Link%">> <%=ButtonLabel%></a></LI>
              <%
              if (ID==2)
                   %>
                   // then I start the second query projects.
                   <blx:sqlExecuteQuery resultSet="rs" queryRef="Project">
                   </blx:sqlExecuteQuery>
                   <%
              if (ID==3)
                   %>
                   // this is again from the first query
                   // here i start the second query again
                   <%
    %>
    Hope it helps.
    -Mak

  • Applet thread problem

    Hi,
    I have an applet. That connecting to server by using ULRconnection. This applet has two thread that connect two server at different times. One off them send message to server periodicly (this message contains that Applet is open and working). My problem is :
    if I go another page then turn back at same browser , my browser is frozen . I cant make anything. Whats the problem ? Have you any idea ?

    Hi,
    I have an applet. That connecting to server by using ULRconnection. This applet has two thread that connect two server at different times. One off them send message to server periodicly (this message contains that Applet is open and working). My problem is :
    if I go another page then turn back at same browser , my browser is frozen . I cant make anything. Whats the problem ? Have you any idea ?

  • 64-bit JNI C++ to JAVA invocation multiple threads classloader problem

    Hi ALL,
    I have a C++ app that invokes Java classes on 64-bit Solaris 10 with 64-bit JVM.
    Here is the problem:
    The native non-main (not the thread that initializes the JVM) threads would not be able to find any user-define class.
    Here are the symptoms and observations:
    1. JNIEnv::ExceptionDescribe() showed the following StackOverflowError:
    Exception in thread "Thread-0" java.lang.StackOverflowError
            at java.util.Arrays.copyOf(Arrays.java:2734)
            at java.util.Vector.ensureCapacityHelper(Vector.java:226)
            at java.util.Vector.addElement(Vector.java:573)
            at java.lang.ClassLoader.addClass(ClassLoader.java:173)
            at java.lang.ClassLoader.defineClass1(Native Method)
            at java.lang.ClassLoader.defineClass(ClassLoader.java:621)
            at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
            at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
            at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
            at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
            at java.security.AccessController.doPrivileged(Native Method)
            at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
            at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
            at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)2. The "main thread" that instantiates the JVM has no problem finding and loading any class or method
    3. But the other threads (non-main threads) would not be able to find the user-defined classes unless the classes were already loaded by the main thread.
    4. The non-main threads can find the "standard" java classes with no problem
    5. The same app ran fine on 32-bit system.
    6. Except for the JVM reference is global, each thread acquired JNIEnv by either GetEnv() or AttachCurrentThread().
    Any idea why it is a problem with 64-bit?
    I have the sample program to reproduce this issue in this thread: http://forums.sun.com/thread.jspa?messageID=10885363&#10885363. That was the original thread I raised but I have narrowed it down to a more concrete scenario. That's why I am creating this new thread. I hope this does not break any rule on this forum. If it does, I apologize.
    I really appreciate it if anyone can provide any help/suggestion.
    Regards,
    - Triet

    Here is the sample program. Again, this works on 32-bit but not 64-bit.
    #include <string>
    #include "jni.h"
    #include "TestThread.h"
    static JavaVM *g_pjvm = NULL;  /* denotes a Java VM */
    static JNIEnv *g_penv = NULL;  /* pointer to native method interface */
    void initJVM(char** jvmOptions) {
        printf("RJniTest init starts...\n");
        JavaVMInitArgs vm_args; /* JDK/JRE 6 VM initialization arguments */
        JavaVMOption* poptions;
        int optionLen = 0;
        while (jvmOptions[optionLen]) {
            optionLen++;
        printf("RJniTest::init len=%d\n", optionLen);
        if (optionLen > 0) {
            printf("RJniWrapper::init jvmOptions\n");
            poptions = new JavaVMOption[optionLen];
            //poptions[0].optionString = "-Djava.class.path=/usr/lib/java";
            int idx = 0;
            while (jvmOptions[idx]) {
                poptions[idx].optionString = jvmOptions[idx];
                idx++;
        printf("RJniTest::init vm_args: version(%x), nOptions(%d)\n",
                JNI_VERSION_1_6, optionLen);
        vm_args.version = JNI_VERSION_1_6;
        vm_args.nOptions = optionLen;
        vm_args.options = poptions;
        vm_args.ignoreUnrecognized = JNI_FALSE;
        // load and initialize a Java VM, return a JNI interface
        // pointer in env
        printf("RJniTest::init creates JVM\n");
        JNI_CreateJavaVM(&g_pjvm, (void**)&g_penv, &vm_args);
        printf("RJniTest init ends\n");
    void findClass(const char* classname) {
        static const char* fname = "justFindClasses";
        printf("%s: findClass: %s\n", fname, classname);
        JNIEnv* jenv;
        jint ret = g_pjvm->GetEnv((void**)&jenv, JNI_VERSION_1_6);
        if (ret == JNI_EDETACHED) {
            ret = g_pjvm->AttachCurrentThread((void**)&jenv, NULL);
            if (ret != JNI_OK || jenv == NULL) {
                printf("%s: get env error: ret=%d\n", ret, fname);
            } else {
                printf("%s: got new env\n", fname);
        } else if (ret == JNI_OK) {
            printf("%s: env already there\n");
        jclass classref;
        classref = jenv->FindClass(classname);
        if (classref == NULL) {
            printf("%s: %s class not found!\n", fname, classname);
            if (jenv->ExceptionOccurred()) {
                jenv->ExceptionDescribe();
                jenv->ExceptionClear();
        printf("%s: found class: %s\n", fname, classname);
    class RJniTestThread : public TestThread {
    public:
        void threadmain();
    void RJniTestThread::threadmain() {
        printf("RJniTestThread::threadmain: Starting testing\n");
        findClass("org/apache/commons/logging/Log");
        findClass("java/util/List");
        printf("RJniTestThread::threadmain: done.\n");
    int main(int argc, char** argv) {
        char **jvmOptions = NULL;
        printf("RJniTestDriver starts...\n");
        if (argc > 1) {
            jvmOptions = new char*[argc];
            for (int i = 0; i < argc ; i ++) {
                jvmOptions[i] = argv[i + 1];
            jvmOptions[argc - 1] = NULL;
        } else {
            int size = 8;
            int i = 0;
            jvmOptions = new char*[size];
            jvmOptions[i++] = (char*) "-Djava.class.path=<list of jar files and path here>";
            jvmOptions[i++] = (char*) "-Djava.library.path=/sandbox/mxdev/3rdparty/java/unix/jdk1.6.0_14/jre/lib/sparc";
            jvmOptions[i++] = (char*) "-Djava.compiler=NONE";
            jvmOptions[i++] = (char*) "-verbose:jni";
            jvmOptions[i++] = (char*) "-Xcheck:jni";
            jvmOptions[i++] = NULL;
        printf("init JVM\n");
        initJVM(jvmOptions);
        // UNCOMMENT HERE
        // findClass("org/apache/commons/logging/Log");
        // findClass("java/util/List");
        // UNCOMMENT END
        printf("start test thread\n");
        RJniTestThread testThread;
        ThreadId tid = testThread.launch();
        printf("wait for test thread\n");
        int ret = pthread_join(tid, NULL);
        printf("RJniTestDriver ends\n");
    }

  • I have a basic applet method timing problem with Firefox (and Chrome), not IE nor Opera. Works if JavaScript issues windows.alert() prior, fails otherwise.

    I have an applet method, which is invoked from a JavaScript function, that is triggered by the window.onload event. The problem seems to center in the loading of the applet and its methods.
    If I step through the 3 applet acceptance prompts (I chose to use a down-level Java), the applet method is never invoked, nor is an exception raised. How this happens is beyond my understanding.
    As additional information, the Init(), start(), and "desired" Java methods all use the synchronized keyword. This is an attempt to minimize the exposure to a multi-thread environment.
    If I issue a message from JavaScript (via window.alert()) PRIOR to invoking the method, I can get the desired results in special circumstances:
    1) When the alert is presented, Firefox also prompts, SIMULTANEOUSLY, to block/continue the applet (the first of the 3 applet acceptance prompts). I can accept that these are separate threads.
    2a) If I walk through the 3 applet acceptance prompts FIRST, and then hit the OK button on the alert message SECOND, I get the desired results, my applet method executes, and all is well (other than the fact that I would prefer not to have the alert in place at all).
    2b) If I hit the OK button on the alert message FIRST, and then walk through the 3 applet acceptance prompts SECOND, I get the same results as when the page loads WITHOUT the alert, which is the applet method is never invoked, nor is an exception raised. Weird, huh?
    The above problem only occurs when the browser and the applet's URL are loaded for the first time.
    Subsequent invocations (after the page & applet has been loaded initially) do not have the failing symptoms.
    It is my understanding that IE and Firefox (and Chrome and Opera, for that matter) each use the same implementation of JavaScript provided by Microsoft. Please correct me if this information is inaccurate.
    The failing page and it's applet are proprietary; I cannot provide the Internet URL, nor the Java or JavaScript source, to aid in your analysis.

    I can speak to the source code, but have no access to it.
    The current process/thread that invokes an applet method must check to see that the applet is not currently being loaded by another process/thread. If it is being loaded, the current process/thread should block until the load is complete, THEN attempt to invoke the applet method.
    Please forward my concern to a knowledgable developer. The nature of the problem, once identified, can be addressed in a very straightforward manner.

  • Applet-Servlet Communication problem EOFException

    Hi! i´ve been searching and searching through forums because it seems this problem is very common, but none of the solutions i´ve seen so far suits me, so i´m here looking for some help because i´ve been stuck one week with this. First of all sorry if my english isn´t the best... i´m a bit rusty...
    Well, i had some code that worked perfectly, but i needed to perform some changes because i needed the servlet to send more info to the applet, and here started the problems, when i made the changes it started to throw EOFException when i was trying to read the InputStream, and furthermore when i came back to the original code it started to throw the exception in the same place too
    So here i am... don´t know what to do now and i entrust to you to give me some tips.
    Here comes some code. This is the original code, the one that runned but it doesn´t run right now
    Applet:
    public ListasComponentesSeleccionables cargarListasComponentes( ) throws IOException, ClassNotFoundException {
              String serv = "/Desaladora/cargarListasComponentesApplet.do";
              String host = Principal.documentBase.getHost( );
              URL direccion = new URL( "http", host, 8080, serv );
              // Create conection
              URLConnection connection = direccion.openConnection( );
              connection.setDoInput( true ); 
              connection.setDoOutput( true );
              connection.setUseCaches( false );
              connection.setRequestProperty( "Content-Type", "application/x-java-serialized-object" );
              ObjectOutputStream output;
              output = new ObjectOutputStream( connection.getOutputStream( ) );
              output.writeObject( new Boolean(true) );
              output.flush( );
              output.close( );
              ObjectInputStream input = new ObjectInputStream( connection.getInputStream( ) ); //<-- Here is the problem
              ListasComponentesSeleccionables response = new ListasComponentesSeleccionables( );
              response = ( ListasComponentesSeleccionables ) input.readObject( );
              return response;
         }Servlet:
    ublic class CargarListasComponentesAppletAction extends Action {
    public ActionForward execute(     ActionMapping mapping,
                                                     ActionForm form,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response )
                            throws ServletException, IOException, Exception  {
              InitialContext context = new InitialContext();
              SensorManagerService sensor_service;
              ActuatorManagerService actuator_service;
              Globals.LOGGER_SECURITY.debug( "Entering ACTION 'CargarListasComponentesAppletAction'" );
              response.setContentType("application/x-java-serialized-object");
              try
                   ObjectInputStream bufferentrada = new ObjectInputStream(request.getInputStream());
                   Boolean peticionOK = (Boolean)bufferentrada.readObject();
                   ObjectOutputStream buffersalida = new ObjectOutputStream(response.getOutputStream());
                   sensor_service = ( SensorManagerService ) context.lookup( "desaladora/SensorManagerServiceBean/local" );
                   ArrayList<AlarmConnectedSensorDTO> sensorList = sensor_service.findAllSensorsToAlarms();
                   actuator_service = ( ActuatorManagerService ) context.lookup( "desaladora/ActuatorManagerServiceBean/local" );
                   ArrayList<AlarmConnectedActuatorDTO> actuatorList = actuator_service.findAllActuatorsToAlarms();
                   buffersalida.writeObject( crearListasSeleccionables(sensorList, actuatorList) );
                   buffersalida.flush();
              catch(Exception e)
                   System.out.println("Error en la trasmision de datos");
              return null;
         private ListasComponentesSeleccionables crearListasSeleccionables(ArrayList<AlarmConnectedSensorDTO> sensorList,
                    ArrayList<AlarmConnectedActuatorDTO> actuatorList) {
              Vector<Integer> vectorSensores = new Vector<Integer>();
              Vector<Integer> vectorActuadores = new Vector<Integer>();
              for(AlarmConnectedSensorDTO sensor : sensorList) {
                   vectorSensores.add(sensor.getIdSensor( ));
              for(AlarmConnectedActuatorDTO actuator : actuatorList) {
                   vectorActuadores.add(actuator.getIdActuator( ));
              ListasComponentesSeleccionables listasComponentesSeleccionables =
                                  new ListasComponentesSeleccionables(vectorSensores, vectorActuadores);
              return listasComponentesSeleccionables;
    }i´ve been running some test in another computer, and this code simply works, but it doesn´t work in the machine i usually work.
    Maybe someway the stream get corrupt? the info i´ve been trying to send and started throwing the exception may still be in the stream? I don´t know what to think right now.
    Hope someone has any idea, thankyou.

    I dont see the problem. However, I suggest you change this;
    System.out.println("Error en la trasmision de datos"); t
    to e.printStackTrace() to see what it is doing when it stops working.
    I also suggest peppering your code with System.out.println() statements to see what it is doing just before stopping.
    Also, try your code with a brand new file with only a few characters in it. If it works, add to it some of your originial file content until it stops working. This way, you can determine if its the file size that is causing the crash or something in the file content. If all else fails, study java I/O and try some other way to read/write the file. You can also try a different browser. If it works, its the browser. Still having problems? Create a new project with a simple applet and file read/write program and get that working. That way, all the other stuff in your original project isn't in the way.

  • Thread concurrency problem - how to know when thread is dead?

    My applet uses a thread to draw an iteration graph step by step.
    The user as the option of pressing two buttons:
    - PLAY button - iteration Points are stored in an arrayList and drawn step by step (a sleeping time follows each step) (drawIterations thread)
    - TO_END button - iteration Points are all stored in the arrayList (swingworker thread) and after all of them have been stored the graph is drawn instantly.
    I have problems in this situation:
    When executing the PLAY-button thread, if the user presses TO_END button, the remaining graph lines should draw instantly. Sometimes I get more points on the graph than I should. It seems that the PLAY thread, which I stop when TO_END buton is pressed, still remains storing new points into the arrayList concurrently to the new thread created after TO_END button was pressed .
    Any ideas?
    I'm already using synchronization.
    private volatile Thread drawIterations;
    public void playButtonClick(JToggleButton btn) {
         pointSet1 = new ArrayList<Point2D.Double>();
         if (drawIterations == null) drawIterations = new Thread(this,   "drawIterations");
         drawIterations.start();
    public void toEndButtonClick(JToggleButton btn) {
         stopThread() ;
         pointSet1 = new ArrayList<Point2D.Double>();
         computeIterationGraphPointsAndRefreshGraph();
    public synchronized void stopThread() {
         drawIterations = null;
         notify();
    private void computeIterationGraphPointsAndRefreshGraphs() {
         SwingWorker worker = new SwingWorker() {
              public Object construct() {
                   // compute all iteration points
                         //repaint graph
         worker.start();
    }Is there a way of testing if a thread is actually dead after setting the thread object to null??

    In general, a Thread keeps running until it's run
    method completes. Threads don't stop when their
    handle is set to null. Your run method should
    constantly be checking on a variable to know when to
    stop running and exit the run method. In this case,
    you could check on the drawIterations variable to see
    if it's null.<br>
    <br>Even using the following line on my run method I get the the same problem:
    <br>
    <br>while (myThread == drawIterations && drawIterations!=null && halfStep < 2 * totalIterations) {
    <br>...
    <br>
    <br>Here's the whole method:
    <br>(actually there are 2 graphs being drawn and the second is only refreshed every 2 steps:)
    <br>
    <br>     <br>public void run() {
         <br>  Thread myThread = Thread.currentThread();
         <br>  int totalIterations = transientIterations +iterationsToDraw ;
              <br>  while (myThread == drawIterations && drawIterations!=null && halfStep < 2 * totalIterations) {
              <br>     computeNextHalfIterationGraphPoint( );
              <br>      if (!TRANSIENT_IS_ENABLED || halfStep >= 2*transientIterations ) {// is     not in transient calculations
              <br>                       graphArea1.repaint();
              <br>                       if (halfStep%2 ==0 ) graphArea2.repaint();
              <br>                       if (halfStep < 2*totalIterations){//no need to execute the following block if at last iteration point
                   <br>                         if (lastIterationPointsFallOutsideGraphArea(toEndCPButtonActive)) break;
                        <br>          try {
                             <br>                      Thread.sleep(sleepingTimeBetweenHalfIterationRendering);
                             <br>                      if (threadInterrupted ){//if clause included to avoid stepping into a synchronized block if unnecessary
                                  <br>                        synchronized (this) {
                                       <br>                          while (threadInterrupted && myThread==drawIterations ) wait();
                                                      <br>    }
    <br>                                               }
         <br>                                   } catch (InterruptedException e) {
              <br>                                     break;
                   <br>                         }     
                        <br>               }
    <br>                            }
         <br>        stopThread();
         <br>     }
    <br>

  • Swing Applet in JSP: problem with fetching data from database

    i am facing a problem while fetching data from database using Swing Applet plugged in a JSP page.
    // necessary import statements
    public class NewJApplet extends javax.swing.JApplet {
    private JLabel jlblNewTitle;
    private Vector vec;
    public static void main(String[] args) {
    JFrame frame = new JFrame();
    NewJApplet inst = new NewJApplet();
    frame.getContentPane().add(inst);
    ((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
    frame.pack();
    frame.setVisible(true);
    public NewJApplet() {
    super();
    initGUI();
    private void initGUI() {
    try {
    this.setSize(542, 701);
    this.getContentPane().setLayout(null);
    jlblTitle = new JLabel();
    this.getContentPane().add(jlblTitle);
    jlblTitle.setText("TITLE");
    jlblTitle.setBounds(197, 16, 117, 30);
    jlblTitle.setFont(new java.awt.Font("Dialog",1,20));
    jlblNewTitle = new JLabel();
    this.getContentPane().add(jlblNewTitle);
    Vector vecTemp = getDBDatum(); // data fetched fm DB r stored here.
    jlblNewTitle.setText(vecTemp.get(1).toString());
    jlblNewTitle.setBounds(350, 16, 117, 30);
    jlblNewTitle.setFont(new java.awt.Font("Dialog",1,20));
    } catch (Exception e) {
    e.printStackTrace();
    }//end of initGUI()
    private Vector getDBDatum() {
    // fetches datum from oracle database and stores it in a vector
    return lvecData;
    }//end of getDBDatum()
    }//end of class
    in index.jsp page i have included the following code for calling this applet:
    <jsp:plugin type="applet" code="NewJApplet.class" codebase="applets"
    width="600" height="300">
    <jsp:fallback>Could not load applet...</jsp:fallback>
    </jsp:plugin>
    if i view it in using AppletViewer it runs perfectly and display the data in JLabel. (ie, both jlblTitle and jlblNewTitle).(ie, DATA FETCHES FROM db AND DISPLAYS PROPERLY)
    BUT IF I CLICK ON INDEX.JSP, ONLY jlblTitle APPEARS. jlblnNewTitle WILL BE BLANK(this label name is supposed to fetch from database)
    EVERY THING IS DISPAYING PROPERLY EXCEPT DATA FROM DATABASE!!!
    i signed the applet as follows :
    grant {
    permission java.security.AllPermission;
    Can any body help me to figure out the problem?

    This is the Swing Applet java code
    import java.awt.Dimension;
    import java.sql.Connection;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.JScrollPane;
    import javax.swing.JApplet;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTree;
    import javax.swing.ScrollPaneConstants;
    import javax.swing.SwingConstants;
    public class HaiApplet extends javax.swing.JApplet {
         private JLabel     jlblTitle;
         private JLabel     jlblNewTitle;
         private Vector     vec;
         * main method to display this
         * JApplet inside a new JFrame.
         public static void main(String[] args) {
              JFrame frame = new JFrame();
              NewJApplet inst = new NewJApplet();
              frame.getContentPane().add(inst);
              ((JComponent)frame.getContentPane()).setPreferredSize(inst.getSize());
              frame.pack();
              frame.setVisible(true);
         public HaiApplet() {
              super();
              initGUI();
         private void initGUI() {
              try {               
                   this.setSize(542, 701);
                   this.getContentPane().setLayout(null);
                        jlblTitle = new JLabel();
                        this.getContentPane().add(jlblTitle);
                        jlblTitle.setText("OMMS");
                        jlblTitle.setBounds(197, 16, 117, 30);
                        jlblTitle.setFont(new java.awt.Font("Dialog",1,20));
                        jlblTitle.setHorizontalAlignment(SwingConstants.CENTER);
                        jlblTitle.setForeground(new java.awt.Color(0,128,192));
                        jlblNewTitle = new JLabel();
                        this.getContentPane().add(jlblNewTitle);
                        Vector vecTemp = getDBDatum();
                        jlblNewTitle.setText(vecTemp.get(1).toString());
                        jlblNewTitle.setBounds(350, 16, 117, 30);
                        jlblNewTitle.setFont(new java.awt.Font("Dialog",1,20));     
              } catch (Exception e) {
                   e.printStackTrace();
         }//end of initGUI()
         private Vector getDBDatum() {
              Vector lvecData = new Vector(10,5);
              Connection lcon = null;
              Statement lstmt = null;
              ResultSet lrsResults = null;
              String lstrSQL = null;
              String lstrOut = null;
              try {
                   OmmsDBConnect db = new OmmsDBConnect();
                   lcon = db.connectDb();
                   lstmt = lcon.createStatement(lrsResults.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
                   lstrSQL = "select DT_ID from P_DATATABLES";
                   lrsResults = lstmt.executeQuery(lstrSQL);        
                   int i = 0;
                   lrsResults.last();
                   int length = lrsResults.getRow();
                   System.out.println(length);
                   lrsResults.beforeFirst();
                   int recCount = 0;
                   while (lrsResults.next()) {
                        recCount++;
                        lvecData.addElement(new String(lrsResults.getString("DT_ID")));
                   //     System.out.println("ID :  " + lrsResults.getString(1));
                        i++;
                   }System.out.println("here 3 out fm while");
              catch(SQLException e) {
                   System.out.print("SQLException: ");
                   System.out.println(e.getMessage());
              catch(Exception ex) {
                   lstrOut = "Exception Occured " + ex.getMessage();
              finally {
                   try {
                        lrsResults.close();
                        lstmt.close();
                        lcon.close();
                        System.out.println("[DONE]");
                   catch(Exception e) {
                        System.out.println(e);
             }//end of finally
              return lvecData;
         }//end of getDBDatum()
    }//end of classOfcourse the above code compiles and runs well. in Applet Viewer
    I plugged the above Swing Applet in a JSP page index.jsp
    <jsp:plugin type="applet" code="NewJApplet.class" codebase="applets"
                   width="600" height="300">
         <jsp:fallback>Could not load applet...</jsp:fallback>
    </jsp:plugin>Every thing is working fine in AppletViewer...But if i view this in any browser, then only the jlblTitle is displaying. jlblNewTitle is not displaying(this label name is actually fetching from thedatabase)
    can any body help me regarding this matter.? Thx in Advance.

  • Nested vectors problem

    Hi,
    I'm having a bit of a problem trying to create a vector within a vector. I am parsing a string and adding the elements to a vector. Then after I've done this I want to add the newly populated vector to another vector, then clear the original vector and start again. Thus adding "rows" and "columns" to create a 2D array as a vector.
    However, my problem comes when I try to clear the first vector after I've added it's contents to the containing vector. When I call the clear(); function it does clear the vector, but it also clears it from containing vector I've just added it to! Surely this can't be right? What's the way around this?
    String rows = "";
    Vector vCols = new Vector();
    Vector vRows = new Vector(vCols);
    // Split on rows
    StringTokenizer stRows = new StringTokenizer(rows, "][");
    //while rows remaining, put contents in vector
    while (stRows.hasMoreTokens()) {
    //split on ']['
    //clearing this also remove the contents already put into vRows !!
    vCols.clear();
    rows = stRows.nextToken(); // contains A row!
    StringTokenizer stCols = new StringTokenizer(rows, ",");
              //now parse the columns
    while (stCols.hasMoreTokens()) {
    String d = stCols.nextToken();
    vCols.addElement(d);
    vRows.addElement(vCols);
    TIA
    ~PAul Phillips

    Use [code ] tags when pasting code to make the code readable. Click on the "Formatting Help" link before you post your next thread for more information.
    You can't just 'clear' a Vector and and more data to it you need to create a new Vector for every row. This thread shows a similiar example on creating a Vector of Vectors from a ResultSet from an SQL query:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=497641

  • Applet / Application Sound problem

    Hey everyone,
    I'm programming a game named None Left, and the main file (NoneLeft.java) contains a constructor :
    public class NoneLeft extends javax.swing.JApplet implements Runnable, ContextListenerIt also contains a main method:
        public static void main(String s[]) {
            JFrame f = new JFrame("NoneLeft");
            f.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {System.exit(0);}
            JApplet applet = new NoneLeft();
            f.getContentPane().add("Center", applet);
            applet.init()        f.pack();
            f.setSize(new Dimension(800,600));
            f.setVisible(true);
    AudioClip music;
    music = applet.getAudioClip(new URL("file:///K:/BinaryFinary2.wav"));
    music.loop();The problem is that whenever I try to use the applet's method getAudioClip,
    i get the following error:
    Exception in thread "main" java.lang.NullPointerException
            at java.applet.Applet.getAppletContext(Applet.java:187)
            at java.applet.Applet.getAudioClip(Applet.java:295)
            at noneleft.NoneLeft.main(NoneLeft.java:865)The code at line 865 is:
    music = applet.getAudioClip(new URL("file:///K:/BinaryFinary2.wav"));
    music.loop();The NullPointerException is really what has me puzzled. The applet is there: It's created in the public static void main method, but it just won't work. Anyone have a clue about why that is?
    I have a feeling it's because of the Applet inheritance and the application; it's not sure which one is which...or maybe not.
    Thanks so much!
    Edited by: simpavid on May 27, 2008 4:11 PM

    Thank you so much for your help so far;
    However, I still haven't gotten this to work.
    I now have the code:
    JFrame f = new JFrame("NoneLeft");
    JApplet applet = new NoneLeft();
    f.getContentPane().add("Center", applet);
    applet.init();
    f.pack();
    f.setSize(new Dimension(800,600));
    f.setVisible(true);
    AudioClip music = applet.getAudioClip(applet.getCodeBase(), "BinaryFinary.wav");
    music.loop();but my error still exists:
    Exception in thread "main" java.lang.NullPointerException
            at java.applet.Applet.getCodeBase(Applet.java:152)
            at noneleft.NoneLeft.main(NoneLeft.java:861)The strange part is that getAudioClip no longer gives me a null pointer but getCodeBase() does. I also tried getDocumentBase() and it gives me an error. I'm wondering if this has to do with the fact that this is called on an applet from a main method? The applet is instantiated as a NoneLeft object, which extends JApplet, so that shouldn't be the problem. Do you have a clue on how to fix that?
    Again, thanks so much for the help.

  • Applet Socket permission problem

    Heloo I made an applet which gets the content of web . like if i pass the www.yahoo.com to applet it must read all the html coding of yahoo page .my code is perfect with the desktop application but when i run it with applet then it gives the socket permission error i search all where but i havent found any solution i tried to edit policy file but still found the same error kindly help me how to get rid from this error thanks and below is my code sample
    Applet code:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.security.Permission;
    public class Apple extends JApplet implements ActionListener{
              Container c;
         JTextField uf=new JTextField(30);
         JTextArea tarea=new JTextArea(600,600);
         JButton b=new JButton("Get Content");
         JButton bb=new JButton("Clear");
         URL u;
         JScrollPane sp=new JScrollPane();
         InputStream is = null;
    DataInputStream dis;
    String s;
         public void init(){
              JOptionPane.showMessageDialog(null,"hello world");
              c=new Container();
                   JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
              c=this.getContentPane();
              uf.setText("http://www.yahoo.com");
              c.setLayout(new FlowLayout(FlowLayout.LEFT));
              sp.add(tarea);
              c.add(new JLabel("Enter Your Url"));
              c.add(uf);
              c.add(b);     c.add(bb);
              c.add(new Label("EXAMPLE: http://www.rentacoder.com"));
              b.addActionListener(this);bb.addActionListener(this);
              c.add(tarea);     
         public void actionPerformed(ActionEvent ae){
              if( ae.getSource()==b){
                        JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
              down();
              if( ae.getSource()==bb){
    tarea.setText("");
              public void down(){
                   try{
                   System.out.println("1");
                   String uu=uf.getText()+":80";
                   u = new URL(uf.getText());
                   is = u.openStream();
                   dis = new DataInputStream(new BufferedInputStream(is));
                   String str;int k=0;int l=50;
                   while ((s = dis.readLine()) != null) {
    tarea.append(s+"\n");
    k++;
    if(k==l){
         JOptionPane.showMessageDialog(null,"Demo Product Developed By sarc");
    l=2*k;
    }is.close();
    } catch (MalformedURLException e) {JOptionPane.showMessageDialog(null,"e"+e);
    } catch (IOException e) {JOptionPane.showMessageDialog(null,e);
    HTML CODE :
    <applet code="Apple.class" width="300" height="300">
    </applet>

    The applet should be able to connect to the host it came from but I think you
    have to connect to the same port as well (not really sure about that).
    You can either have the consumers of your applet set up a policy for your applet
    or you sign the applet.
    Signing applets:
    http://forum.java.sun.com/thread.jsp?forum=63&thread=524815
    second post and last post for the java class file
    http://forum.java.sun.com/thread.jsp?forum=63&thread=409341
    4th post explaining how to set up your own policy with your own keystore
    Java security configuration (according to me):
    1. Signing, good for Internet published applets. The user will be asked if he or she trusts
    the applet and when yes or allways is clicked the applet can do whatever it wants. This
    is the default setting of the SUN jre and can be compared with IE setting that askes the
    user about downloading and running ActiveX controls from the Internet security zone.
    2. Setting up a policy. Good for people who disabled asking the user about signed
    applets (like companies that are worried this could cause a problem). it is possible
    to provide multiple java.policy files in the java.security, a company could put a .policy file
    on the Intanet and have all jre's use this by adding this URL to the java.security.
    When a policy needs to be changed the admin only has to do this is the file on the
    Intranet.
    A specific user can have a policy in their user.home to set up personal policies (to be
    done by Administrators).
    A policy file can use a keystore to be used in a signed by policy. For example "applets
    that are signed by SUN can access some files on my machine). It can allso be used
    to identify yourselve, when making an SSL connection the keystore can be used as
    the source of your public key.

  • Applet - page reload problem

    Greetings 4all,
    I'm developing, a bit complicated applet with few threads, listeners, and not difficult but expanded GUI. You can see it under www.demo.twelvee.com.pl.
    The problem is that this applet doesn't behave correctly after page reload in the browser. I mean that there are no graphics with parameters drawn in the middle of the main internal frame. I don't know why. When I'm visiting page first time everything works fine. This bug occurs only after reloading the page. Threads are still working, also all listeners are catching events. After few small tests I've recognized that method paintComponent() in each JPanel isn't called. I suppose it might be connected with browser's cache.
    Have You got any ideas? Because I have none, any suggestions are welcome :)
    You can access source here: http://www.iem.pw.edu.pl/~opalam/12/source/

    If it is due to the browser's cache of the applet, the only way that most (all?) current browsers will reload the applet is to close ALL of the browser's windows and restart the browser. (You used to be able to CTRL-F5 but this no longer works, afaik.)

  • Applet Object Class Problem

    I am just eperimenting with applets. I have made a very simple applet which works fine without any non-Java-Native object types. The applet only inserts a blank tabbed pane. As soon as I try to import another package, JFree Graphing in this case, the applet cannot find these JFree object data type classes.
    Everything works fine from the command prompt locally or via the appletViewer. I am using Resin as a standalone webserver, and the html and applet class are all in the same /doc directory. I have copied the two JFree JAR's (jfreechart-0.9.8.jar & jcommon-0.8.3.jar) everywhere I could think of. They're in my classpath, and they're in resin/lib, resin/doc/web-inf/lib, resin/doc/web-inf/work, and the local directory.
    There's obviously a problem with the applet finding the JAR, does anyone know how I can fix this?
    Thanks.
    -- APPLET TAG --
    <applet class="applet" code="applet.class" codebase="." width="600" height="300"></applet>
    -- EXCEPTION --
    java.lang.NoClassDefFoundError: org/jfree/data/DefaultMeterDataset
         at applet.<clinit>(applet.java:56)
         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)

    Hello.
    Try this...
    <applet class="applet" code="applet.class" codebase="." archive="jfreechart-0.9.8.jar,jcommon-0.8.3.jar" width="600" height="300"></applet>

  • Applet ms jvm problem

    Hi all,
    I'm writing an applet in which I use threads and it's giving me some errors with msjvm I don't understand.
    With sun plugins there is no problem and all is ok.
    I know that msjvm supports only 1.1.8 and I have to compile with -source 1.4 -target 1.1
    I did all my variable volatile, but with ms jvm the process never ends.
    My source is this:
    //File Prova.java
    public class Prova extends Applet implements ActionListener {
    public void init()
    MakeGUI();
    public void actionPerformed(ActionEvent event)
    if(event.getSource() == start)
    down_result.setText("");
    up_result.setText("");
    start.setEnabled(false);
    cycles = 0;
    status = 0;
    task = new LongTask(0);
    task.start();
    checkWork();
    task = null;
    private void checkWork() {
    try {
    while ( task.noStopRequested ) {
    if(status == 0) {
    //set_Stato_Progress();
    double b_c = format_double((double)task.current );
    double b_t = format_double((double)task.lengthOfTask);
    String cur = Double.toString(b_c);
    String tot = Double.toString(b_t);
    cycles++;
    double s_t = (double)task.current * 1000.0 * 8.0;
    down_result.setText("prova");
    //printThreadName("Down in ");
    if(task.done)
    stato_progress.setText("First step concluded");
    down_result.setText("Fine");
    status = 1;
    cycles = 0;
    else {
    //set_Stato_Progress();
    double b_c = format_double((double)task.current_up );
    double b_t = format_double((double)task.lengthOfTask);
    String cur = Double.toString(b_c);
    String tot = Double.toString(b_t);
    cycles++;
    double speed_temp = (double)task.current_up * 1000.0 * 8.0);
    double s_t = format_double(speed_temp);
    if(task.done_up)
    stato_progress.setText("Test concluso");
    start.setEnabled(true);
    repaint();
    task.interrupt();
    return;
    repaint();
    Thread.sleep((long)QUART_SECOND);
    catch ( Exception x ) {
    stop();
    //File LongTask.java
    public class LongTask extends Thread {
    public volatile boolean noStopRequested;
    private final Object pauseLock = new Object();
    private boolean paused;
    public volatile int lengthOfTask;
    public volatile int current = 0;
    public volatile boolean done = false;
    public boolean canceled = false;
    public String statMessage;
    public volatile long duration;
    public volatile double speed_down;
    public volatile long duration_up;
    public volatile double speed_up;
    public volatile int current_up = 0;
    public volatile boolean done_up = false;
    private byte [] image_byte;
    static int DEFAULT_DOWN_SIZE = 2097152;
    private void printThreadName(String prefix) {
    String name = Thread.currentThread().getName();
    System.out.println(prefix + name);
    public LongTask(int tipo_conn) {      
         lengthOfTask = DEFAULT_DOWN_SIZE;
    paused = true;
    noStopRequested = true;
    current = 0;
    duration = 0;
    speed_down = 0;
    duration_up = 0;
    speed_up = 0;
    current_up = 0;
    done = false;
    done_up = false;
    canceled = false;
    statMessage = null;
    image_byte = null;
    paused = false;
    public void stopThread() {
    paused = true;
    public void run() {
    Socket sock = null;
    InetSocketAddress isa = null;
    InputStream instream = null;
    ByteArrayOutputStream tempBuffer;
    int numBytesRead = 0;
    byte [] buffer;
    try {
    while (noStopRequested) {
    waitWhilePaused();
    //My first operation
    done = true;
    //My second operation
    done_up = true;
    paused = true;
    catch (MalformedURLException e) {
    System.out.println("[Errore] " + e.getMessage());
    Thread.currentThread().interrupt();
    catch(UnknownHostException e) {
    System.out.println("[Errore] " + e.getMessage());
    Thread.currentThread().interrupt();
    catch (IOException e) {
    System.out.println("[Errore] " + e.getMessage());
    Thread.currentThread().interrupt();
    catch(Exception e) {
    e.printStackTrace();
    speed_down = 0.0;
    speed_up = 0.0;
    Thread.currentThread().interrupt();
    private void setPaused(boolean newPauseState) {
    synchronized ( pauseLock ) {
    if ( paused != newPauseState ) {
    paused = newPauseState;
    pauseLock.notifyAll();
    private void waitWhilePaused() throws InterruptedException {
    synchronized ( pauseLock ) {
    while ( paused ) {
    pauseLock.wait();
    I can't explain me where is my error.
    Running my applet on msjvm, it semms that LongTask never ends and never update the volatile variables.
    Any hints?
    Thanks for the support
    Laura

    Solved.
    The ms jvm support 1.1* and then there is no Double.parseDouble.....
    You have to use Double.valueOf(....).doubleValue();
    Bye
    Laura

  • Java Threads compilation problem

    Hi everyone,
    I've having problems getting a simple thread program to compile, the programs says " ; " expected when there is already one present. I've gone through the program many times and still can't put my finger on whats going wrong. If someone could take a quick look and if possible tell me where I am going wrong.
    Many Thanks
    Its class ThreadA that will not compile
    ***code********************************************
    public class ThreadA extends Thread
    private int id;
    public ThreadA(int i) (id = i);
    public void run()
    for (int i=0}; i < 10; i++);
    try {sleep(1000};)catch (InterruptedException e)();
    System.out.println("Output from Thread " + id);
    import java.io.*;
    public class TestThreads1
    public static void main (String args [] )
    Thread t1 = new ThreadA (1);
    Thread t2 = new ThreadA (2);
    Thread t3 = new ThreadA (3);
    t1.start();
    t2.start();
    t3.start();
    **code***********************************************************

    public class ThreadA extends Thread
    private int id;
    public ThreadA(int i) (id = i); // <-- problem
    public void run()
    for (int i=0}; i < 10; i++); // <-- two problems
    try {sleep(1000};)catch (InterruptedException e)(); // <-- more problems
    System.out.println("Output from Thread " + id);
    }

Maybe you are looking for