IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Applets Java Discussion :

Application -> Applet


Sujet :

Applets Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 29
    Par défaut Application -> Applet
    Bonjour,

    J'ai un exemple d'application que je voudrais transformer en Applet.
    Pas trop de littérature là-dessus. Alors je vous soumets mon code :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
     
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
     
    public class GetFile extends JApplet {
     
    // java GetFile http://www.compupress.net or http://random.yahoo.com/bin/ryl
     
    	public static void main(String[] arguments) {
    		if ( arguments.length == 1 ) {
    			PageFrame page = new PageFrame(arguments[0]);
    			page.show();
    		}
    		else {
    			System.out.println("Usage: java GetFile url");
    		}
    	}
    }
     
    class PageFrame extends JFrame {
    	JTextArea box = new JTextArea("Get text...");
     
    	URL page;
     
    	public PageFrame (String address) {
    		super(address);
    		setSize( 600, 300 );
    		JScrollPane pane = new JScrollPane(box);
    		getContentPane().add(pane);
    		WindowListener wl = new WindowAdapter() {
    			public void windowClosing(WindowEvent evt) {
    				System.exit(0);
    			}
    		};
    		addWindowListener(wl);
     
    		try {
    			page = new URL(address);
    			getData(page);
    		}
    		catch (MalformedURLException e) {
    			System.out.println("Bad URL: " + address );
    		}
    	}
     
    	void getData( URL url ) {
    		URLConnection conn = null;
    		InputStreamReader in;
    		BufferedReader data;
    		String line;
    		StringBuffer buf = new StringBuffer();
    		try {
    			conn = this.page.openConnection();
    			conn.connect();
    			box.setText("Connexion open...");
     
    			in = new InputStreamReader(conn.getInputStream());
    			data = new BufferedReader(in);
    			box.setText("Reading data...");
     
    			while ((line = data.readLine()) != null) {
    				buf.append(line +"\n");
    			}
    			box.setText(buf.toString());
    		}
    		catch (IOException e) {
    			System.out.println("I/O error: " + e.getMessage());
    		}
    	}
    }
    J'ai tourné pendant des heures dans tous les sens, rien à faire pour transformer ce code en Applet.

    Ecran grisaille.

    Merci de me donner un coup de main et de me suggérer quelques lignes à modifier.

  2. #2
    Membre Expert Avatar de willoi
    Profil pro
    Développeur informatique
    Inscrit en
    Décembre 2006
    Messages
    1 355
    Détails du profil
    Informations personnelles :
    Âge : 52
    Localisation : France, Haute Garonne (Midi Pyrénées)

    Informations professionnelles :
    Activité : Développeur informatique

    Informations forums :
    Inscription : Décembre 2006
    Messages : 1 355
    Par défaut
    Lis un peu de doc sur les applets et tu t'apercevras que la methode main ne s'utilise pas dans une applet, qu'on ne travaille plus avec des Frames (ou du moins la plupart du temps) mais avec des Panels, car Applet est un instance de Panel.

    par exemple chapitre 9, un exemple d'applet:
    http://java.developpez.com/cours/lecoursjava/

  3. #3
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 29
    Par défaut
    Citation Envoyé par willoi
    Lis un peu de doc sur les applets et tu t'apercevras que la methode main ne s'utilise pas dans une applet, qu'on ne travaille plus avec des Frames (ou du moins la plupart du temps) mais avec des Panels, car Applet est un instance de Panel.

    par exemple chapitre 9, un exemple d'applet:
    http://java.developpez.com/cours/lecoursjava/
    Hello,

    Merci beaucoup pour la suggestion. Je suis allé faire un tour et j'ai trouvé ceci : ftp://ftp2.developpez.biz/developpo/...eneralites.pdf, une page pour dire qu'il faut :
    1) Initialiser
    • Public void init() {…}
    2) Démarrer
    • Public void start() {…}
    3) Arreter
    • Public void stop() {…}
    4) Dessiner (et écrire)
    • Public void paint(Graphics g) {…}

    ... Je savais un peu déjà cela (if you read me)...

    Le problème est + complexe : http://forum.java.sun.com/thread.jsp...art=0&tstart=0 où il est dit (vers le bas de la page) :

    "Provided no security will be broken by my application (although you can 'sign' your applet), I can make it become an applet by doing something like the following example. Note that I am instantiating the GUI from my application ...getting its content pane ...and then assigning that content pane to be the content pane of the applet. Simple. But be warned ...this is not a common thing to do. You are best to run straight back to example one post haste, lest you be lead down the path to Hell. Quick, run to the light!" etc...

    Ce que je ne savais pas - et merci - c'est que je dois remplacer les "Frames" par des "Panels". Je vais essayer.
    Ce que je ne sais toujours pas c'est comment concilier Applet avec la citation du dessus : "Simple. Be warned ... this is not a common thing to do."
    Exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
     
    /*
     * ApplicationTwo.java
     */
    public class ApplicationTwo extends javax.swing.JFrame {
      javax.swing.JLabel label;
      /** Creates new ApplicationTwo */
        public ApplicationTwo() {
            initComponents();
            calculate();
        }
      /** Helper method */
        private void initComponents() {
            label = new javax.swing.JLabel();
            setDefaultCloseOperation(
                javax.swing.WindowConstants.DISPOSE_ON_CLOSE
            );
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    System.exit(0);
                }
            });
            getContentPane().add(label, java.awt.BorderLayout.CENTER);
            pack();
            java.awt.Dimension screenSize =
              java.awt.Toolkit.getDefaultToolkit().getScreenSize();
            setSize(new java.awt.Dimension(300, 200));
            setLocation((screenSize.width-300)/2,(screenSize.height-200)/2);
        }
      /** Helper method */
        private void calculate() {
            double i;
            double f= 880;
            i=(Math.log(f)/Math.log(10));
            label.setText("i= " + i);
        }///:~
      /** This is only used when run as an application !! */
        public static void main(String args[]) {
          new ApplicationTwo().show();
        }
    }
    et :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     
    /*
     * AppletTwo.java
     */
    public class AppletTwo extends javax.swing.JApplet {
      /** Initializes AppletTwo by adding ApplicationTwo's content pane. */
        public AppletTwo() {
            getContentPane().add( new ApplicationTwo().getContentPane() );
        }
    }
    Encapsulation ...

    J'ai testé et cela fonctionne ... mais pas dans mon cas un tout p'tit peu plus compliqué ...

    Je ne suis vraiment pas très - et même pas du tout - avancé.

    ________________________________________________
    It's not what I'm but what I don't become that hurts me.

  4. #4
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 29
    Par défaut Voilà où j'en suis maintenant
    J'ai tout réécrit propre pour en faire un Applet Java mais cela bloque à la compilation.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
     
    // expected results in the JTextField
    // AF.PA;36,39;4/5/2007;17h35;+1,25;35,53;36,62;35,52;2547827
    // LVMH.PA;84,28;4/3/2007;17h38;+1,16;83,80;84,58;83,32;1963844
    import java.applet.AppletContext;
    import javax.swing.*;
    import java.awt.GridBagLayout;
    import java.awt.GridBagConstraints;
    import java.awt.Insets;
    import java.awt.event.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.io.*;
     
    public class ShowDocument extends JApplet 
                              implements ActionListener {
        the_URLWindow the_URLWindow;
     
        public void init() {
            //Execute a job on the event-dispatching thread:
            //creating this applet's GUI.
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        createGUI();
                    }
                });
            } catch (Exception e) {
                System.err.println("createGUI didn't successfully complete");
            }
        }
     
        private void createGUI() {
            JButton button = new JButton("Bring up the_URL window");
            button.addActionListener(this);
            add(button);
     
            JFrame.setDefaultLookAndFeelDecorated(true);
            the_URLWindow = new the_URLWindow(getAppletContext());
            the_URLWindow.pack();
        }
     
        public void destroy() {
            //Execute a job on the event-dispatching thread:
            //creating this applet's GUI.
            try {
                SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        destroyGUI();
                    }
                });
            } catch (Exception e) { }
        }
     
        private void destroyGUI() {
            the_URLWindow.setVisible(false);
            the_URLWindow = null;
        }
     
        public void actionPerformed(ActionEvent event) {
            the_URLWindow.setVisible(true);
        }
    }
     
    class the_URLWindow extends JFrame 
                            implements ActionListener {
        JTextField the_URL_Field;
        JComboBox choice;
        AppletContext appletContext;
     
        public the_URLWindow(AppletContext appletContext) {
            super("Show a Document!");
            this.appletContext = appletContext;
     
            JPanel contentPane = new JPanel(new GridBagLayout());
            setContentPane(contentPane);
            contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
            GridBagConstraints c = new GridBagConstraints();
            c.fill = GridBagConstraints.HORIZONTAL;
     
            JLabel label1 = new JLabel("the_URL of document to show: ",
    				   JLabel.TRAILING);
            add(label1, c);
     
            the_URL_Field = new JTextField("http://fr.finance.yahoo.com/d/quotes.txt?m=PA&f=sl1d1t1c1ohgv&e=.csv&s=AF.PA&s=LVMH.PA", 20);
            label1.setLabelFor(the_URL_Field);
            the_URL_Field.addActionListener(this);
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.weightx = 1.0;
            add(the_URL_Field, c);
     
            JLabel label2 = new JLabel("Window/frame to show it in: ",
    				   JLabel.TRAILING);
            c.gridwidth = 1;
            c.weightx = 0.0;
            add(label2, c);
     
            String[] strings = {
                "(browser's choice)", //don't specify
                "My Personal Window", //a window named "My Personal Window"
                "_blank",             //a new, unnamed window
                "_self",
                "_parent",
                "_top"                //the Frame that contained this applet
            };
            choice = new JComboBox(strings);
            label2.setLabelFor(choice);
            c.fill = GridBagConstraints.NONE;
            c.gridwidth = GridBagConstraints.REMAINDER;
            c.insets = new Insets(5,0,0,0);
            c.anchor = GridBagConstraints.LINE_START;
            add(choice, c);
     
    		JTextField box = new JTextField("Results");
    		//box.setLines(10);
    		box.setColumns(100);
     
    		c.fill = GridBagConstraints.NONE;
    		c.gridwidth = GridBagConstraints.REMAINDER;
    		c.insets = new Insets(5,100,100,0);
            c.anchor = GridBagConstraints.LINE_START;
            add(box, c);
     
            JButton button = new JButton("Show document");
            button.addActionListener(this);
            c.weighty = 1.0;
            c.ipadx = 10;
            c.ipady = 10;
            c.insets = new Insets(10,0,0,0);
            c.anchor = GridBagConstraints.PAGE_END;
            add(button, c);
        } 
     
        public void actionPerformed(ActionEvent event) {
            String the_URL_String = the_URL_Field.getText();
            URL the_URL = null;
            try {
                the_URL = new URL(the_URL_String);
            } catch (MalformedURLException e) {
                System.err.println("Malformed URL: " + the_URL_String);
            }
     
            if (the_URL != null) {
    			box.setText(showDocument(the_URL));// *********** compilation bloque ici *************
    			/*
    			URLConnection conn = the_URL.openConnection();
    			BufferedReader in = 
    				new BufferedReader(new InputStreamReader(conn.getInputStream()));
    				String inputLine;
     
    				while ((inputLine = in.readLine()) != null) {
    					System.out.println(inputLine);
    				}
    				in.close();
    			*/
                /*
    			if (choice.getSelectedIndex() == 0) {
                    appletContext.showDocument(the_URL);
                } else {
                    appletContext.showDocument(the_URL, 
    				  (String)choice.getSelectedItem());
                }
    			*/
     
            }
        }
    }
    Ce que je veux récupérer c'est les deux lignes :
    // AF.PA;36,39;4/5/2007;17h35;+1,25;35,53;36,62;35,52;2547827
    // LVMH.PA;84,28;4/3/2007;17h38;+1,16;83,80;84,58;83,32;1963844

    Après, je lis ligne par ligne le JTextField, je fais un split(";") pour me donner un vecteur et avec les valeurs je mets à jour via connector/J ma base de données mYSQL etc ...

    Simple mais cela bloque.

  5. #5
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 29
    Par défaut
    En fait mon applet marche mais pas comme je le souhaite :
    vers la fin :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
     
     /*
    			if (choice.getSelectedIndex() == 0) {
                    appletContext.showDocument(the_URL);
                } else {
                    appletContext.showDocument(the_URL, 
    				  (String)choice.getSelectedItem());
                }
    			*/
    Si j'enlève les commentaires /* et */, le fichier texte espéré est téléchargé alors que je veux l'avoir dans ma box. Actuellement, j'ai dans mon dossier "/Downloads" un myriade de fichiers "quotes. txt quotes-1.txt etc ... quotes-n.txt", correspondant aux n clicks que j'ai fait sur le bouton.

    En final, je veux lancer un Thread qui va jouer sa musique toutes les 20 mn et ainsi automatiser ma collection de données.

    Merci.

  6. #6
    Membre averti
    Profil pro
    Inscrit en
    Septembre 2006
    Messages
    29
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Septembre 2006
    Messages : 29
    Par défaut Détruire un fichier une fois lu ?
    Si j'arrive à détruire un fichier "quotes.txt" après l'avoir lu, mon problèmes est résolu.

    Je ne pense pas que ce soit vraiment possible sans signer l'Applet avec un certificat, et cela c'est plus dur.

Discussions similaires

  1. Transformer une application en applet
    Par kayenne77 dans le forum Applets
    Réponses: 1
    Dernier message: 21/07/2009, 11h44
  2. Lancer une application par applet
    Par maikof dans le forum Applets
    Réponses: 3
    Dernier message: 18/10/2007, 17h26
  3. convertir application en applet
    Par franfr57 dans le forum Applets
    Réponses: 1
    Dernier message: 15/06/2007, 09h32
  4. Application ou Applet dans mon cas ?
    Par Tarfaa dans le forum Applets
    Réponses: 4
    Dernier message: 07/05/2007, 23h11
  5. Transformation d'une application en Applet
    Par Alex2065 dans le forum Applets
    Réponses: 2
    Dernier message: 07/02/2007, 14h23

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo