J’ai besoin d’append un keylistener je pense

J’ai ce code qui est un client de discussion qui fonctionne avec mon serveur sur lequel je travaille. Dans le champ textEnter, je le veux, ainsi, si vous appuyez sur Entrée, il effectue la même action que si vous cliquiez sur le bouton d’envoi. Si l’un de vous peut m’aider à trouver un moyen d’y parvenir, je vous en serai très reconnaissant.

package TryOne; /* Things to do * 1.fix (java.lang.ArrayIndexOutOfBoundsException: 2) "remove spaces and new lines after text" * 2.fix user names not being cleared after disconnect * 3.fix server chat logs * 4. */ import java.net.*; import java.awt.event.KeyEvent; import java.io.*; import java.util.*; import javax.swing.JTextField; public class ChatClient extends javax.swing.JFrame { static Ssortingng username; /* if user names don't copy to the field correctly remove static*/ Ssortingng serverIP = "localhost"; int Port = 13; Socket sock; BufferedReader reader; PrintWriter writer; ArrayList  userList = new ArrayList(); Boolean isConnected = false; static Boolean isPressed = false; /** Creates new form Chat */ public ChatClient() { initComponents(); } public class IncomingReader implements Runnable { public void run() { Ssortingng[] data; Ssortingng stream, done = "Done", connect = "Connect", disconnect = "Disconnect", chat = "Chat"; /*if(isPressed){ sendButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sendButtonActionPerformed(evt); System.out.println(evt); }}); isPressed = false; }*/ try { while ((stream = reader.readLine()) != null) { data = stream.split(":"); if (data[2].equals(chat)) { chatTextArea.append(data[0] + ": " + data[1] + "\n"); chatTextArea.setCaretPosition(chatTextArea .getDocument().getLength()); } else if (data[2].equals(connect)) { chatTextArea.removeAll(); userAdd(data[0]); } else if (data[2].equals(disconnect)) { userRemove(data[0]); } else if (data[2].equals(done)) { usersList.setText(""); writeUsers(); userList.clear(); } } } catch (Exception ex) {} } } public void ListenThread() { Thread IncomingReader = new Thread(new IncomingReader()); IncomingReader.start(); } public void userAdd(Ssortingng data) { userList.add(data); } public void userRemove(Ssortingng data) { chatTextArea.append(data + " has disconnected.\n"); } public void writeUsers() { Ssortingng[] tempList = new Ssortingng[(userList.size())]; userList.toArray(tempList); for (Ssortingng token: tempList) { usersList.append(token + "\n"); } } public void sendDisconnect() { Ssortingng bye = (username + ": :Disconnect"); try { writer.println(bye); // Sends server the disconnect signal. writer.flush(); // flushes the buffer } catch (Exception e) { chatTextArea.append("Could not send Disconnect message.\n"); } } public void Disconnect() { try { chatTextArea.append("Disconnected.\n"); sock.close(); } catch (Exception ex) { chatTextArea.append("Failed to disconnect. \n"); } isConnected = false; usernameField.setEditable(true); usersList.setText(""); } /** * 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") //  private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); inputTextArea = new javax.swing.JTextArea(); jScrollPane2 = new javax.swing.JScrollPane(); chatTextArea = new javax.swing.JTextArea(); jLabel1 = new javax.swing.JLabel(); usernameField = new javax.swing.JTextField(); connectButton = new javax.swing.JButton(); disconnectButton = new javax.swing.JButton(); sendButton = new javax.swing.JButton(); jScrollPane3 = new javax.swing.JScrollPane(); usersList = new javax.swing.JTextArea(); jLabel2 = new javax.swing.JLabel(); jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Chat Client"); inputTextArea.setColumns(20); inputTextArea.setLineWrap(true); inputTextArea.setRows(5); jScrollPane1.setViewportView(inputTextArea); chatTextArea.setColumns(20); chatTextArea.setEditable(false); chatTextArea.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N chatTextArea.setLineWrap(true); chatTextArea.setRows(5); jScrollPane2.setViewportView(chatTextArea); jLabel1.setText("Username:"); usernameField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { usernameFieldActionPerformed(evt); } }); connectButton.setText("Connect"); connectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { connectButtonActionPerformed(evt); } }); disconnectButton.setText("Disconnect"); disconnectButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { disconnectButtonActionPerformed(evt); } }); sendButton.setText("Send"); sendButton.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { sendButtonActionPerformed(evt); System.out.println(evt); } }); usersList.setEditable(false); usersList.setColumns(20); usersList.setRows(5); jScrollPane3.setViewportView(usersList); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Online Users"); jMenu1.setText("File"); jMenuItem1.setText("Settings"); jMenuItem1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem1ActionPerformed(evt); } }); jMenu1.add(jMenuItem1); jMenuBar1.add(jMenu1); setJMenuBar(jMenuBar1); javax.swing.GroupLayout layout = new javax.swing.GroupLayout( getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING) .addGroup( javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent( jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent( jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 419, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup( layout.createSequentialGroup() .addComponent( jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent( usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent( connectButton) .addGap(18, 18, 18) .addComponent( disconnectButton))) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.LEADING) .addComponent( jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jScrollPane3)) .addContainerGap())); layout.setVerticalGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup( layout.createSequentialGroup() .addContainerGap() .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(disconnectButton) .addComponent(connectButton) .addComponent( usernameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent( jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE) .addComponent(jLabel2)) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup( layout.createSequentialGroup() .addComponent( jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap( javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup( layout.createParallelGroup( javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent( sendButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent( jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))) .addComponent(jScrollPane3)) .addContainerGap())); pack(); } //  private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: if (isConnected == false) { username = usernameField.getText(); usernameField.setEditable(false); try { sock = new Socket(serverIP, Port); InputStreamReader streamreader = new InputStreamReader( sock.getInputStream()); reader = new BufferedReader(streamreader); writer = new PrintWriter(sock.getOutputStream()); writer.println(username + ":has connected.:Connect"); // Displays // to // everyone // that // user // connected. writer.flush(); // flushes the buffer isConnected = true; // Used to see if the client is connected. } catch (Exception ex) { chatTextArea.append("Cannot Connect! Try Again. \n"); usernameField.setEditable(true); } ListenThread(); } else if (isConnected == true) { chatTextArea.append("You are already connected. \n"); } } private void disconnectButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: sendDisconnect(); Disconnect(); } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); } private void sendButtonActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: Ssortingng nothing = ""; if ((inputTextArea.getText()).equals(nothing)) { inputTextArea.setText(""); inputTextArea.requestFocus(); } else { try { writer.println(username + ":" + inputTextArea.getText() + ":" + "Chat"); writer.flush(); // flushes the buffer } catch (Exception ex) { chatTextArea.append("Message was not sent. \n"); } inputTextArea.setText(""); inputTextArea.requestFocus(); } inputTextArea.setText(""); inputTextArea.requestFocus(); } private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: // new SettingsWindow().setVisible(true); } private void usernameFieldActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here: } /** * @param args * the command line arguments */ public static void main(Ssortingng args[]) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ChatClient().setVisible(true); } }); } // Variables declaration - do not modify private javax.swing.JTextArea chatTextArea; private javax.swing.JButton connectButton; private javax.swing.JButton disconnectButton; private javax.swing.JTextArea inputTextArea; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JMenu jMenu1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JButton sendButton; private javax.swing.JTextField usernameField; private javax.swing.JTextArea usersList; // End of variables declaration } 

    Non, n’utilisez jamais un KeyListener dans un composant texte. Ici, tout ce que vous voulez, c’est append un ActionListener à votre JTextField, le même que celui utilisé sur le bouton devrait fonctionner correctement ici.

    En fait, vous l’avez déjà fait, mais vous ne l’avez pas encore branché. Essayez de changer cela:

      usernameField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { usernameFieldActionPerformed(evt); } }); 

    à

      usernameField.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { // use the actionPerformed method you've already created for the send button sendButtonActionPerformed(evt); System.out.println(evt); } }); 

    Vous devriez également éviter d’utiliser le générateur de fenêtres NetBeans pour créer vos interfaces graphiques et coder à la main car cela vous aidera à apprendre la bibliothèque Swing.