Membuat Aplikasi Chating Sederhana Menggunakan Java

Chatting

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

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
*
* @author Haidi
*/
public class NewJFrame extends javax.swing.JFrame implements Runnable {

@Override
public void run() {
while (true){
try {
LChat.add(Server_Reader.readLine());
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}

private static class jBton {

private static void setText(String disconnection) {
throw new UnsupportedOperationException(“Not yet implemented”);
}

public jBton() {
}
}
Socket client;
ServerSocket server;
BufferedReader Server_Reader, Client_Reader;
BufferedWriter Server_Writer, Client_Writer;

/**
* Creates new form NewJFrame
*/
public NewJFrame() {
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() {

jPanel1 = new javax.swing.JPanel();
jPanel2 = new javax.swing.JPanel();
LChat = new java.awt.List();
jLabel1 = new javax.swing.JLabel();
jtxtUsername = new javax.swing.JTextField();
jBtO = new javax.swing.JButton();
jCBServer = new javax.swing.JComboBox();
jtxtChat = new javax.swing.JTextField();
jBtSend = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jPanel1.setBackground(new java.awt.Color(255, 255, 51));

jPanel2.setBackground(new java.awt.Color(0, 0, 0));

jLabel1.setFont(new java.awt.Font(“Perpetua”, 1, 36)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 255, 0));
jLabel1.setText(“HaiChat”);

jtxtUsername.setText(“Username”);

jBtO.setText(“On”);
jBtO.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtOActionPerformed(evt);
}
});

jCBServer.setModel(new javax.swing.DefaultComboBoxModel(new String[] { “Server”, “Client” }));
jCBServer.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCBServerActionPerformed(evt);
}
});

jBtSend.setText(“Send”);
jBtSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jBtSendActionPerformed(evt);
}
});

javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
jPanel2.setLayout(jPanel2Layout);
jPanel2Layout.setHorizontalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel2Layout.createSequentialGroup()
.addComponent(jtxtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(jCBServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(26, 26, 26)
.addComponent(jBtO))
.addComponent(LChat, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addComponent(jtxtChat)
.addGap(18, 18, 18)
.addComponent(jBtSend))))
.addGroup(jPanel2Layout.createSequentialGroup()
.addGap(129, 129, 129)
.addComponent(jLabel1)))
.addContainerGap(33, Short.MAX_VALUE))
);
jPanel2Layout.setVerticalGroup(
jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
.addGap(5, 5, 5)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jtxtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBtO)
.addComponent(jCBServer, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 43, Short.MAX_VALUE)
.addComponent(LChat, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jtxtChat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jBtSend))
.addGap(36, 36, 36))
);

javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);

pack();
}// </editor-fold>
private void client_connection() throws IOException {
try {
String ip =JOptionPane.showInputDialog(“Masukkan IP Address :”);
client = new Socket(ip, 2000);
jCBServer.setEnabled(false);
Server_Reader = new BufferedReader (new InputStreamReader(client.getInputStream()));
Server_Writer = new BufferedWriter (new OutputStreamWriter(client.getOutputStream()));
jBtO.setText(“Disconnection”);
}
catch (UnknownHostException ex) {
System.out.println(“Accept Failed”);
System.exit(-1);
} catch (IOException ex){
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void read_connection(){
try {
try {
try {
server = new ServerSocket(2000);
this.setTitle(“Please Wait..”);
} catch (IOException ex){
System.out.println(“Could not listen”);
System.exit(-1);
}
client = server.accept();
this.setTitle(“Connected” + client.getInetAddress());
} catch (IOException ex) {
System.out.println(“Accept Failed”);
System.exit(-1);
}
Server_Reader = new BufferedReader (new InputStreamReader(client.getInputStream()));
Server_Writer = new BufferedWriter (new OutputStreamWriter(client.getOutputStream()));
} catch (IOException ex){
System.out.println(“Read Failed”);
System.exit(-1);
}
}

private void disconnected_by_client(){
try {
client.close();
Server_Reader.close();
Server_Writer.close();
jCBServer.setEnabled(true);
jBtO.setText(“Connect”);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}

private void stopped_by_server(){
try {
Server_Reader.close();
Server_Writer.close();
jBtO.setText(“ON”);
setTitle(“Disconnect”);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);

}
}

private void jCBServerActionPerformed(java.awt.event.ActionEvent evt) {
if (jCBServer.getSelectedItem().equals(“Server”)){
jBtO.setText(“On”);
jtxtUsername.setText(“Server”);
} else {
jBtO.setText(“Connect”);
jtxtUsername.setText(“Client”);

}
// TODO add your handling code here:
}

private void jBtOActionPerformed(java.awt.event.ActionEvent evt) {
if (jBtO.getText().equals(“Connect”)){
jBtO.setText(“Disconnect”);
try {
client_connection();
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
Thread thread= new Thread(this);
thread.start();
} else if (jCBServer.getSelectedItem().equals(“Server”)){
jBtO.setText(“Off”);
read_connection();
Thread thread = new Thread(this);
thread.start();
}
// TODO add your handling code here:
}

private void jBtSendActionPerformed(java.awt.event.ActionEvent evt) {
try {
Server_Writer.write(jtxtUsername.getText() + “: ” + jtxtChat.getText());
Server_Writer.newLine();
Server_Writer.flush();
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
LChat.add(“Me : ” + jtxtChat.getText());
jtxtChat.setText(“”);

// 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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

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

@Override
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration – do not modify
private java.awt.List LChat;
private javax.swing.JButton jBtO;
private javax.swing.JButton jBtSend;
private javax.swing.JComboBox jCBServer;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JTextField jtxtChat;
private javax.swing.JTextField jtxtUsername;
// End of variables declaration
}

Terimakasih dan semoga bermanfaat.

Leave a comment