Главная страница Случайная страница КАТЕГОРИИ: АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника |
frmChat.java ⇐ ПредыдущаяСтр 7 из 7
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package jChat;
import java.awt.Dimension; import java.awt.Toolkit; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane;
/** * * @author VasVas */ class Chat extends Thread{ Socket socket; PrintWriter out; BufferedReader in; frmChat frm; String IP; String PORT; String NikName; Chat(String IP, String PORT, frmChat x, String NikName){ frm=x; this.IP=IP; this.PORT=PORT; this.NikName=NikName; try{ InetAddress addr = InetAddress.getByName(IP); socket = new Socket(addr, Integer.parseInt(PORT)); try { out = new PrintWriter( new BufferedWriter( new OutputStreamWriter( socket.getOutputStream())), true); in =new BufferedReader( new InputStreamReader( socket.getInputStream())); } catch (Exception ex) { Logger.getLogger(frmChat.class.getName()).log(Level.SEVERE, null, ex); } start(); frm.txtNik.setEnabled(false); frm.jButton1.setEnabled(true); frm.jButton2.setEnabled(false); }catch(Exception ex){ System.out.println(ex); frm.jButton2.setEnabled(true); JOptionPane.showMessageDialog(frm, " Не можливо з’эднатись з сервером! "); } }
public void run(){ String str = null; do { try { str = in.readLine(); if(! str.equals(" EXIT")){ frm.txtChat.setText(frm.txtChat.getText()+" \n" +str); }else{ frm.txtChat.setText(frm.txtChat.getText()+" \n" +" Сервер завершив роботу"); frm.jButton2.setEnabled(true); frm.jButton1.setEnabled(false); frm.txtNik.setEnabled(true); cloose(); break; } }catch (IOException ex) { //System.out.println(ex); break; }
}while (! str.equals(" EXIT"));
} public void Send(String a){ out.println(NikName+": " +a); } public void cloose(){ try{ out.println(" END"); }finally{ try { socket.close(); } catch (IOException ex) { Logger.getLogger(Chat.class.getName()).log(Level.SEVERE, null, ex); }
} } } public class frmChat extends javax.swing.JFrame { private static frmChat item; public int connect=0; Chat chat; /** * Creates new form frmChat */ public static frmChat getObj(){ if(item! =null)return item;
item=new frmChat();
return item; } private frmChat() { 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() {
jScrollPane1 = new javax.swing.JScrollPane(); txtChat = new javax.swing.JTextArea(); txtMsg = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); txtIP = new javax.swing.JTextField(); jLabel2 = new javax.swing.JLabel(); txtPort = new javax.swing.JTextField(); jButton2 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); txtNik = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosed(java.awt.event.WindowEvent evt) { formWindowClosed(evt); } public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } });
txtChat.setColumns(20); txtChat.setRows(5); jScrollPane1.setViewportView(txtChat);
txtMsg.setText(" текст повідомлення...");
jButton1.setText(" Надіслати"); jButton1.setEnabled(false); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } });
jLabel1.setText(" IP: ");
txtIP.setText(" 192.168.0.101");
jLabel2.setText(" PORT: ");
txtPort.setText(" 11777");
jButton2.setText(" Підключитись"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } });
jLabel3.setText(" Ваш нік");
txtNik.setText(" РђРЅРѕРЅС–Рј");
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(jScrollPane1) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtIP, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(txtNik, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2)) .addGroup(layout.createSequentialGroup() .addComponent(txtMsg, javax.swing.GroupLayout.PREFERRED_SIZE, 322, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1))) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(txtIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel2) .addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3) .addComponent(txtNik, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 246, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtMsg, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) );
pack(); }// < /editor-fold> //GEN-END: initComponents
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST: event_jButton2ActionPerformed jButton2.setEnabled(false); chat=new Chat(txtIP.getText(), txtPort.getText(), this, txtNik.getText()); }//GEN-LAST: event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST: event_jButton1ActionPerformed // TODO add your handling code here: chat.Send(txtMsg.getText()); }//GEN-LAST: event_jButton1ActionPerformed
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST: event_formWindowClosing // TODO add your handling code here: jButton2.setEnabled(true); txtNik.setEditable(true); if(connect> 0){ chat.cloose(); } }//GEN-LAST: event_formWindowClosing
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST: event_formWindowClosed // TODO add your handling code here: }//GEN-LAST: event_formWindowClosed
/** * @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 https://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(frmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmChat.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmChat.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() { frmChat z=new frmChat(); z.setVisible(true); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); z.setLocation((screenSize.width - z.getWidth()) / 2, (screenSize.height - z.getHeight()) / 2);
} }); }
// Variables declaration - do not modify//GEN-BEGIN: variables public javax.swing.JButton jButton1; public javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JScrollPane jScrollPane1; public javax.swing.JTextArea txtChat; private javax.swing.JTextField txtIP; private javax.swing.JTextField txtMsg; public javax.swing.JTextField txtNik; private javax.swing.JTextField txtPort; // End of variables declaration//GEN-END: variables }
|