GUI用のJavaおよびSwingクラスを使用してチャットアプリケーションを実行しています。Java Swing GUIクライアントおよびサーバーチャットアプリケーションTextAreaが更新されない
ChatServerクラスはクライアントからのメッセージを受信するサーバーになり、すべてのクライアントにエコーバックしますが、2つのクライアントのチャットのみを行います。
ChatClientクラスは、両方ともクライアントです。テキスト領域にサーバーから送信されたものを表示します。テキストフィールドのテキストをサーバーに送信します。
ChatClientクラス
package chatclient;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
public class ChatClient extends javax.swing.JFrame {
public ChatClient() {
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">
private void initComponents() {
scrollPane = new javax.swing.JScrollPane();
textArea = new javax.swing.JTextArea();
btnConnect = new javax.swing.JButton();
btnDisconnect = new javax.swing.JButton();
lblStatus = new javax.swing.JLabel();
lblShowStatus = new javax.swing.JLabel();
txtInput = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Chat Client A");
textArea.setEditable(false);
textArea.setColumns(20);
textArea.setRows(5);
textArea.setText("Welcome to the Chat Server. Type '/close' or Click 'Disconnect' to close.");
textArea.setWrapStyleWord(true);
textArea.setCaretPosition(textArea.getDocument().getLength());
scrollPane.setViewportView(textArea);
btnConnect.setText("Connect");
btnConnect.setActionCommand("btnConnect");
btnConnect.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
btnConnectMouseClicked(evt);
}
});
btnDisconnect.setText("Disconnect");
btnDisconnect.setActionCommand("btnDisconnect");
btnDisconnect.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDisconnectActionPerformed(evt);
}
});
lblStatus.setText("Status: ");
lblShowStatus.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblShowStatus.setForeground(new java.awt.Color(255, 51, 51));
lblShowStatus.setText("Disconnected");
txtInput.setToolTipText("");
txtInput.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
txtInputActionPerformed(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(scrollPane)
.addGroup(layout.createSequentialGroup()
.addComponent(btnConnect)
.addGap(18, 18, 18)
.addComponent(btnDisconnect)
.addGap(42, 42, 42)
.addComponent(lblStatus)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lblShowStatus)
.addGap(0, 42, Short.MAX_VALUE))
.addComponent(txtInput))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(scrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
.addComponent(txtInput, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnConnect)
.addComponent(btnDisconnect)
.addComponent(lblStatus)
.addComponent(lblShowStatus))
.addContainerGap())
);
pack();
}// </editor-fold>
private void btnConnectMouseClicked(java.awt.event.MouseEvent evt) {
// TODO add your handling code here:
lblShowStatus.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblShowStatus.setForeground(new java.awt.Color(0, 204, 51));
lblShowStatus.setText("Connected");
// ADD CODES FOR CONNECTING TO CHAT SERVER
}
private void btnDisconnectActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
lblShowStatus.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lblShowStatus.setForeground(new java.awt.Color(255, 51, 51));
lblShowStatus.setText("Disconnected");
// ADD CODES FOR DISCONNECTING FROM CHAT SERVER
}
private void txtInputActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
/**
* @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(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ChatClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ChatClient.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 ChatClient().setVisible(true);
}
});
String input = "", serverInput = "";
String host = "localhost";
int port = 1337;
Socket client;
// updateTextArea("TEST UPDATE");
try {
client = new Socket(host, port);
System.out.println("Connected to Server!");
DataInputStream in = new DataInputStream(client.getInputStream());
DataOutputStream out = new DataOutputStream(client.getOutputStream());
System.out.println("Before setting text area");
updateTextArea("trying to update");
do {
// HANDLE INPUT PART HERE
serverInput = in.readUTF();
if(serverInput != null) {
System.out.println("Reached here");
System.out.println(serverInput);
updateTextArea(serverInput);
}
} while(!input.equals("/close"));
System.out.println("Program closed");
}
catch(Exception exc) {
System.err.println(exc.getMessage());
}
}
private static void updateTextArea(String temp) {
textArea.setText(textArea.getText() + "\n" + temp + "\n");
textArea.setCaretPosition(textArea.getDocument().getLength());
}
// Variables declaration - do not modify
private javax.swing.JButton btnConnect;
private javax.swing.JButton btnDisconnect;
private javax.swing.JLabel lblShowStatus;
private javax.swing.JLabel lblStatus;
private javax.swing.JScrollPane scrollPane;
private static javax.swing.JTextArea textArea;
private javax.swing.JTextField txtInput;
// End of variables declaration
}
ChatServerクラス
package chatserver;
import java.io.BufferedReader;
import java.io.InputStreamReader;
// for testing
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author wacats
*/
public class ChatServer {
public static void main(String args[]) {
int port = 1337;
try {
ServerSocket server = new ServerSocket(port);
String inMessage = "";
while(true) {
Socket clientA = server.accept();
DataInputStream inA = new DataInputStream(clientA.getInputStream());
DataOutputStream outA = new DataOutputStream(clientA.getOutputStream());
// outA.writeUTF("Welcome to the Chat Server. Type '/close' or Click 'Disconnect' to close.");
// for testing
// BufferedReader user = new BufferedReader(new InputStreamReader(System.in));
do {
inMessage = inA.readUTF();
outA.writeUTF("testing");
if(inMessage != null) {
outA.writeUTF(inMessage);
}
} while(!inMessage.equals("/close"));
clientA.close();
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
このプログラムのプロセスに関する私の考えは次のとおりです。
- 起動ChatServer
- チャットクライアントの起動
- 両方のクライアントがサーバーに接続されている場合、チャットを開始できます。
- 「Enter」を押すと、テキストフィールドのテキストがサーバーに送信されます。
- サーバーは両方のクライアントにテキストをブロードキャストします。
- クライアントは、サーバーから受信したテキストを追加してテキスト領域を更新します。あなたがしようと
updateTextArea
を呼び出すとき
含めて、上に追いつくために読んだのがたくさんあります。メソッドSwingUtilities.invokeLaterによってラップされたメソッドupdateTextAreaの呼び出しを行う必要があるでしょう。 –
'static '参照を無効にします。 'setText'の上に' append'を使用してください – MadProgrammer
あなたは 'updateTextArea'に' NullPointerException'を持っています。UIが確立される前にサーバからの内容を読み書きするためのループが実行されているためです。 – MadProgrammer