Swing timer

Fermé
KENZA15A - 31 déc. 2013 à 03:45
KENZA15A Messages postés 2 Date d'inscription jeudi 5 décembre 2013 Statut Membre Dernière intervention 1 janvier 2014 - 1 janv. 2014 à 01:09
Bonjour,


dans le domaine du reseau couche liaison il existe plusieurs protocles dont chacun possede des fonctionnalités differentes
j'ai programmer une simmulation du protocole n2 qui consite a controler le flux (reguler la vitesse du recepteur a celle de l'emetteur(client en verifiant a chaque fois l'espace memoire disponible chez le recepteur(serveur))
j'ai creer deux classe et deux formes en utilisant netbeans comme IDE
mnnt je dois programmer le protocol 3
en ajoutant un controle d'erreur et un dg qui se declanche a un moment donné pour retransmettre le msg en cas d'erreur detectée par le recepteur
je dois utiliser pour cela la classe timer et la classe timertask mais j'arrive pas à les faire inclure dans mon code voici les classes du protocole 2 svp aider moi j'ai vraiment besoin de
votre aide et mrc d'avance
coté emetteur(client)
/*emetteur*/
package client;
import java.io.*;
import java.net.Socket;

public class Client{

public static void main(String[] args) throws IOException {

try {
entree_client fen_ser = new entree_client();//instance de la fenetre
fen_ser.setVisible(true);
Socket soc = new Socket("127.0.0.1", 2012);//connexion
PrintWriter sortie =new PrintWriter(soc.getOutputStream(), true);//contient le msg a envoyé par le client

BufferedReader entree = new BufferedReader(new InputStreamReader(soc.getInputStream()));//recevoir le credit du serveur

do {

String credit = entree.readLine();//lire le credit envoyé par le serveur

entree_client.Affichage_msg.append(credit);//afficher le credit dans le txtarea

sortie.println("abcd");//msg a envoyé
entree_client.Affichage_msg.append("\n msg est bien envoyé \n");


} while (true);

} catch (Exception e) {
System.out.println(e.getMessage());
}

}
}
la forme

package client;
import java.io.*;
import java.net.Socket;

/**
*
* @author rebelle
*/
public class entree_client extends javax.swing.JFrame {

/** Creates new form clientinter */
public entree_client() {
initComponents();

}

/** 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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
Affichage_msg = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel1.setText("liste des évenement");

Affichage_msg.setColumns(20);
Affichage_msg.setEditable(false);
Affichage_msg.setLineWrap(true);
Affichage_msg.setRows(5);
jScrollPane1.setViewportView(Affichage_msg);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(184, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(30, Short.MAX_VALUE))
);

pack();
}// </editor-fold>//GEN-END:initComponents

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(entree_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(entree_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(entree_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(entree_client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>


/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new entree_client().setVisible(true);
}
});

}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JTextArea Affichage_msg;
// End of variables declaration//GEN-END:variables
}


coté recepteur (serveur)
package serveur;
/*recepteur*/

import java.io.*;
import java.net.*;
import serveur.entree_serveur;

public class Serveur {

public static void main(String[] args) throws IOException {
entree_serveur fen_ser = new entree_serveur();//instance de la fenete
fen_ser .setVisible(true);
// TODO code application logic here
try {
ServerSocket sersoc = new ServerSocket(2012);//ouvrir le port 2012
entree_serveur.affichage.append("attente d'un client");//afficher attente
//**** recevoir la connexion qui vient du client et la mettre dans l'objet soc **** //

Socket soc = sersoc.accept();//accepter la connexion du client
entree_serveur.affichage.append("\n un client vient de se connecter");
//***** Création des flux de sortie et d'entrée ****//

PrintWriter sortie =new PrintWriter(soc.getOutputStream(), true);//flux de sortie
fen_ser .sortie = sortie;
BufferedReader entree = new BufferedReader(new InputStreamReader(soc.getInputStream()));//flux d'entree contient le msg du client
// int k=0;
int n = 20, m = 0;//n espace libre du buffer m espace occupé

entree_serveur.espace_libre.setText("" + n);//inserer l'espace libre
entree_serveur.espace_occupee.setText("" + m);//inserer l'espace occuppee
do {

String msg_lu;
msg_lu = entree.readLine();//lire le msg envoyé par le client
int i = msg_lu.length();//langeur de msg envoyé
//initialisation des elements de la fenetre
fen_ser .i = i;
n = fen_ser .n;
m = fen_ser .m;

fen_ser .n = n - i;//maj de l'espace libre dans la fenetre
fen_ser .m = m + i;//maj de l'espace occupé dans la fenetre

if (i <= n) {//si la langeur du msg envoyé < la taille du buffer
entree_serveur.affichage.append("\n" +"le message reçu est :"+ msg_lu);//accepter le msg et l'afficher
} else {

entree_serveur.affichage.append("Espace insufisant message non reçu");//sinon le msg n'est pas reçu
}
n = n - i;//maj de l'espace du buffer
m = m + i;//maj de l'espace occupé

entree_serveur.espace_libre.setText("" + n);//afficher l'espace libre du buffer dans le label espace_libre
entree_serveur.espace_occupee.setText("" + m);//afficher l'espace occupé du buffer dans le label espace_occupee

// k=k++;
} while (true);

} catch (Exception e) {
entree_serveur.affichage.append(e.getMessage()); }

}
}
forme
package serveur;

import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* serveurinter.java
*
* Created on 5 déc. 2013, 10:36:58
*/
/**
*
* @author rebelle
*/
public class entree_serveur extends javax.swing.JFrame {

public PrintWriter sortie;
public int n, m, i;//taille espace occupe taille du msg lu

/** Creates new form serveurinter */
public entree_serveur() {
initComponents();
n=20; m=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.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jLabel1 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
affichage = new javax.swing.JTextArea();
vider = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
libre = new javax.swing.JLabel();
occupé = new javax.swing.JLabel();
espace_libre = new javax.swing.JLabel();
espace_occupee = new javax.swing.JLabel();
envoyer = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel1.setText("liste des évenement:");

affichage.setBackground(new java.awt.Color(255, 255, 180));
affichage.setColumns(20);
affichage.setEditable(false);
affichage.setRows(5);
affichage.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
jScrollPane1.setViewportView(affichage);

vider.setBackground(new java.awt.Color(255, 255, 180));
vider.setText("vider le buffer");
vider.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
vider.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viderActionPerformed(evt);
}
});

jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12));
jLabel2.setText("contenu du buffer :");

libre.setFont(new java.awt.Font("Tahoma", 1, 12));
libre.setForeground(new java.awt.Color(0, 153, 0));
libre.setText("Libre ");

occupé.setFont(new java.awt.Font("Tahoma", 1, 12));
occupé.setForeground(new java.awt.Color(255, 0, 0));
occupé.setText("Occupé ");

espace_libre.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N

espace_occupee.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
espace_occupee.setText(" ");

envoyer.setBackground(new java.awt.Color(240, 240, 180));
envoyer.setText("envoyer un crédit");
envoyer.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
envoyer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
envoyerActionPerformed(evt);
}
});

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 186, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(envoyer, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
.addComponent(vider, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 157, Short.MAX_VALUE)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(libre)
.addComponent(occupé))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(espace_libre, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(espace_occupee, javax.swing.GroupLayout.PREFERRED_SIZE, 51, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(32, 32, 32))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(11, 11, 11)
.addComponent(envoyer, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(vider, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22)
.addComponent(jLabel2)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(libre)
.addComponent(espace_libre, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(occupé)
.addComponent(espace_occupee)))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE))
.addContainerGap())
);

pack();
}// </editor-fold>

private void viderActionPerformed(java.awt.event.ActionEvent evt) {
if(m>0){//on a encore de l'espace libre
n = n+i ;
m = m-i;

espace_libre.setText("" + n);
espace_occupee.setText("" + m);

}

}

private void envoyerActionPerformed(java.awt.event.ActionEvent evt) {
try {
if (n > 0) {
sortie.println("ok");

}else{
entree_serveur.envoyer.remove(this);
}


} catch (Exception o) {
affichage.append("\n erreur");
}

}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(entree_serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(entree_serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(entree_serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(entree_serveur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>


/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {
new entree_serveur().setVisible(true);
}
});
}
// Variables declaration - do not modify
public static javax.swing.JTextArea affichage;
public static javax.swing.JButton envoyer;
public static javax.swing.JLabel espace_libre;
public static javax.swing.JLabel espace_occupee;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JScrollPane jScrollPane1;
public static javax.swing.JLabel libre;
public static javax.swing.JLabel occupé;
public static javax.swing.JButton vider;
// End of variables declaration
}

nb:pour que le code fonctionne vous dever lancer le serveur avant l'emetteur
A voir également:

1 réponse

irmeche Messages postés 71 Date d'inscription jeudi 10 juin 2010 Statut Membre Dernière intervention 18 juillet 2014 17
Modifié par irmeche le 31/12/2013 à 11:15
Azul Kenza,
j'ai pas bien compris ce que tu veux faire masis regarde cette class si elle peut t'aider ou explique moi ce que tu veux exactement :



import java.util.Timer;
import java.util.TimerTask;

public class TimerPerso {
public static void main(String[] args) {

long temps = 2000; // délai avant de répéter la tache : 2000 = 2 seconde
long startTime = 0; // délai avant la mise en route (0 demarre immediatement)
Timer timer = new Timer(); // création du timer
TimerTask tache = new TimerTask() { // création et spécification de la tache à effectuer
public void run() {
//TODO ici se qui doit être effectué
System.out.println("salut");
}
};
timer.scheduleAtFixedRate(tache, startTime, temps); // ici on lance la mecanique
}
}
0
KENZA15A Messages postés 2 Date d'inscription jeudi 5 décembre 2013 Statut Membre Dernière intervention 1 janvier 2014
1 janv. 2014 à 01:09
mrc bcp irmeche
pour votre aide je c aussi q'au lieu de definir le TimerTask dans la meme classe je peut le definir comme une classe separée qui herite de la classe TimerTask mais comme j'ai deja dit le timer que je veut l'utiliser fonctionne avec une interface graphique(precisement un bouton qui reenvoie le mm msg deja envoyé apres un moment donné cad declanche le timer)
et je veut aussi afficher un countdown (le timer se deminue) du timer dans un TextField.est ce que vous pouvez m'aider ??et mrc encore une fois
0