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

AWT/Swing Java Discussion :

Association Button à une variable dans une autre classe


Sujet :

AWT/Swing Java

  1. #1
    Nouveau Candidat au Club
    Femme Profil pro
    Étudiant
    Inscrit en
    Novembre 2011
    Messages
    1
    Détails du profil
    Informations personnelles :
    Sexe : Femme
    Localisation : France

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Novembre 2011
    Messages : 1
    Points : 1
    Points
    1
    Par défaut Association Button à une variable dans une autre classe
    Bonjour à tous,
    Je viens de m'inscrire sur le forum parce que j'ai vraiment besoin d'aide. J'ai fait une application client/serveur (le serveur peut supporter différents clients )et maintenant je dois créer une interface graphique pour le client!
    Tout marche bien jusqu'à ce que j'essaie d'associer la réponse d'un bouton à une variable dans la classe client!
    Chaque client commence un thread et communique avec le serveur via une boucle while. Je ne peux pas arrêter la boucle ni le thread pour associer cette variable.
    Voici ma classe client


    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
    public class Client implements Runnable {
        static Socket clientSocket = null;
         static PrintWriter out = null;
        static BufferedReader in = null;
        static BufferedReader stdIn= null;
        static String fromServer;
        static String fromUser;
    
        static int id=0;
        static String ID=null;
        
        public static void main(String[] args) throws IOException {
            try {
                Interface inter = new Interface();
                inter.application();
                clientSocket = new Socket("localhost", 9999);
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: localhost.");
                System.exit(1);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: localhost.");
                System.exit(1);
            }     
       }
        public static void start(){
        	Client client =new Client();
            Thread t = new Thread(client);
            t.start();
        }
    
    public void run() {		
    	try{
    	   out = new PrintWriter(clientSocket.getOutputStream(), true);
           in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
           BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
           
           String ClientID;
           
            if((ClientID = in.readLine()) != null){
        		System.out.println("Client: My ID is : "+ClientID );
        		ID= ClientID;
        	}
                  
            while (true) {
            	if((fromServer = in.readLine()) != null){
                System.out.println("***Server: " + fromServer);
                Interface.afficheServer("Server : " +fromServer);
                if (fromServer.equals("Bye.")||fromServer.equals("Exit."))           	
                    break;
            	}
                out.println("ok");
                if((fromServer = in.readLine()) != null){
                    System.out.println("Server: " + fromServer);
                    Interface.afficheServer("Server : " +fromServer);
                    	while(Interface.setServer()!=null ){
    					fromUser= Interface.setServer();
    					break;
                    	}
                   if (fromUser != null) {
                    	System.out.println("Client["+this.getId() +"]:" + fromUser);
                    	out.println(fromUser);
                    }  
                }
            }
        	
        	stdIn.close();
            clientSocket.close();
            out.close();
            in.close();
            
    	}catch (IOException e) {
            System.err.println("IOException:  " + e);    
          }
    }
    et ceci est ma classe Interface

    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
    public class Interface extends JFrame implements ActionListener{
    	private static String nom;
    	JPanel bas = new JPanel();
    	JPanel centre = new JPanel();
    	
    	JScrollPane scrollPane ;
    	JScrollPane scrollPaneMsg;
    
    	JButton start = new JButton("Start");
    	static JButton yes = new JButton("Yes");
    	static JButton no = new JButton("No");
    	JTextField nbrId = new JTextField();
        static JTextArea texte =new JTextArea("JOKES FROM YOUR FILE\n");
    	static JTextArea ss =new JTextArea("Welcome in Jokes application \n");
        Font police = new Font("Cambria", Font.BOLD, 14);
    	
    	private static Client client = new Client();
    	
    	public Interface() {
    		this.setTitle("Client Interface ");
    	    start.addActionListener(this);
    		yes.addActionListener(this);
    		no.addActionListener(this);
    		
    		addWindowListener (new WindowAdapter(){
    			public void windowClosing (WindowEvent e){
    				System.exit(0);
    			}
    		});
    	}
    	
    	public void application(){
    
    		/****REMPLISSAGE DU PANEL BT***/
    		bt.add(start);
    		bt.add(yes);
    		bt.add(no);
    		/*********************************/
    		/****REMPLISSAGE DU PANEL Messages****/
    		 JLabel msg = new JLabel("Messages from the server");
    		  lst.setLayout(new BorderLayout());
              ss.setFont(police);
    		  
    		/************************************/
    		sens.setLayout(new GridLayout(1,4));
    		/****REMPLISSAGE DU PANEL ID**/
    		JLabel typ = new JLabel("My ID");
    		sens.add(typ);
    		sens.add(nbrId);
    		/************************************/
    		/****REMPLISSAGE DU PANEL Jokes******/
    		JLabel st = new JLabel("Jokes");
    		statis.setLayout(new BorderLayout());
    		texte.setRows(20);
            texte.setFont(police);
           
    		/***************************************/
    		/******CREATION DU CONTAIMER*********/
    		Container tmp = this.getContentPane();
    		tmp.setLayout(new BorderLayout());
    		bas.setLayout(new GridLayout(2,1));
    		centre.setLayout(new GridLayout(2,1));
    		bas.add(sens);
    		bas.add(bt);
    	
    
    		tmp.add(bas,BorderLayout.NORTH);
    		tmp.add(centre,BorderLayout.CENTER);
    		this.pack(); 
    		this.setSize(700, 700);
    	    this.setLocationRelativeTo(null);
    		tmp.setBackground(Color.RED);
    		this.setVisible(true);   
    	
    	}
    	
    	public void actionPerformed(ActionEvent e) {
    		if(e.getSource() == start){
    			    nbrId.setText(client.getId());
    			    Client.start();
    			    nom="y";
    		}
    		if(e.getSource()== yes ){
    			nom = "y";
    			ss.append("y");			
    		}
    	}
    	public static void afficheServer(String s){
    		ss.setText(ss.getText()+"\n"+s);
    	}
    	public static void afficheFile(String s){
    		texte.setText(texte.getText()+"\n"+s);
    	}
    	public static String setServer(){
    		String b = null;
    		
    		if( nom == "y"){
    			b="y";
    		}
    		else if(nom=="n"){
    			b="n";
    		}
    		return b;
    	}
        
    }

  2. #2
    Membre éclairé
    Avatar de bpy1401
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Mars 2003
    Messages
    471
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 63
    Localisation : France, Eure (Haute Normandie)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : Industrie

    Informations forums :
    Inscription : Mars 2003
    Messages : 471
    Points : 831
    Points
    831
    Par défaut
    Bonjour zaina22

    Ton client est un thread, c'est bien. Fait juste une méthode dans ta classe client qui permet de modifier ta variable dans le client. puis appelle cette méthode lorsque que tu capture l'évènement sur ton bouton
    Page sur Developpez : http://pbriand.developpez.com

  3. #3
    Membre régulier
    Profil pro
    Inscrit en
    Mai 2010
    Messages
    107
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mai 2010
    Messages : 107
    Points : 120
    Points
    120
    Par défaut
    Bonjour,

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
     
    //Ici tu créer une nouvelle instance de Client() ce qui ne correspond pas à ce que tu veux
    private static Client client = new Client();
    Pour pouvoir avoir un lien sur ta classe Client, il te faut renseigner le constructeur de ta classe Interface que tu veux te rattacher à ta classe Client EXISTANTE.

    Donc dans ta classe Interface
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    private Client client;
    
    public Interface(Client leClient) {
          this.client = leClient;
          //... la suite du code
    }
    Et lorsque tu créais ta classe Interface depuis Client :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    Interface inter = new Interface(this);
    Mais attention ca c'est la version rapide (crade) de la chose.
    Je te conseil de lire ce tuto : ici

    edit : je suis à coter de la plaque.

Discussions similaires

  1. Réponses: 6
    Dernier message: 16/06/2011, 12h45
  2. récupérer une variable d'une fonction dans une classe
    Par free_dom dans le forum Général Python
    Réponses: 20
    Dernier message: 08/07/2009, 12h35
  3. portée d'une variable dans une fonction dans une méthode
    Par laurentg2003 dans le forum Général JavaScript
    Réponses: 4
    Dernier message: 29/06/2009, 19h05
  4. Réponses: 1
    Dernier message: 15/02/2007, 00h24
  5. Mettre une valeur d'une table dans une variable
    Par Raphou96 dans le forum Access
    Réponses: 5
    Dernier message: 06/02/2006, 15h19

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