SwingWorker in Applet

Hi,
I have a question on using class SwingWorker and Applets.
My usecase is this:
I have an applet with a menue (java.awt.Choice). My applet implements ItemListener and so I can register
the applet as itemlistener for the menue.
I have an inner class in the applet which extends SwingWorker. This worker is constantly running in the background - when the user
makes a choice in the menu, the worker is notified and some logic is carried out.
I need the worker to be constantly running in the background. So, in method done() - the last thing I do is to re-instantiate the worker itself.
Is this ok? Code below:
public class myapplet ....{
      private MyWorker worker;
      init(){
           worker = new MyWorker();
     class MyWorker extends SwingWorker....{
          protected String doInBackground(){
              while(true){
                 if(userMadeChoiceInTheMenu()){
                      return "someValue";             
          public void done(){
               try{
                   showNewPageBasedOnUsersChoiceInTheMenue();
               finally{
                    worker = new MyWorker();
                   worker.execute();
}best regards, Håkan
Edited by: 933709 on Jul 11, 2012 1:06 AM
Edited by: 933709 on Jul 11, 2012 1:07 AM

First, best practices guides exists to be followed, they prevent you from getting strange errors like this one you got.
I'll not enumerate your mistakes here, I'll just try to help you, but you should really try to follow some coding rules.
The problem could be this:
There is no guarantee that your objects will be collected at the end of your applet, or if the user reload the page, or even if he closes the tab and open another.
Calling System.gc() just asks kindly to the garbage collector, but it will probably not run.
What does it have to do with your applet?
Let's take a look:
public abstract class SwingWorker<T, V> implements Runnable, Future<T> {    
    private static ExecutorService executorService = null;This code will run only when your class is loaded the first time. Considering that it's still in the memory when the page is reloaded, it will not be executed and your old ExecutorService will be used instead of a new one, and it could will be in an illegal state!
Holp it helps,
Henrique Abreu

Similar Messages

  • Using a SwingWorker in an Executor class?

    Here's some code that works and does what I want but I don't know if its a good idea....
    I have a program that may run one of a couple dozen long operations. I want to bring up a progress dialog to show the user how these operations are coming along.
    I was using a swing worker every time I ran a long task but its a pain to make changes in so many different places. So I set up the approach below.
    import java.util.concurrent.Executor;
    import javax.swing.JOptionPane;
    import com.sun.java.help.impl.SwingWorker;
    * This class takes a long task as a Runnable and
    * runs it while showing a progress dialog
    public class MyExecutor implements Executor
         public void execute(Runnable r)
              final MySmallProgressWindow dialog;
              dialog = new MySmallProgressWindow();
              final Runnable fr = r;
              dialog.show("Testing Executor ") ;
              final SwingWorker worker = new SwingWorker()
                   public Object construct()
                        try
                            fr.run();
                       catch(Exception g)
                             System.err.println(g);
                             JOptionPane.showMessageDialog(null, "Error: " + g.toString(), "Error", JOptionPane.ERROR_MESSAGE);
                       finally
                            dialog.hide();
                            System.out.println("Clean up here in finally");
                       return null;
                   public void finished()
                           dialog.hide();
             worker.start();
    I call it this way
    MyExecutor execute = new MyExecutor();                   
    Runnable runnableCopy = new Runnable() {
    public void run() {
         someLongTask();
    execute.execute(runnableCopy);Comments?
    Message was edited by:
    legoqueen

    import javax.swing.*;
    public class MyApplet extends JApplet {
         public void init() {
              //init stuff here
         public void start() {
              //start stuff here
         public static void main(String[] args) {
              JFrame f = new JFrame();
              JApplet a = new MyApplet();
              f.getContentPane().add(a);
              f.setSize(600, 400);
              f.setVisible(true);
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              a.init();
              a.start();
    }Excuse me, but is there a way to do this on Applet only instead of JApplet... I was told we need to use Applet only...

  • Loading an image into an Applet from a JAR file

    Hello everyone, hopefully a simple question for someone to help me with!
    Im trying to load some images into an applet, currently it uses the JApplet.getImage(url) method just before registering with a media tracker, which works but for the sake of efficiency I would prefer the images all to be contained in the jar file as oppossed to being loaded individually from the server.
    Say I have a class in a package eg, 'com.mydomain.myapplet.class.bin' and an images contained in the file structure 'com.mydomain.myapplet.images.img.gif' how do I load it (and waiting for it to be loaded before preceeding?
    I've seen lots of info of the web for this but much of it is very old (pre 2000) and im sure things have changed a little since then.
    Thanks for any help!

    I don't touch applets, so I can't help you there, but here's some Friday Fun: tracking image loading.
    import java.awt.*;
    import java.awt.image.*;
    import java.beans.*;
    import java.io.*;
    import java.net.*;
    import javax.imageio.*;
    import javax.imageio.event.*;
    import javax.imageio.stream.*;
    import javax.swing.*;
    public class ImageLoader extends SwingWorker<BufferedImage, Void> {
        private URL url;
        private JLabel target;
        private IIOReadProgressAdapter listener = new IIOReadProgressAdapter() {
            @Override public void imageProgress(ImageReader source, float percentageDone) {
                setProgress((int)percentageDone);
            @Override public void imageComplete(ImageReader source) {
                setProgress(100);
        public ImageLoader(URL url, JLabel target) {
            this.url = url;
            this.target = target;
        @Override protected BufferedImage doInBackground() throws IOException {
            ImageInputStream input = ImageIO.createImageInputStream(url.openStream());
            try {
                ImageReader reader = ImageIO.getImageReaders(input).next();
                reader.addIIOReadProgressListener(listener);
                reader.setInput(input);
                return reader.read(0);
            } finally {
                input.close();
        @Override protected void done() {
            try {
                target.setIcon(new ImageIcon(get()));
            } catch(Exception e) {
                JOptionPane.showMessageDialog(null, e, "Error", JOptionPane.ERROR_MESSAGE);
        //demo
        public static void main(String[] args) throws IOException {
            final URL url = new URL("http://blogs.sun.com/jag/resource/JagHeadshot.jpg");
            EventQueue.invokeLater(new Runnable(){
                public void run() {
                    launch(url);
        static void launch(URL url) {
            JLabel imageLabel = new JLabel();
            final JProgressBar progress = new JProgressBar();
            progress.setBorderPainted(true);
            progress.setStringPainted(true);
            JScrollPane scroller = new JScrollPane(imageLabel);
            scroller.setPreferredSize(new Dimension(800,600));
            JPanel content = new JPanel(new BorderLayout());
            content.add(scroller, BorderLayout.CENTER);
            content.add(progress, BorderLayout.SOUTH);
            JFrame f = new JFrame("ImageLoader");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.setContentPane(content);
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            ImageLoader loader = new ImageLoader(url, imageLabel);
            loader.addPropertyChangeListener( new PropertyChangeListener() {
                 public  void propertyChange(PropertyChangeEvent evt) {
                     if ("progress".equals(evt.getPropertyName())) {
                         progress.setValue((Integer)evt.getNewValue());
                         System.out.println(evt.getNewValue());
                     } else if ("state".equals(evt.getPropertyName())) {
                         if (SwingWorker.StateValue.DONE == evt.getNewValue()) {
                             progress.setIndeterminate(true);
            loader.execute();
    abstract class IIOReadProgressAdapter implements IIOReadProgressListener {
        @Override public void imageComplete(ImageReader source) {}
        @Override public void imageProgress(ImageReader source, float percentageDone) {}
        @Override public void imageStarted(ImageReader source, int imageIndex) {}
        @Override public void readAborted(ImageReader source) {}
        @Override public void sequenceComplete(ImageReader source) {}
        @Override public void sequenceStarted(ImageReader source, int minIndex) {}
        @Override public void thumbnailComplete(ImageReader source) {}
        @Override public void thumbnailProgress(ImageReader source, float percentageDone) {}
        @Override public void thumbnailStarted(ImageReader source, int imageIndex, int thumbnailIndex) {}
    }

  • Problems with SwingWorker and classes in my new job, ;), can you help me?

    Hi all, ;)
    First of all, sorry about my poor English.
    I have a problem with Swing and Threads, I hope you help me (because I'm in the firsts two weeks in my new job)
    I have two classes:
    Form1: Its a JPanel class with JProgressBar and JLabel inside.
    FormularioApplet: (the main) Its a JPanel class with a form1 inside.
    I have to download a file from a server and show the progress of the download in the JProgressBar. To make it I do this:
    In Form1 I make a Thread that update the progress bar and gets the fole from the server.
    In FormularioApplet (the main) I call to the method getDownloadedFile from Form1 to get the File.
    THE PROBLEM:
    The execution of FormularioApplet finishes before the Thread of Form1 (with download the file) download the file. Then, when I call in FormularioApplet the variable with the file an Exception: Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException is generated.
    First main begins his execution, then call to Form1 (a thread) then continues his execution and when the execution is finished ends the execution os Form1 and his thread.
    How can I do for main class call the function and the Thread download his file after main class assign the file of return method?
    How can I pass information froma class include an a main class. Form1 can't send to main (because main class made a Form1 f1 = new Form1()) any information from his end of the execution. I think if Form1 can say to main class that he finishes is job, then main class can gets the file.
    I put in bold the important lines.
    Note: My level of JAVA, you can see, is not elevated.
    THANKS A LOT
    Form1 class:
    package es.cambrabcn.signer.gui;
    import java.awt.HeadlessException;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.SwingUtilities;
    public class Form1 extends javax.swing.JPanel {
        //Variables relacionadas con la clase original DownloadProgressBar
        private InputStream file;
        private int totalCicles;
        private int totalFiles;
        private int currentProgress;
        private SwingWorker worker;
        private ByteArrayOutputStream byteArray;
        private boolean done;
        /** Creates new form prueba */
        public Form1() {
            initComponents();
            this.byteArray = new ByteArrayOutputStream();
            progressBar.setStringPainted(true);
            //this.totalFiles = totalFiles;
            currentProgress = 0;
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" C�digo Generado ">                         
        private void initComponents() {
            label1 = new javax.swing.JLabel();
            progressBar = new javax.swing.JProgressBar();
            statusLabel = new javax.swing.JLabel();
            setBackground(new java.awt.Color(255, 255, 255));
            setMaximumSize(new java.awt.Dimension(300, 150));
            setMinimumSize(new java.awt.Dimension(300, 150));
            setPreferredSize(new java.awt.Dimension(300, 150));
            label1.setFont(new java.awt.Font("Arial", 1, 18));
            label1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label1.setText("Barra de progreso");
            statusLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            statusLabel.setText("Cargando");
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap()
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, statusLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, progressBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, label1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE))
                    .addContainerGap())
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label1)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(progressBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(statusLabel)
                    .addContainerGap(73, Short.MAX_VALUE))
        }// </editor-fold>                       
        // Declaraci�n de variables - no modificar                    
        private javax.swing.JLabel label1;
        private javax.swing.JProgressBar progressBar;
        private javax.swing.JLabel statusLabel;
        // Fin de declaraci�n de variables                  
        public byte[] getDownloadedFile(String documentToSign){
             //Variables locales
             byte puente[] = null;
             try{
                //Leemos el documento a firmar
                StringTokenizer st = new StringTokenizer(documentToSign, ";");
                Vector<URL> fileURL = new Vector<URL>();
                HttpSender sender = new HttpSender(null);
                //Introducimos la lista de URLs de archivos a bajar en el objeto Vector
                for(; st.hasMoreTokens(); fileURL.add(new URL(st.nextToken())));
                //Para cada URL descargaremos un archivo
                for(int i = 0; i < fileURL.size(); i++) {
                    file = sender.getMethod((URL)fileURL.get(i));
                    if(file == null) {
                        Thread.sleep(1000L);
                        throw new RuntimeException("Error descarregant el document a signar.");
                    System.out.println("Form1 Dentro de getDownloadFile, Antes de startDownload()");
                    //Fijamos el valor del n�mero de ciclos que se har�n seg�n el tama�o del fichero
                    this.totalCicles = sender.returnCurrentContentLength() / 1024;
                    this.progressBar.setMaximum(totalCicles);
                    //Modificamos el texto del JLabel seg�n el n�mero de fichero que estemos descargando
                    this.statusLabel.setText((new StringBuilder("Descarregant document ")).append(i + 1).append(" de ").append(fileURL.size()).toString());
                    statusLabel.setAlignmentX(0.5F);
                    *//Iniciamos la descarga del fichero, este m�todo llama internamente a un Thread*
                    *this.startDownload();*
                    *System.out.println("Form1 Dentro de getDownloadFile, Despu�s de startDownload()");*
                    *//if (pane.showProgressDialog() == -1) {*
                    *while (!this.isDone()){*
                        *System.out.println("No est� acabada la descarga");*
                        *if (this.isDone()){*
                            *System.out.println("Thread ACABADO --> Enviamos a puente el archivo");*
                            *puente = this.byteArray.toByteArray();*
                            *System.out.println("Form1 getDownloadFile() tama�o puente: " + puente.length);*
                        *else{*
                            *Thread.sleep(5000L);*
    *//                        throw new RuntimeException("Proc�s de desc�rrega del document a signar cancel�lat.");*
            catch (HeadlessException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("UI: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (MalformedURLException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (HttpSenderException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            catch (InterruptedException e) {
                    //javascript("onSignError", new String[] {
                    //(new StringBuilder("CMS: ")).append(e.getMessage()).toString()});
            e.printStackTrace();
            //System.out.println("Form1 getDownloadFile() tama�o puente: " + puente.length);
            return puente;
        public void updateStatus(final int i){
            Runnable doSetProgressBarValue = new Runnable() {
                public void run() {
                    progressBar.setValue(i);
            SwingUtilities.invokeLater(doSetProgressBarValue);
        public void startDownload() {
            System.out.println("Form1 Inicio startDownload()");
            System.out.println("Form1 Dentro de startDownload, antes de definir la subclase SwingWorker");
            System.out.println(done);
            worker = new SwingWorker() {
                public Object construct() {
                    System.out.println("Form1 Dentro de startDownload, dentro de construct(), Antes de entrar en doWork()");
                    return doWork();
                public void finished() {
                    System.out.println("Form1 Dentro de startDownload, dentro de finished(), Antes de asignar done = true");
                    System.out.println(done);
                    done = true;
                    System.out.println("Form1 Dentro de startDownload, dentro de finished(), Despu�s de asignar done = true");
                    System.out.println(done);
                    statusLabel.setText("Completado, tama�o del archivo: " + (byteArray.size() / 1024) + "KB");
            System.out.println("Form1 Dentro de startDownload, antes de worker.start()");
            worker.start();
            System.out.println("Form1 Dentro de startDownload, antes de salir de startDownload");
            System.out.println(done);
            System.out.println("Form1 Dentro de startDownload, despu�s de worker.start()");
         * M�todo doWork()
         * Este m�todo descarga por partes el archivo que es necesario descargar, adem�s de actualizar
         * la barra de carga del proceso de carga de la GUI.
        public Object doWork() {
            System.out.println("Form1 doWork() this.byteArray.size(): " + this.byteArray.size());
            try {
                byte buffer[] = new byte[1024];
                for(int c = 0; (c = this.file.read(buffer)) > 0;) {
                    this.currentProgress++;
                    updateStatus(this.currentProgress);
                    this.byteArray.write(buffer, 0, c);
                this.byteArray.flush();
                this.file.close();
                this.currentProgress = totalCicles;
                updateStatus(this.currentProgress);
            } catch(IOException e) {
                e.printStackTrace();
            System.out.println("Form1 doWork() FINAL this.byteArray.size(): " + this.byteArray.size());
            //done = true;
            System.out.println("AHORA DONE = TRUE");
            return "Done";
        public boolean isDone() {
            return this.done;
    FormularioApplet class (main)
    package es.cambrabcn.signer.gui;
    import java.awt.Color;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.URL;
    import java.security.Security;
    import java.util.StringTokenizer;
    import java.util.Vector;
    import javax.swing.SwingUtilities;
    import netscape.javascript.JSObject;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import sun.security.provider.Sun;
    import be.cardon.cryptoapi.provider.CryptoAPIProvider;
    public class FormularioApplet extends java.applet.Applet {
        //Variables globales
        int paso = 0;
        private static final String JS_ONLOAD = "onLoad";
        private static final String JS_ONLOADERROR = "onLoadError";
        private static final int SIGNATURE_PDF = 1;
        private static final int SIGNATURE_XML = 2;
        //private String signButtonValue;
        private int signatureType;
        private String documentToSign;
        private String pdfSignatureField;
        private Vector<String> outputFilename;
        private Color appletBackground = new Color(255, 255, 255);
        private Vector<byte[]> ftbsigned;
         * Initializes the applet FormularioApplet
        public void init(){
            try {
                SwingUtilities.invokeLater(new Runnable() {
                //SwingUtilities.invokeAndWait(new Runnable() {
                //java.awt.EventQueue.invokeAndWait(new Runnable() {
                    public void run() {
                        try{
                            readParameters();
                            initComponents();
                        catch(FileNotFoundException e){
                            javascript(JS_ONLOADERROR, new String[] {
                                (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                            e.printStackTrace();                       
                        catch(IOException e) {
                            javascript(JS_ONLOADERROR, new String[] {
                                (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                            e.printStackTrace();
            catch (Exception e) {
                javascript(JS_ONLOADERROR, new String[] {
                    (new StringBuilder("Init: ")).append(e.getMessage()).toString()});
                e.printStackTrace();
            javascript(JS_ONLOAD, null);
        /** This method is called from within the init() method to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" C�digo Generado ">
        private void initComponents() {
            this.setSize(350, 450);
            appletPanel = new javax.swing.JPanel();
            jPanel1 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JLabel();
            jPanel2 = new javax.swing.JPanel();
            label = new javax.swing.JLabel();
            jPanel3 = new javax.swing.JPanel();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            setLayout(new java.awt.BorderLayout());
            appletPanel.setBackground(new java.awt.Color(255, 255, 255));
            appletPanel.setMaximumSize(new java.awt.Dimension(350, 430));
            appletPanel.setMinimumSize(new java.awt.Dimension(350, 430));
            appletPanel.setPreferredSize(new java.awt.Dimension(350, 430));
            jPanel1.setBackground(new java.awt.Color(255, 255, 255));
            jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            jTextField1.setFont(new java.awt.Font("Arial", 1, 18));
            jTextField1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jTextField1.setText("SIGNATURA ELECTRONICA");
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel2.setBackground(new java.awt.Color(255, 255, 255));
            jPanel2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            label.setIcon(new javax.swing.ImageIcon("C:\\java\\workspaces\\cambrabcn\\firmasElectronicas\\logo.gif"));
            org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 308, Short.MAX_VALUE)
                    .addContainerGap())
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(label)
                    .addContainerGap(229, Short.MAX_VALUE))
            jPanel3.setBackground(new java.awt.Color(255, 255, 255));
            jPanel3.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 204)));
            //this.jButton1.setVisible(false);
            //this.jButton2.setVisible(false);
            jButton1.setText("Seg\u00fcent");
            jButton1.setAlignmentX(0.5F);
            //Cargamos el primer formulario en el JPanel2
            loadFirstForm();
            //Modificamos el texto del bot�n y el contador de pasos.
            //this.jButton1.setText("Siguiente");
            //this.jButton1.setVisible(true);
            //this.jButton2.setVisible(true);
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
            jButton2.setText("Cancel\u00b7lar");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
            org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
            jPanel3.setLayout(jPanel3Layout);
            jPanel3Layout.setHorizontalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jButton1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 94, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 112, Short.MAX_VALUE)
                    .add(jButton2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            jPanel3Layout.setVerticalGroup(
                jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel3Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jButton2)
                        .add(jButton1))
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout appletPanelLayout = new org.jdesktop.layout.GroupLayout(appletPanel);
            appletPanel.setLayout(appletPanelLayout);
            appletPanelLayout.setHorizontalGroup(
                appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, appletPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jPanel3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addContainerGap())
            appletPanelLayout.setVerticalGroup(
                appletPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, appletPanelLayout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())
            add(appletPanel, java.awt.BorderLayout.CENTER);
        }// </editor-fold>
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
            this.destroy();
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                        
            changeForms(this.paso);
        // Declaraci�n de variables - no modificar
        private javax.swing.JPanel appletPanel;
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JPanel jPanel3;
        private javax.swing.JLabel jTextField1;
        private javax.swing.JLabel label;
        // Fin de declaraci�n de variables
         * M�todo readParameters
         * M�todo que inicializa los valores de los par�metros internos, recibidos por par�metro.
        private void readParameters() throws FileNotFoundException, IOException {
             ???????????????? deleted for the forum
            addSecurityProviders();
         * M�tode loadFirstForm
         * Aquest m�tode carrega a jPanel2 el formulari que informa sobre la c�rrega dels arxius
        private void loadFirstForm(){
            //Form1 f1 = new Form1(stream, i + 1, fileURL.size(), sender.returnCurrentContentLength(), appletBackground);
            //Form1 f1 = new Form1(fileURL.size(), sender.returnCurrentContentLength());
            Form1 f1 = new Form1();
            //Lo dimensionamos y posicionamos
            f1.setSize(310, 150);
            f1.setLocation(10, 110);
            //A�adimos el formulario al JPanel que lo contendr�
            this.jPanel2.add(f1);
            //Validem i repintem el JPanel
            jPanel2.validate();
            jPanel2.repaint();
            //Descarreguem l'arxiu a signar
            *System.out.println("FormularioApplet Dentro de loadFirstForm(), antes de llamar a getDownloadFile()");*
            *byte obj[] = f1.getDownloadedFile(this.documentToSign);*
            if (obj == null){
                System.out.println("Lo que devuelve f1.getDownloadedFile(this.documentToSign) es NULL");
            else{
                System.out.println("Lo que devuelve f1.getDownloadedFile(this.documentToSign) NO es NULL");
                System.out.println("obj: " + obj.length);
            this.ftbsigned.add(obj);
            System.out.println("FormularioApplet Dentro de loadFirstForm(), despu�s de llamar a getDownloadFile()");
            //Indicamos que el primer paso ya se ha efectuado
            this.paso++;
         * M�tode changeForms
         * Aquest m�tode carrega a jPanel2 un formulari concret segons el valor de la variable global "paso"
        private void changeForms(int paso){
            /*A cada paso se cargar� en el JPanel y formulario diferente
             * Paso previo: Se realiza en la inicializaci�n, carga el formulario, descarga el archivo y muestra la barra de carga.
             * Case 1: Se carga el formulario de selecci�n de tipo de firma.
             * Case 2: Se carga el formulario de datos de la persona que firma.
            this.paso = paso;
            switch(paso){
                case 1:
                    //Creamos un objeto de formulario (seleccion de tipo de firma)
                    Form2 f2 = new Form2();
                    //Lo dimensionamos y posicionamos
                    f2.setSize(310, 185);
                    f2.setLocation(10, 110);
                    //Quitamos el formulario 1 y a�adimos el formulario 2 al JPanel
                    this.jPanel2.remove(1);
                    this.jPanel2.add(f2);
                    //Validem i repintem el JPanel
                    jPanel2.validate();
                    jPanel2.repaint();
                    //Modificamos el contador de pasos.
                    this.paso++;
                    break;
                case 2:
                    //Creamos un objeto de formulario (seleccion de tipo de firma)
                    Form3 f3 = new Form3();
                    //Lo dimensionamos y posicionamos
                    f3.setSize(310, 175);
                    f3.setLocation(15, 130);
                    //Quitamos el formulario 1 y a�adimos el formulario 3 al JPanel
                    this.jPanel2.remove(1);
                    this.jPanel2.add(f3);
                    //Validem i repintem el JPanel
                    jPanel2.validate();
                    jPanel2.repaint();
                    //Modificamos el texto del bot�n y el contador de pasos.
                    this.jButton1.setText("Finalizar");
                    this.paso++;
                    break;
                default:
                    //Finalizar el Applet
                    //C�digo que se encargue de guardar el archivo en el disco duro del usuario
                    break;
        private void addSecurityProviders() throws FileNotFoundException, IOException {
            Security.addProvider(new CryptoAPIProvider());
            if (signatureType == SIGNATURE_PDF) {
                Security.addProvider(new BouncyCastleProvider());
            else {
                Security.addProvider(new Sun());
        private File createOutputFile(String filename, int index) {
            return new File((String)outputFilename.get(index));
        protected Object javascript(String function, String args[]) throws RuntimeException {
            //Remove
            if (true) return null;
            try {
                Vector<String> list = new Vector<String>();
                if(args != null) {
                    for(int i = 0; i < args.length; i++) {
                        list.addElement(args);
    if(list.size() > 0) {
    Object objs[] = new Object[list.size()];
    list.copyInto(objs);
    return JSObject.getWindow(this).call(function, objs);
    } catch(UnsatisfiedLinkError e) {
    e.printStackTrace();
    throw new RuntimeException((new StringBuilder()).append(e).append("\nFunci�: ").append(function).toString());
    } catch(Throwable e) {
    e.printStackTrace();
    throw new RuntimeException((new StringBuilder()).append(e).append("\nFunci�: ").append(function).toString());
    return JSObject.getWindow(this).call(function, new Object[0]);
    Edited by: Kefalegereta on Oct 31, 2007 3:54 AM
    Edited by: Kefalegereta on Oct 31, 2007 4:00 AM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        

    Look at iOS Troubleshooting Wi-Fi networks and connections  http://support.apple.com/kb/TS1398
    iPad: Issues connecting to Wi-Fi networks  http://support.apple.com/kb/ts3304
    iOS: Recommended settings for Wi-Fi routers and access points  http://support.apple.com/kb/HT4199
    Additional things to try.
    Try this first. Turn Off your iPad. Then turn Off (disconnect power cord) the wireless router & then back On. Now boot your iPad. Hopefully it will see the WiFi.
    Go to Settings>Wi-Fi and turn Off. Then while at Settings>Wi-Fi, turn back On and chose a Network.
    Change the channel on your wireless router. Instructions at http://macintoshhowto.com/advanced/how-to-get-a-good-range-on-your-wireless-netw ork.html
    Another thing to try - Go into your router security settings and change from WEP to WPA with AES.
    How to Quickly Fix iPad 3 Wi-Fi Reception Problems
    http://osxdaily.com/2012/03/21/fix-new-ipad-3-wi-fi-reception-problems/
    If none of the above suggestions work, look at this link.
    iPad Wi-Fi Problems: Comprehensive List of Fixes
    http://appletoolbox.com/2010/04/ipad-wi-fi-problems-comprehensive-list-of-fixes/
    Fix iPad Wifi Connection and Signal Issues  http://www.youtube.com/watch?v=uwWtIG5jUxE
    ~~~~~~~~~~~~~~~
    If any of the above solutions work, please post back what solved your problem. It will help others with the same problem.
     Cheers, Tom

  • Java.io.File causes "access denied" exception in a signed applet

    Hi,
    New to these forums and not entirely where it's appropriate to post this issue, so I'll stick it here for now until told otherwise.
    The problem:
    My applet throws the following exception.
    INFO: Exception Message: access denied (java.io.FilePermission C:\Some Dir With Spaces\AnotherDir\FinalDir read)
    The psuedo-code:
    java.io.File RootPath = new java.io.File( "C:\" );
    private boolean doesSubdirectoryExist(String directory) {
            boolean mResult = false;
            try
                java.io.File tmpPath = new java.io.File( RootPath.toString() + java.io.File.separatorChar + directory );
                mResult = tmpPath.isDirectory();
                tmpPath = null;
            catch (Exception e)
                ... error handling code
            return mResult;
    private void btnCheckPathActionPerformed(java.awt.event.ActionEvent evt) {
            ....some other stuff....
            doesSubdirectoryExist(.. a text field value from the GUI form..);
            ....some other stuff....
    }                                       The conditions:
    1) The applet is signed.
    2) The applet runs fine in the AppletViewer.
    3) I am using JDK1.5.0_09.
    4) When I click the button the event handler is tied to, it works correctly the first time.
    5) If I click a second time, with the same value in the text field (i.e. testing for the same subdirectory again) I get the exception error.
    I'm pulling my hair out trying to figure this one out. If it were a security issue with the applet running from a browser, why does it work the first time?
    Am I failing to release some lock that creating a java.io.File instance creates?
    I would appreciate any help.

    I've identified the issue. I was attempting to access the filesystem from two different thread and/or contexts.
    It seems that if I use the SwingWorker class from https://swingworker.dev.java.net/ to perform background tasks in the Worker thread, I don't get the security privileges required to modify the filesystem. Even though I have signed the jar correctly.
    However I can access the filesystem quite happily from the Event Dispatcher thread. If my jar is signed correctly.
    So, I have the following questions:
    1. Why doesn't SwingWorker worker threads get the same security context as the event dispatcher thread?
    2. Is there anyway I can give the worker thread the necessary security privileges?
    3. Is there anyway to do this without having to write my own thread handling code and creating my own thread pools?
    Message was edited by:
    Fidotas
    Message was edited by:
    Fidotas

  • Applet dont show the Components

    Hi,
    I’ve embedded applet in a jsp page. Initially appearance of applet is coming well. After some time during the process of applet , when the browser window is minimized and restored or if we are switching to any other window and coming back to the applet embedded jsp page, the things whatever displayed in applet are vanished because of which behavior of applet could not be recognized.
    I’ll explain the applet process flow briefly. My applet is for transferring files from local machine to server through FTP concept. To show the progress of file transfer I’ve used progress bar with percentage displayed on it. As the files are transferred, progress bar status varies and also the percentage displayed.
    Because of the above mentioned problem, the end user could not see the progress bar or anything else displayed in the applet. Problem is with applet behavior only.
    Can any body suggest me how to rectify this problem?
    Following is the fraction of applet code I’ve used.
    public class UploadFolderApplet extends javax.swing.JApplet {
         private javax.swing.JProgressBar jPB_Progress;
         private javax.swing.JPanel jPanel;
         private javax.swing.JLabel msglabel;
        public void init() {     
         try
                initComponents();
              catch (Exception ex)
                ex.printStackTrace();
         public void start()
         System.out.println("start()");     
         public void stop()
              try
              System.gc();
              System.out.println("stop()");               
              catch (Exception ee)
                   System.out.println("The Exception is at line 214 is ===>"+ee);
         public void destroy()
              try
              System.gc();
              System.out.println("destroy()");               
              catch (Exception ee)
                   System.out.println("The Exception is at line 214 is ===>"+ee);
         private void initComponents() {
         jPanel = new javax.swing.JPanel();
            msglabel = new javax.swing.JLabel();
            jPB_Progress = new javax.swing.JProgressBar();
            getContentPane().setLayout(null);
            jPanel.setLayout(null);
            jPanel.setBackground(new java.awt.Color(235, 235, 235));
            msglabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
            jPanel.add(msglabel);
            msglabel.setBounds(20, 40, 830, 270);
            jPanel.add(jPB_Progress);
            jPB_Progress.setBounds(280, 10, 280, 20);
            getContentPane().add(jPanel);
            jPanel.setBounds(0, 0, 870, 320);          
         jPB_Progress.setVisible(false);
         jPB_Progress.setBackground(new java.awt.Color(255, 255, 255));
            jPB_Progress.setForeground(new java.awt.Color(153, 227,155));
    public void pageLoad(String projid01,String clientname01,String projectname01,String isbnno01,String isbnext01,String projtype01,String username01)
              SwingWorker sw = new SwingWorker() {
              protected Object doInBackground() throws Exception {
              // this part is executed when user clicks button in jsp page
              return null;
    //          sw.execute();
              Thread th = new Thread(sw);
              th.start();
              th = null;
              if(sw.isDone()){
              sw = null;
    }Following code explains how the applet is embedded in JSP.
    <html>
    <head
    //some script code
    <script language='javascript'>
    function subForm(clientname,projectname,projid,isbnno,isbnext,projtype)
         document.applets.fmsupload.init();     
         document.applets.fmsupload.start();     
         document.applets.fmsupload.pageLoad(projid,clientname,projectname,isbnno,isbnext,projtype,uname);
    </script>
    </head>
    <body>
    //here some jsp code
    <input class="but" name="b" type="button" value="UploadFiles" onclick="return subForm('<%=clientname%>','<%=projectname.toUpperCase()%>','<%=projid%>','<%=isbnno%>','<%=isbnextn%>','<%=projtype%>');"  style="font-family: Verdana; font-size: 10pt; font-weight: bold">
    <applet  name="fmsupload" archive="fmstest.jar" type="applet"  code="UploadFolderApplet.class" codebase="./fms/uploadfolders"  height="320" width="870">
    </body>
    </html>can any one please give me the solution.

    If you are on a Mac, this requires Java SE 6 to compile (64 bit). It's my current understanding that Safari (32 bit) won't display 64 bit applets.
    I'm on a Mac, therefore it's pointless for me to try and assist you any more.

  • Threaded swing applet

    Hi,
    I need to write an applet that shows the results of a database query on a JTable.
    The query will be executed every second (only a few registers are retrieved from a mySQL db), and if a change is detected, the JTable must be updated.
    I've been reading about Swing and threads, and I know I must be careful when workin with threads on my GUI.
    So far, I know there exists a few methods to perform what I need, but I'm not shure which one would be the best for my app.
    The methods I'm considering are:
    - invokeLater or invokeAndWait
    - timer
    - SwingWorker
    What do you guys sugest and why ?
    Thanks

    Not sure of this, but I think you need both Timer (to query DB every second) and SwingUtilities.invokeLater (because your update task must be run outside of EDT)...
    Hope this helped a little,
    Regards.

  • How to show progress - Applet - Servlet

    Hi,
    I am new to applet-servlet communication. I have to show the progress at the applet front-end using a JProgressBar for a task being done at the servlet end. I request the gurus on the forum to post any example code for the above situation.

    Hi,
    U will have to use the SwingWorker to popup the JProgressBar, but in here i dont think u will be getting any input from servlet giving the job completed, if u are using jdk1.4.1 u can use
    setIndeterminate(true);
    I am attaching 2 methods below which i use to display the JProgressBar
    Method long task is where i actually call the servlet and in method buildData i create the URLConnection etc
    //appletData must implement Serializable
    public void buildData(Object appletData)throws Exception
    //define servlet name here
    ObjectInputStream inputFromServlet = null;
    URL          studentDBservlet = new URL("MyServlet");
    URLConnection servletConnection = studentDBservlet.openConnection();
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setUseCaches(false);
    servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
    ObjectOutputStream outputToServlet =
              new ObjectOutputStream(servletConnection.getOutputStream());
         // serialize the object
         if (!SwingUtilities.isEventDispatchThread())
              outputToServlet.writeObject(input);
              outputToServlet.flush();
              outputToServlet.close();
              inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
         else
              inputFromServlet = longTask(servletConnection, outputToServlet, appletData);
    private ObjectInputStream longTask(final URLConnection servletConnection,
                        final ObjectOutputStream outputToServlet,
                        final Object appletData)
         final JDialog dialog = new JDialog(PlanApplet.appletFrame, "Please Wait", true);
    isProcess = true;
         MapsPanel panel = new MapsPanel();
         panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
         //MapsLabel label = new MapsLabel("Work in process....");
    //label.setFont(Constant.bigFont);
         //label.setPreferredSize(new Dimension(230, 40));
         JProgressBar progressBar = new JProgressBar();
         progressBar.setIndeterminate(true);
         progressBar.setPreferredSize(new Dimension(140, 30));
    // final JugglerLabel jugLabel = new JugglerLabel();
    // jugLabel.startAnimation();
    // panel.setPreferredSize(new Dimension(175, 175));
         MapsPanel progressPanel = new MapsPanel(new FlowLayout(FlowLayout.CENTER, 5, 5));
         progressPanel.setPreferredSize(new Dimension(140, 80));
    progressPanel.add(progressBar);
    //     progressPanel.add(jugLabel);
    //     panel.add(Box.createVerticalStrut(5));
         //panel.add(label);
         panel.add(Box.createVerticalStrut(15));
         panel.add(progressPanel);
         panel.add(Box.createVerticalStrut(15));
         dialog.setSize(150, 115);
         dialog.setResizable(false);
    //     dialog.getContentPane().add(jugLabel);
    dialog.getContentPane().add(panel);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.setLocation(ScreenSize.getDialogLocation(dialog));
    //      final javax.swing.Timer popupTimer = new javax.swing.Timer(2000, new TimerListener(dialog));
         final SwingWorker worker = new SwingWorker()
         public Object construct()
              try
              PlanApplet.applet.setCursor(new Cursor(Cursor.WAIT_CURSOR));
              outputToServlet.writeObject(appletData);
              outputToServlet.flush();
              outputToServlet.close();
              return new ObjectInputStream(servletConnection.getInputStream());
              catch (Exception exc)
              return null;
         public void finished()
    // jugLabel.stopAnimation();
              dialog.dispose();
    Toolkit.getDefaultToolkit().beep();
    isProcess = false;
              LogWriter.out("the long process is finished", LogWriter.BASIC);
         worker.start();
    // popupTimer.start();
         //System.out.println("Process complete");
         dialog.show();
    // while(isProcess)
         return (ObjectInputStream) worker.getValue();

  • Progress bar on Applet using swing

    Not sure if this is Swing related or applet related, so I'll post it here... :-)
    Long work should be done on a Worker thread an not inside the Swing Dispacher thread .
    So normally I create a Runnable object that calls something like doWork(), and pass the runnable object as a parameter to the Sing utilities invokelater() function.
    My question is inside the worker thread how to update the GUI, in this case the progress bar?
    Can I just call from inside doWork() with no problems the progressbar.setValue(X)?
    Do I need to create another thread and use it too update the UI?
    Is something like this valid ?
    public void doWork() {
    // work work work
    progressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so on
    Thanks for the help!

    Not sure if this is Swing related or applet related,
    so I'll post it here... :-)It's definitely Swing related.
    Long work should be done on a Worker thread an not
    inside the Swing Dispacher thread . This is true.
    So normally I create a Runnable object that calls
    something like doWork(), and pass the runnable object
    as a parameter to the Sing utilities invokelater()
    function.This does not start a worker thread but rather schedules your Runnable object to be run on the EDT.
    My question is inside the worker thread how to update
    the GUI, in this case the progress bar?SwingUtilities or EventQueue have invokeLater and invokeAndWait specifically for this purpose.
    Can I just call from inside doWork() with no problems
    the progressbar.setValue(X)?
    Do I need to create another thread and use it too
    update the UI?No. Here's where you could use invokeLater.
    Is something like this valid ?
    public void doWork() {
    // work work work
    rogressbar.setValue(5);
    //more work
    progressbar.setValue(15);
    // and so onNo.
    >
    Thanks for the help!Like pete has pointed out, this seems to be a job for SwingWorker.

  • Swing Applet question

    I would like to know why the look and feel for Swing applet (especially, Text information embedded in JPanels) are different on Windows 2000 and XP embedded versions. The text information is left aligned in XP embedded when the same is centrally aligned in the 2000 version. In XP embedded, the applet is expanding beyond the screen size bounds. Is there anything I can do so that look and feel are the same in both these OS's.
    Regards, Scr

    nitroniouz wrote:
    (which don't work when you click on them)Are they freeze? The buttons don't react to the clicks or they seam to work but don't execute the expected function?
    I think that your actSignup actionPerfomed methos is not working well or it's taking too long to execute and you're blocking the EDT.
    Try to create a separate thread to do the database task, a SwingWorker may help you. Take a look at the [Cocurrency in Swing Tutorial|http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html].
    Regards,
    Henrique Abreu

  • Status about  Applet is loading

    Hi,
    My applet contains scrollpane and on the canvas the graphics were drawn. This applet loads on a browser. But it is taking time to load and i would like to show the status or progress bar so that user can know that applet is loading.
    Thanks in advance
    punni

    This may help:
    public void init() {   
       Container c = getContentPane();
       //create progress bar and loading label
       progressBar = new JProgressBar(0, 7);
       progressBar.setValue(0);
       progressBar.setStringPainted(true);   
       final JPanel progressPanel = new JPanel();
       progressPanel.add(progressBar,BorderLayout.SOUTH);
       JPanel panel = new JPanel(new BorderLayout());
       panel.add(new JPanel(),BorderLayout.NORTH);
       panel.add(new JLabel("<HTML><B>Loading...</B></HTML>",SwingConstants.CENTER),BorderLayout.CENTER);
       panel.add(progressPanel,BorderLayout.SOUTH);
       c.add(panel,BorderLayout.CENTER);
       doTimeConsumingStuff();
    }//end init method
       * Retrieve data from the database and build and display the currently selected Map.
       * Builds a MapData object after retrieving the data from the database. Builds all
       * the panels and adds everything to the Applet so that it can be displayed.                           
       private void doTimeConsumingStuff() {
          final JApplet applet = this;
          //SwingWorker is a class that SUN programmers made. 
          //You can find its code in 'The Java Tutorial'
          final SwingWorker worker = new SwingWorker() {
             * Whatever you put in this method is meant to take awhile.  So,
             * this is the portion that is actually ran in a thread separate from
             * the main thread.
             public Object construct() {
                //do your long stuff here.
                //note, in differring locations of your time-consuming, code, do:
                progressBar.setValue(1);
                progressBar.setValue(6);
                return yourObjectRef; //this can be any object
             }//end construct
             *  Executes all its code in the event-dispatching thread.  We want
             *  the GUI building to be done in the event dispatch thread. 
             *  Because we are using SUN's SwingWorker class, we don't need to
             *  wrap the GUI building portion in a SwingUtilities.invokeLater()
             *  method.  We just put the GUI building in the finished method of
             *  the SwingWorker and it will accomplish the same thing.
             public void finished() {    
                final Container c = getContentPane(); //applet's
                c.removeAll();  //removes the progress bar
                c.add({add your components});
                c.validate();               
             }//end finished
          };//end SwingWorker class
          worker.start();     
       }//end buildMap method

  • 1.6.0_23 JNLP2ClassLoader.findClass try again . slow jnlp applet loading

    Hello everyone,
    I am using jnlp to load applet. using jre1.6.0_23. (next generation plugin).
    While loading the applet I am getting following messages,
    security: The root CA hasnt been replaced
    security: No timestamping info available
    security: Found jurisdiction list file
    security: No need to checking trusted extension for this certificate
    security: The CRL support is disabled
    security: The OCSP support is disabled
    security: This OCSP End Entity validation is disabled
    security: Checking if certificate is in Deployment denied certificate store
    security: Checking if certificate is in Deployment permanent certificate store
    network: Cache entry not found [url: http://package/mic/ri/lib/japllet.jar, version: null]
    basic: Plugin2ClassLoader.getPermissions CeilingPolicy allPerms
    security: JAVAWS AppPolicy Permission requested for: http://testurl/test/ri/lib/jpllet.jar
    basic: JNLP2ClassLoader.getPermissions() X
    basic: JNLP2ClassLoader.findClass: com.pack.MyApplet: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.DefaultMICLookAndFeel: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.XMLScreen: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.JRenderer$1: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.TimeoutPopup: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.TransparentContainer: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.SwingWorker: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.JRenderer$10: try again ..
    basic: JNLP2ClassLoader.findClass: com.pack.StatusPanel: try again ..
    Let me know if anyone want to look at entire messages in java console.
    for all the classes in jar which is signed.
    JNLP I am using.
    *<?xml version="1.0" encoding="UTF-8" ?>*
    *<jnlp spec="1.0+">*
    *<information>*
    *<title>TestApp</title>*
    *<vendor>TestApp</vendor>*
    *</information>*
    *<security>*
    *<all-permissions/>*
    *<j2ee-application-client-permissions/>*
    *</security>*
    *<resources>*
    *<j2se version="1.6+"/>*
    *<jar href="japllet.jar" main="true" version="0007.0000.0012.0000"/>*
    *<property name="jnlp.versionEnabled" value="true"/>*
    *</resources>*
    *<applet-desc*
    name="TestApplet"
    main-class="com.pack.MyApplet"
    width="300"
    height="300">
    *</applet-desc>*
    *</jnlp>*
    and am using the deployJava.js in html.. find below the snippet from html,
    *+<script src=\"http://www.java.com/js/deployJava.js\"></script>+*
    *+<script type="text/javascript">+*
    +var attributes = {width:'100%', height:'100%'};+*
    +var parameters = {jnlp_href:'mttest.jnlp'}+*
    deployJava.runApplet(attributes, parameters, version);*
    *+</script>+*
    In the above script I have tried various combinations like codebase, code, type, archive. finally i kept the minimal attributes and parameters.
    Kindly note my applet is working fine in the browser. But I think because of the try again messages in java console it is taking time to load the applet ?
    Any help on this highly appreciated. I have almost spent my week trying to remove these messages.

    837182 wrote:
    ..the last message of fetching resources japllet.jar is there as i changed the location. .. How? To what? I now note the applet Jar uses a version number, which JaNeLA fails to take into account.
    ..but how about rest of the messages, How to get rid of those ? ..Although I wrote the software, in conjunction with others, we did not configure it to send us an email when someone runs the software. Because of that (and hopefully unsurprisingly) I will state that I do not know what JaNeLA reported. OTOH I will make a WAG that there was an 'invalid content' message somewhere in the report.
    Have you checked the JaNeLA Help page? It is the first place to check the error messages.
    Some notes:
    <li> Most of the errors are produced by J2SE inbuilt tools, and are messages common to XML validation. Search the net for them and you should find many hits.
    <li> You can 'ignore' the warnings and optimizations. They are intended to identify things that might or might not be relevant. JaNeLA is unable to tell, and prompts you to make an informed decision.
    As to whether it matters, consider this. I dealt with a failed JNLP launch that came down to illegal characters in the application title field. That is not something that JaNeLA even checks. But the simple principle is: Garbage In, Garbage Out. Before even considering why a JWS based launch is failing (or not working as you expect), it pays to ensure the input files are as logical and valid as we can make them. Otherwise 'all bets are off' as to how JWS clients will parse and act (or not) on the JNLP.
    Reviewing the original problem now that you have at least run the JaNeLA tool. Just as an 'out there' suggestion, try adding a codebase_lookup='false' parameter into the applet code (JNLP launch file(1)). That attribute is only relevant to applets that can use loose class files & JWS should not need that, but it might indicate a JRE bug if it speeds things up.
    1) ..Oh heck, throw it into the deployJava.js script as well. It will probably not help, but cannot hurt.
    BTW: How big is apllet.jar in bytes? How 'slow' in seconds/minutes is slow? What is the network bandwidth of the testing machine(s)?
    And now I remember to mention:
    1) 'apllet' -> 'applet'.
    2) Please use the code tags when posting Java or JavaScript code or snippets, XML/HTML/JNLP or input/output. For details see the 'sticky post' on the top of the forum thread listing. It is still possible to edit your original post to add the code tags.

  • Applet permissions denied unpredictably

    I have a Java 1.5 applet using SwingWorker that seems to break unpredictably due to the following error:
    java.util.concurrent.ExecutionException: java.security.AccessControlException: access denied (java.lang.RuntimePermission modifyThreadGroup)
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.jdesktop.swingworker.SwingWorker.get(Unknown Source)
    The applet is signed with jarsigner using a key I generated with
    keytool and exported as a self signed certificate.
    One pattern I often observe is that the applet works fine the first time I download it from a new browser when it pops up a dialog asking me if I want to trust the signer I created. However, if I close the first applet window and open it again from the same browser I do not get the trust dialog and the applet fails as above. This seems to happen for all subsequent applet invocations from the same browser.
    I've observered this with Firefox 1.5.0.7 and IE 6.0 on Windows XPsp2.
    Thank you.

    I have a Java 1.5 applet using SwingWorker that seems
    to break unpredictably due to the following error:
    java.util.concurrent.ExecutionException:
    java.security.AccessControlException: access denied
    (java.lang.RuntimePermission modifyThreadGroup)
    at
    java.util.concurrent.FutureTask$Sync.innerGet(Unknown
    Source)
    at java.util.concurrent.FutureTask.get(Unknown
    Source)
    at
    org.jdesktop.swingworker.SwingWorker.get(Unknown
    Source)
    The applet is signed with jarsigner using a key I
    generated with
    keytool and exported as a self signed certificate.
    One pattern I often observe is that the applet works
    fine the first time I download it from a new browser
    when it pops up a dialog asking me if I want to trust
    the signer I created. However, if I close the first
    applet window and open it again from the same browser
    I do not get the trust dialog and the applet fails as
    above. This seems to happen for all subsequent
    applet invocations from the same browser.
    I've observered this with Firefox 1.5.0.7 and IE 6.0
    on Windows XPsp2.
    Thank you.Something is not getting shutdown properly; I'd wager your AWTEvent Thread.
    To ensure this, make sure you overwrite stop/start/run/init for the Applet
    as described here...
    http://java.sun.com/j2se/1.3/docs/guide/misc/threadPrimitiveDeprecation.html
    This is the safe way to implement stop/start. Do it this way and there are no issues and the behavior is consistent across different Thread / Event models/Operating Systems.
    I personally prefer the Runnable interface as opposed to Thread BTW.
    Good Luck!
    (T)

  • Applet jar downloading

    Hi,
    As much as I understand, jars specified within the 'ARCHIVE' parameter of the APPLET tag are only downloaded when needed, i.e. a jar won't be dowloaded or at least not loaded into the classpath unless a class that's within it is being imported.
    I conclude that by watching the java console messages which dislay whenever a jar is downloaded...
    anyways, due to this behavior I occasionally run into flows that run really slowly because they import a class that's in a jar that wasn't yet downloaded... my question is whether there is anyway to tell the JVM to download in the background all jars specified in the ARCHIVE param ?
    clearly I could add a swingworker that does that in the background but the problem is that this won't be automatic, i.e. whenever i'll add a new jar to the classpath, i'll need to write another import in the swing worker so that this jar will also be downloaded....
    anyone ?
    thanks,
    Gil.

    As much as I understand, jars specified within the 'ARCHIVE' parameter of the APPLET tag are only downloaded when needed, i.e. a jar won't be dowloaded or at least not loaded into the classpath unless a class that's within it is being imported.That doesn't even make sense. How can Java know what's in the JAR file without downloading it?
    I suspect the truth is that Java downloads the JARS in the list in order whenever it needs a class it hasn't got yet, starting of course with the applet class itself and therefore the first JAR on the list.
    anyways, due to this behavior I occasionally run into flows that run really slowly because they import a class that's in a jar that wasn't yet downloaded... my question is whether there is anyway to tell the JVM to download in the background all jars specified in the ARCHIVE param?Combine the JAR files. But that will slow down the initial loading of course. Lazy loading is an optimization, normally a good idea.

  • SwingWorker, not sure how to implement...

    My problem: I've got a button in a simple Applet. This button, once clicked, triggers, basically, a quite long computation.
    The result is then displayed in a jLabel;
    Then, because the computating process sometimes can be really long, i've decided to show a "wait for a few second string" once the button is clicked BEFORE the actual results are displayed,
           lbLabel0.setText("wait a few second");
           String prob = testingBankroll.BibbidiBobbidiDisruptTimeout(risultati, tempi, bankroll, tempomax);
           lbLabel0.setText("result: " + prob );
       }); well, everything runs fine but the "wait for a few sec" string is not displayed.
    I was suggested (in another forum) to use SWINGWORKER, but i'm not really sure how to implement it... ( i was redirected here http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html
    I mean, do I have to creat a class? Or can I do without it?

    You can find an example of using a SwingWorker here:
    http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html

Maybe you are looking for

  • How to mapp logical repositories to physical ones

    hi, i ve created logical repository in miniSAP and know i want to know how to map it to physical repositories? waiting for reply regards, nasir

  • Formula as Parameter

    I have Crystal Reports X1, Pack 2. I have an inventory forecasting report with 2 subreports. I have set up the report with parameters as the user likes to view the report for a specific brand or item category. The report Item     Brand     Net Stock 

  • Change the appleid on a computer

    We gave a MacBook (10.7) to granddaughter for college (smart girl, will use it well) which I set up initially which means it was born with my AppleID. She has her own ID, so I'd really like to switch it to hers, but i cant figure out where to do that

  • Previous Version of the document after sent to Record Centre

    In the current Farm we have 2 web apps Collaboration Record Centre We are sending the document to Record Centre using the Send to Connection and the connection is setup as Move and leave a link . Once the document is sent to Record Centre its leaves

  • Adobe reader Form PDF renderered in Internet Explorer not being read by JAWS

    Hello, I'm checking the accessibility of my web application in case of XFA forms generated from Lifecycle Server ES. The standalone version of the PDF forms gets easily read by JAWS but when the same PDF is embedded in a web application JAWS does not