Bonjour j'aimerai pouvoir changer un String dans ma classe main et j'utiliserai celui dans mon autre classe comment puis je faire cela??
merci bien de votre aide
Version imprimable
Bonjour j'aimerai pouvoir changer un String dans ma classe main et j'utiliserai celui dans mon autre classe comment puis je faire cela??
merci bien de votre aide
Je ne comprend pas ce que tu souhaites faire ?!
Tu veux passer un String de la classe main à une autre classe ? Si c'est çà il te suffit de le passer en argument du constructeur de l'autre classe ou par l'intermédiaire d'une méthode de l'autre classe.
je vais peut etre mieux expliquer pour que tout le monde comprenne.
Dans ma classe principale j'ai une combobox avec plusieur valeur.
Lorsque je choisi cette valeur j'aimerai que ma 2em classe (qui envoie des données via mon port com vert un autre pc) envoi le texte de ma combobox.
J'espère que vous avez compris??
Merci de votre aide
si j'ai bien compris, tout est simple tu cré une methode qui retourne une string et tu la recupere dans ta classe ou tu as instancier la classe
Dans ce cas il te suffit de détecter l'évènement de sélection de ta JComboBox et d'en récupérer l'objet sélectionné (dans ton cas un String) à l'aide de la méthode getSelectedItem() et tu la donnes à ta 2ème classe par l'intermédiaire d'une méthode du genre :
Code:
1
2
3
4 public void envoieChaine(String maChaine) { // Envoie de la chaine }
hein?
La j'ai rien compris à ce que tu me dis dsl
en gros je choisi dans ma combobox le texte que je veut (dans ma 1er classe)
et avec ma 2em classe j'envoie ce contenue vers un autre pc
voila
Une fois que tu as choisi le texte de ta JComboBox il faut le récupérer et pour ça il faut faire :
Ensuite tu dois la passer à ta deuxième classe qui va se charger de faire le transfert sur l'autre PC.Code:
1
2 String maChaine = (String)(maComboBox.getSelectedItem());
Je suppose donc que tu as déjà une méthode dans ta 2ème classe qui te permet d'envoyer une chaine de caractère, non ?
Si oui, elle doit prendre en argument un objet de type String et donc tu l'appeleras depuis ta classe principale avec la chaine sélectionnée.
Donc en gros tu as :
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 class Principale { private JComboBox _maComboBox; private MaDeuxiemeClasse _deuxiemeClasse; public void comboBoxChanged() { String maChaineSelectionnee = (String)(maComboBox.getItemSelected()); _deuxiemeClasse.envoie(maChaineSelectionnee); } } class MaDeuxiemeClasse { public void envoie(String maChaine) { // Envoie de la chaine .... } }
Une fois que ça sera fait, il te faudra détecter à quel moment la sélection de la JComboBox a été modifiée, pour ça il te faut un listener sur cette dernière, cf. :
http://www.developpez.net/forums/sho...d.php?t=190313
J'espère avoir été plus clair :roll:
merci c'est très claire, mais avec cette méthode si j'ai plusieurs combobox, j'ai donc plusieurs chaine de caractère à envoier je fait de la meme manière ou pas?
Merci en tout cas de ta réponse
Si tu en as plusieurs tu pourrais par exemple faire en sorte que l'utilisateur sélectionne toutes les chaines souhaitées dans les différentes JComboBox et ensuite clique sur un bouton qui aura pour effet de les récupérer et de les envoyer une par une.
Donc tu auras lors du clique sur le bouton :
Où tu peux également concaténer les différentes chaines et envoyer le résultat :Code:
1
2
3
4
5
6
7
8
9 String maChaineSelectionnee; maChaineSelectionnee = (String)(maComboBox1.getItemSelected()); _deuxiemeClasse.envoie(maChaineSelectionnee); maChaineSelectionnee = (String)(maComboBox2.getItemSelected()); _deuxiemeClasse.envoie(maChaineSelectionnee); maChaineSelectionnee = (String)(maComboBox3.getItemSelected()); _deuxiemeClasse.envoie(maChaineSelectionnee); ....
Code:
1
2
3
4
5
6
7 String maChaine; maChaine = (String)(maComboBox1.getItemSelected()); maChaine = maChaine + (String)(maComboBox2.getItemSelected()); maChaine = maChaine + (String)(maComboBox3.getItemSelected()); .... _deuxiemeClasse.envoie(maChaine);
ok merci bien;
Mais pour le :
_deuxiemeClasse.envoie(maChaineSelectionnee);
Netbeans me met une erreur
et je sais pas pourquoi voici ce que j'ai fait :
1er classe :
2em classe :Code:
1
2
3
4 private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { String maChaineSelectionnee = (String)(jComboBox1.getSelectedItem()); _readwrite.envoie(maChaineSelectionnee); }
Code:
1
2
3
4
5 public void serialEvent(SerialPortEvent event,String maChaineSelectionnee) { ............//envoi chaine }
voici les erreurs :
Code:
1
2
3
4
5
6
7
8
9 Compiling 2 source files to /home/ami01/NetBeansProjects/BlackBox/build/classes /home/ami01/NetBeansProjects/BlackBox/src/blackbox/Main.java:152: cannot find symbol symbol : method envoie(java.lang.String) location: class blackbox.readwrite _readwrite.envoie(maChaineSelectionnee); /home/ami01/NetBeansProjects/BlackBox/src/blackbox/readwrite.java:6: blackbox.readwrite is not abstract and does not override abstract method serialEvent(javax.comm.SerialPortEvent) in javax.comm.SerialPortEventListener public class readwrite implements Runnable, SerialPortEventListener 2 errors BUILD FAILED (total time: 1 second)
je vais fournir les 2 classe cela sera plus simple je crois :
1er classe : (Main)
2em classe : (readwrite)Code:
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182 package blackbox; import java.io.*; import java.util.*; import javax.comm.*; public class Main extends javax.swing.JFrame { static CommPortIdentifier portId; static Enumeration portList; SerialPort serialPort; InputStream inputStream; private readwrite _readwrite; public Main() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code"> private void initComponents() { jComboBox1 = new javax.swing.JComboBox(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jComboBox1.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBox1ItemStateChanged(evt); } }); jButton1.setText("Connection"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Lister les Ports"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jButton3.setText("Lecture"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Ecriture"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setText("Quitter"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(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) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addGap(31, 31, 31)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(205, 205, 205) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4) .addComponent(jButton1) .addComponent(jButton5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold> private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { new Read(); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { jTextArea1.setText(""); jComboBox1.removeAllItems(); jTextArea1.append("Début création liste des Ports\n"); portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); jComboBox1.addItem(portId.getName()+" "+portId); System.out.println(portId); } jTextArea1.append("Fin création liste des Ports\n"); System.out.println(jComboBox1.getSelectedItem()); System.out.println(portId); } private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) { new readwrite(); } private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) { String maChaineSelectionnee = (String)(jComboBox1.getSelectedItem()); _readwrite.envoie(maChaineSelectionnee); } private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) { System.exit(1); } private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) { } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Main().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JComboBox jComboBox1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration }
et voilaCode:
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 package blackbox; import java.io.*; import java.util.*; import javax.comm.*; public class readwrite implements Runnable, SerialPortEventListener { static CommPortIdentifier portId; static Enumeration portList; InputStream inputStream; SerialPort serialPort; Thread readThread; static OutputStream outputStream; public static void main(String[] args) { readwrite reader = new readwrite(); } public readwrite() { boolean portFound = false; String defaultPort = "/dev/ttyS0"; portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals(defaultPort)) { System.out.println("Found port: "+defaultPort); portFound = true; try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); System.out.println(portId); inputStream = serialPort.getInputStream(); serialPort.addEventListener(this); serialPort.notifyOnDataAvailable(true); serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE); outputStream = serialPort.getOutputStream(); outputStream.write("+++".getBytes()); readThread = new Thread(this); readThread.start(); } catch (PortInUseException e) { } catch (IOException e) { } catch (TooManyListenersException e) { } catch (UnsupportedCommOperationException e) { } } } } } public void run() { try { Thread.sleep(20000); } catch (InterruptedException e) {} } @SuppressWarnings("empty-statement") public void serialEvent(SerialPortEvent event,String maChaineSelectionnee) { switch (event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: String chaine = ""; byte[] readBuffer = new byte[20]; try { outputStream.write("maChaineSelectionnee\n\r".getBytes()); try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char)readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} } catch (IOException e) {} try { outputStream.write("ATS201?\n\r".getBytes()); try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char)readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} } catch (IOException e) {} try { outputStream.write("ATS202?\n\r".getBytes()); try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char)readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} } catch (IOException e) {} } } }
La méthode d'envoie que tu appelles dans la première classe est envoie alors qu'en fait tu la appellée serialEvent dans la deuxième.
De plus je ne sais pas d'où tu as sortie la méthode serialEvent mais elle prend également un SerialPortEvent comme premier argument, donc il faut le renseigner.
Il n'y a pas lieu d'avoir la méthode public static void main(String[] args) dans la 2ème classe.
Tu ne dois pas modifier les arguments de la méthode serialEvent puisqu'elle provient de l'interface SerialPortEventListener
Cette méthode te permet de détecter un évènement sur le port série (comme par exemple, une arrivée de donnée). Donc ce n'est pas dedans que tu dois envoyer la chaine. Tu dois écrire une nouvelle méthode dans laquelle tu pourras y mettre le code que tu as déjà écris dans la section case SerialPortEvent.DATA_AVAILABLE
maintenant je suis occupé de voir pour faire auttrement avec 3 classe
la première main
la deuxieme pour me connecter au port
et la troisième pour envoier les données
mais j'ai une erreur dans ma troisième ggggggrrrrrrrr
hum hum ok a ce que tu m'a dit mais je vois pas trop comment faire exactement
J'ai l'impression que ce que tu ne vois pas c'est l'enchainement d'appels des méthodes entre objets ? (ce qui n'est pas anormal si tu es débutant dans la programmation objet)
Déjà je ne vois pas pourquoi faire 3 classes, 2 sont bien suffisantes :
une pour le main (avec l'interface graphique) et une autre pour toute la gestion du port série (initialisation, envoie et réception).
Dans la deuxième classe il te suffit d'ajouter:
Code:
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 public void envoie(String maChaineSelectionnee) { String chaine = ""; byte[] readBuffer = new byte[20]; try { outputStream.write("maChaineSelectionnee\n\r".getBytes()); try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char)readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} } catch (IOException e) {} try { outputStream.write("ATS201?\n\r".getBytes()); try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char)readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} } catch (IOException e) {} try { outputStream.write("ATS202?\n\r".getBytes()); try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char)readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} } catch (IOException e) {} } }
Je n'ai pas vérifier si ton code pour l'envoie était correct, je te laisse maitre de cette partie.
ok ca marche je vais tester cela merci a vous
Me revoila alors voici mes 2 classes
Main :
PortComManager :Code:
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 import java.io.*; import java.util.*; import javax.comm.*; public class Main extends javax.swing.JFrame { private PortComManager manager; public Main() { manager = new PortComManager(); initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jComboBox1 = new javax.swing.JComboBox(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jButton3 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jComboBox1.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBox1ItemStateChanged(evt); } }); jButton1.setText("Connection"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setText("Lister les Ports"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jTextArea1.setColumns(20); jTextArea1.setRows(5); jScrollPane1.setViewportView(jTextArea1); jButton3.setText("Lecture"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton4.setText("Ecriture"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setText("Quitter"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(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) .addGroup(layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jComboBox1, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton2, javax.swing.GroupLayout.Alignment.LEADING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, 142, Short.MAX_VALUE) .addGap(31, 31, 31)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(205, 205, 205) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jButton3) .addComponent(jButton4) .addComponent(jButton1) .addComponent(jButton5)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed manager.init(); }//GEN-LAST:event_jButton1ActionPerformed private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed jTextArea1.setText(""); jComboBox1 = null; jTextArea1.append("Début création liste des Ports\n"); jComboBox1 = new javax.swing.JComboBox(PortComManager.getPortList().toArray()); jTextArea1.append("Fin création liste des Ports\n"); }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed jTextArea1.setText(manager.read()); }//GEN-LAST:event_jButton3ActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed manager.write(jComboBox1.getSelectedItem().toString()); }//GEN-LAST:event_jButton4ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed System.exit(1); }//GEN-LAST:event_jButton5ActionPerformed private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged manager.setPortId((CommPortIdentifier)jComboBox1.getSelectedItem()); }//GEN-LAST:event_jComboBox1ItemStateChanged public static void main(String args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Main().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JComboBox jComboBox1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea jTextArea1; // End of variables declaration//GEN-END:variables }
Le souci est que quand je clique sur mon jbutton2 la combobox ne se rempli pas et pas de message d'erreur pouvez vous m'aider?Code:
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 import java.io.*; import java.util.*; import javax.comm.*; public class PortComManager implements SerialPortEventListener { public static String defaultPort="/dev/ttyS0"; private SerialPort serialPort; private InputStream inputStream; private OutputStream outputStream; private CommPortIdentifier portId; public PortComManager() { boolean portFound = false; Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { portId = (CommPortIdentifier) portList.nextElement(); if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) { if (portId.getName().equals(defaultPort)) { System.out.println("Found port: "+defaultPort); portFound = true; this.init(); } } } if (!portFound) { System.out.println("port " + defaultPort + " not found."); } } public void init() { try { serialPort = (SerialPort) portId.open("SimpleReadApp", 2000); } catch (PortInUseException e) {} try { inputStream = serialPort.getInputStream(); } catch (IOException e) {} try { serialPort.addEventListener(this); } catch (TooManyListenersException e) {} serialPort.notifyOnDataAvailable(true); try { serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); } catch (UnsupportedCommOperationException e) {} try { outputStream = serialPort.getOutputStream(); } catch (IOException e) {} try { outputStream.write("+++".getBytes()); } catch (IOException e) {} } public CommPortIdentifier getPortId() { return this.portId; } public void setPortId(CommPortIdentifier portId){ this.portId = portId; } public static List<CommPortIdentifier> getPortList() { List list = new ArrayList(); Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { list.add((CommPortIdentifier) portList.nextElement()); } return list; } public void write(String data) { } public String read() { try { inputStream = serialPort.getInputStream(); } catch (IOException e) {} String chaine = ""; byte[] readBuffer = new byte[20]; try { while (inputStream.available() > 0) { int numBytes = inputStream.read(readBuffer); for(int i=0; i<numBytes; i++) { chaine = chaine + (char) readBuffer[i]; } } System.out.println(chaine); } catch (IOException e) {} return chaine; } public void serialEvent(SerialPortEvent arg0) { } }
Merci
As-tu vérifié si la méthode PortComManager.getPortList() te retournait les données attendues ?
c'est bon j'ai réussi à trouver pour cela maintenant j'aimerai que quand je clique sur le bouton 3 je puisse recevoir les données d'un autre pc
Merci à voici
Réponse pour la combobox :
Main :
PortComManager :Code:
1
2
3
4
5
6
7
8
9
10
11
12 private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed jTextArea1.setText(""); jComboBox1.removeAllItems(); jTextArea1.append("Début création liste des Ports\n"); System.out.println(PortComManager.getPortList()); System.out.println(PortComManager.getPortList().toArray()); for (Object o : PortComManager.getPortList()) { jComboBox1.addItem(o); } jTextArea1.append("Fin création liste des Ports\n"); }
Code:
1
2
3
4
5
6
7
8
9
10
11 public static List<CommPortIdentifier> getPortList() { List<CommPortIdentifier> list = new ArrayList<CommPortIdentifier>(); Enumeration portList = CommPortIdentifier.getPortIdentifiers(); while (portList.hasMoreElements()) { list.add((CommPortIdentifier) portList.nextElement()); } return list; }