Ecrire code ActionListener pour connexion VPN avec ComboBox

Lume_56 Messages postés 26 Date d'inscription lundi 1 juin 2020 Statut Membre Dernière intervention 20 octobre 2023 - 19 oct. 2023 à 09:26
Lume_56 Messages postés 26 Date d'inscription lundi 1 juin 2020 Statut Membre Dernière intervention 20 octobre 2023 - 20 oct. 2023 à 13:56

Bonjour à tous,

Je voudrais choisir un pays parmi une liste (ComboBox) pour lancer le VPN. J'ai parcouru pas mal de sites et étudié nb de scripts sans réussir à écrire le code pour la méthode ActionListener. Il existe beaucoup d'exemples avec  

System.out.println...

Je me suis inspiré du script ci-dessous mais je n'ai pas trouvé comment coder l'action qui devrait lancer cette commande :

sudo cyberghostvpn --streaming --country-code "$Name" --connect    

(J'ai laissé "$Name" mais je ne pense pas que ce soit écrit correctement.)

import javax.swing.*;
import java.awt.FlowLayout;

public class ComboBoxActionListenerVPN extends JFrame {
    public ComboBoxActionListenerVPN() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new ComboBoxActionListenerVPN().setVisible(true));
    }

    private void initialize() {
        setSize(300, 300);
        setLocationRelativeTo(null); //Nous demandons maintenant à notre objet de se positionner au centre  
        setLayout(new FlowLayout(FlowLayout.LEFT));
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        String[] names = new String[]{
                "France", "USA", "Allemagne", "GB", "Italie", "Espagne"
        };
        JComboBox<String> comboBox = new JComboBox<>(names);
        comboBox.setEditable(true);

        // Create an ActionListener for the JComboBox component.
        comboBox.addActionListener(event -> {
            // Get the source of the component, which is our combo
            // box.
            JComboBox comboBox1 = (JComboBox) event.getSource();
            

            //// Print the selected items and the action command.
            //Object selected = comboBox1.getSelectedItem();
            //System.out.println("Selected Item  = " + selected);
            //String command = event.getActionCommand();
            //System.out.println("Action Command = " + command);

            // Essai d'action avec cyberghostvpn
            Object selected = comboBox1.getSelectedItem();



            // Detect whether the action command is "comboBoxEdited"
            // or "comboBoxChanged"
            if ("comboBoxEdited".equals(command)) {
                System.out.println("User has typed a string in " +
                        "the combo box.");
            } else if ("comboBoxChanged".equals(command)) {
                System.out.println("User has selected an item " +
                        "from the combo box.");
            }
        });
        getContentPane().add(comboBox);
    }
}

Merci à tous.

A voir également:

4 réponses

KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
19 oct. 2023 à 15:26

Bonjour,

Sur la partie ComboBox, tu peux beaucoup simplifier :

private void initialize() {
    setSize(300, 300);
    setLocationRelativeTo(null);
    setLayout(new FlowLayout(FlowLayout.LEFT));
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    String[] names = {"France", "USA", "Allemagne", "GB", "Italie", "Espagne"};
    JComboBox<String> comboBox = new JComboBox<>(names);
    comboBox.addActionListener(event -> cyberghostvpn((String) comboBox.getSelectedItem()));
    add(comboBox);
}

private void cyberghostvpn(String country) {
    String command = "sudo cyberghostvpn --streaming --country-code " + country + " --connect";
    System.out.println(command); // TODO
}

0
Lume_56 Messages postés 26 Date d'inscription lundi 1 juin 2020 Statut Membre Dernière intervention 20 octobre 2023 1
19 oct. 2023 à 19:32

Bonsoir,

Merci pour ton aide. La commande se lance correctement mais la connexion au serveur VPN ne se fait pas. J'ai alors pensé au nom des pays tels qu'ils sont enregistrés par Cyberghostvpn : France =FR ! Après modification, tout se lance bien et la commande s'affiche dans le terminal. Par contre, aucune connexion. En mode direct via la console, la commande se connecte au VPN. 

0
KX Messages postés 16734 Date d'inscription samedi 31 mai 2008 Statut Modérateur Dernière intervention 24 avril 2024 3 015
19 oct. 2023 à 21:00

Dans mon message précédent je n'ai traité que la partie Combobox.
Aucune commande n'est lancée, on affiche juste ce que devrait être la commande.

Techniquement la commande pourra être lancée avec Runtime.exec() mais cela va ouvrir un nouveau processus avec des flux qu'il va falloir lire, c'est un travail un peu plus conséquent (voir code ci-dessous).

De plus, si tu fais plusieurs choix de pays avec ta Combobox, cela va lancer plusieurs commandes les unes derrières les autres, il faudrait s'assurer que les processus précédents soient bien arrêtés, c'est à dire qu'il faudra sûrement gérer une commande stop avant de faire une nouvelle commande connect.

En creusant un peu ton besoin, on voit bien que ton code va se complexifier, sans parler de la partie purement VPN qu'il faudra déboguer, car quand bien même tu exécuterait la bonne commande, ce n'est pas sûr que tu arrives à établir une connexion dès le premier coup.

Exemple de code pour exécuter des commandes, afficher les flux (out et err) et gérer les processus :

import java.io.*;

public class Ping {
    public static void main(String[] args) throws Exception {
        Process p1 = exec("ping", "localhost");
        p1.waitFor();
        System.err.println("#P1 = " + p1.exitValue()); // #P1 = 0 => on a attendu la fin du processus (en succès)

        Process p2 = exec("ping", "toto");
        p2.waitFor();
        System.err.println("#P2 = " + p2.exitValue()); // #P2 = 1 => on a attendu la fin du processus (en erreur)

        Process p3 = exec("ping", "localhost");
        Thread.sleep(100);
        p3.destroy();
        System.err.println("#P3 = " + p3.exitValue()); // #P3 = 1 => on a interrompu le processus avant la fin
    }

    private static Process exec(String... command) throws Exception {
        Process process = Runtime.getRuntime().exec(command);
        echoAll(process.getInputStream(), System.out);
        echoAll(process.getErrorStream(), System.err);
        return process;
    }

    private static void echoAll(InputStream input, PrintStream printer) {
        Thread t = new Thread(() -> new BufferedReader(new InputStreamReader(input)).lines().forEach(printer::println));
        t.setDaemon(true);
        t.start();
    }
}
0
Lume_56 Messages postés 26 Date d'inscription lundi 1 juin 2020 Statut Membre Dernière intervention 20 octobre 2023 1
20 oct. 2023 à 13:56

Ça ouvre des horizons !! Je vais étudier, tester et je te tiens au courant. Je vais être passablement pris, ne t'étonne pas de ne pas avoir de mes nouvelles prochainement.

Encore un grand merci !

0