lập trình khô khan như vậy thì góp vui gì đây chứ, tớ đg học Java muốn học hỏi các Pro nhiều
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class Bai01JFC extends JPanel implements ActionListener
{
JLabel label1,label2,label3;
JTextField textField1, textField2,result;
JButton add, sub, mul, div, exit;
//---------khoi tao JPanel va add cac Component vao do-----------
public Bai01JFC()
{
GridBagLayout layout = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints ();
setLayout(layout);
//cac nut cach nhau 2 pixel
gbc.insets = new Insets(4,4,4,4);
//cac nut nhan thay doi kich thuoc theo ca hai chieu
gbc.fill = GridBagConstraints.BOTH;
label1 = new JLabel("Input a: ");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 1;
layout.setConstraints(label1,gbc);
textField1 = new JTextField();
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 3;
gbc.gridheight = 1;
layout.setConstraints(textField1,gbc);
label2 = new JLabel("Input b: ");
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.gridheight = 1;
layout.setConstraints(label2,gbc);
textField2 = new JTextField();
gbc.gridx = 2;
gbc.gridy = 2;
gbc.gridwidth = 3;
gbc.gridheight = 1;
layout.setConstraints(textField2,gbc);
label3 = new JLabel("Result: ");
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.gridheight = 1;
layout.setConstraints(label3,gbc);
result = new JTextField();
gbc.gridx = 2;
gbc.gridy = 3;
gbc.gridwidth = 3;
gbc.gridheight = 1;
layout.setConstraints(result,gbc);
add = new JButton("Addition");
add.addActionListener(this);
add.setMnemonic(KeyEvent.VK_A);
gbc.gridx = 1;
gbc.gridy = 5;
gbc.gridwidth = 2;
gbc.gridheight = 2;
layout.setConstraints(add,gbc);
sub = new JButton("Subtraction");
sub.addActionListener(this);
sub.setMnemonic(KeyEvent.VK_S);
gbc.gridx = 3;
gbc.gridy = 5;
gbc.gridwidth = 2;
gbc.gridheight = 2;
layout.setConstraints(sub,gbc);
mul = new JButton("Multiplication");
mul.addActionListener(this);
mul.setMnemonic(KeyEvent.VK_M);
gbc.gridx = 1;
gbc.gridy = 7;
gbc.gridwidth = 2;
gbc.gridheight = 2;
layout.setConstraints(mul,gbc);
div = new JButton("Division");
div.addActionListener(this);
div.setMnemonic(KeyEvent.VK_D);
gbc.gridx = 3;
gbc.gridy = 7;
gbc.gridwidth = 2;
gbc.gridheight = 2;
layout.setConstraints(div,gbc);
exit = new JButton("Exit");
exit.addActionListener(this);
exit.setMnemonic(KeyEvent.VK_E);
gbc.gridx = 2;
gbc.gridy = 9;
gbc.gridwidth = 2;
gbc.gridheight = 2;
layout.setConstraints(exit,gbc);
add(label1); add(textField1);
add(label2); add(textField2);
add(label3); add(result);
add(add); add(sub); add(mul); add(div); add(exit);
}
//--------kiem tra input co phai la so khong--------//
public boolean isNumber (String s)
{
char c[] = s.toCharArray();
for (int i = 0; i < c.length; i++)
{
char d = c[i];
if (!Character.isDigit(d))
return false;
}
return true;
}
//-------phuong thuc su ly su kien xay ra khi nhan nut--------
public void actionPerformed(ActionEvent e)
{
String sa = textField1.getText();
String sb = textField2.getText();
if (e.getActionCommand().equals("Addition"))
{
if ((sa == null)||(sa.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number a");
else if ((sb == null)||(sb.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number b");
else if (!isNumber(sa)||!isNumber(sb))
JOptionPane.showMessageDialog(this,"You have to input numbers");
else
{
double da = Double.parseDouble(sa);
double db = Double.parseDouble(sb);
double re = da + db;
result.setText(String.valueOf(re));
}
}
else if (e.getActionCommand().equals("Subtraction"))
{
if ((sa == null)||(sa.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number a");
else if ((sb == null)||(sb.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number b");
else if (!isNumber(sa)||!isNumber(sb))
JOptionPane.showMessageDialog(this,"You have to input numbers");
else
{
double da = Double.parseDouble(sa);
double db = Double.parseDouble(sb);
double re = da - db;
result.setText(String.valueOf(re));
}
}
else if (e.getActionCommand().equals("Multiplication"))
{
if ((sa == null)||(sa.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number a");
else if ((sb == null)||(sb.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number b");
else if (!isNumber(sa)||!isNumber(sb))
JOptionPane.showMessageDialog(this,"You have to input numbers");
else
{
double da = Double.parseDouble(sa);
double db = Double.parseDouble(sb);
double re = da * db;
result.setText(String.valueOf(re));
}
}
else if (e.getActionCommand().equals("Division"))
{
if ((sa == null)||(sa.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number a");
else if ((sb == null)||(sb.equals("")))
JOptionPane.showMessageDialog(this,"Please enter number b");
else if (!isNumber(sa)||!isNumber(sb))
JOptionPane.showMessageDialog(this,"You have to input numbers");
else
{
double da = Double.parseDouble(sa);
double db = Double.parseDouble(sb);
if (db==0)
JOptionPane.showMessageDialog(this,"Number b has to differ from 0");
else{
double re = da / db;
result.setText(String.valueOf(re));
}
}
}
else if (e.getActionCommand().equals("Exit"))
{
System.exit(0);
}
}
//----------------Tao Container--------------//
public static void creatAndShowGUI()
{
JFrame frame = new JFrame("Demo 1");
frame.setBounds(50,50,300,300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Bai01JFC bai01 = new Bai01JFC();
frame.setContentPane(bai01);
frame.setVisible(true);
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
creatAndShowGUI();
}
});
}
}
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.lang.Math;
public class Bai02JFC extends JPanel implements ActionListener
{
private boolean operatorState; //trang thai phep toan
private int operator; //toan tu thuc hien
private float oldIterator; //so hang truoc
private JLabel lbl;
private JPanel pnl;
private JButton btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9,
btnPoint, btnReset, btnAdd, btnSub, btnMul, btnDiv, btnPow,
btnSqrt, btnRev,btnResult, btnSin, btnCos, btnTg, btnNeg, btnPI;
public Bai02JFC()
{
setLayout(null);
lbl = new JLabel("0"); //mac dinh ket qua = 0
lbl.setBounds(15,20,200,20);
add(lbl);
JPanel pnl = new JPanel();
pnl.setSize(300,200);
pnl.setLocation(15,60);
pnl.setLayout(new GridLayout(5,6));
add(pnl);
btn5 = new JButton("5");
btn5.addActionListener(this);
pnl.add(btn5);
btn6 = new JButton("6");
btn6.addActionListener(this);
pnl.add(btn6);
btn7 = new JButton("7");
btn7.addActionListener(this);
pnl.add(btn7);
btn8 = new JButton("8");
btn8.addActionListener(this);
pnl.add(btn8);
btn9 = new JButton("9");
btn9.addActionListener(this);
pnl.add(btn9);
btn0 = new JButton("0");
btn0.addActionListener(this);
pnl.add(btn0);
btn1 = new JButton("1");
btn1.addActionListener(this);
pnl.add(btn1);
btn2 = new JButton("2");
btn2.addActionListener(this);
pnl.add(btn2);
btn3 = new JButton("3");
btn3.addActionListener(this);
pnl.add(btn3);
btn4 = new JButton("4");
btn4.addActionListener(this);
pnl.add(btn4);
btnNeg = new JButton("-/+");
btnNeg.addActionListener(this);
pnl.add(btnNeg);
btnAdd = new JButton("+");
btnAdd.addActionListener(this);
pnl.add(btnAdd);
btnSub = new JButton("-");
btnSub.addActionListener(this);
pnl.add(btnSub);
btnMul = new JButton("*");
btnMul.addActionListener(this);
pnl.add(btnMul);
btnDiv = new JButton("/");
btnDiv.addActionListener(this);
pnl.add(btnDiv);
btnSin = new JButton("Sin");
btnSin.addActionListener(this);
pnl.add(btnSin);
btnCos = new JButton("Cos");
btnCos.addActionListener(this);
pnl.add(btnCos);
btnTg = new JButton("Tg");
btnTg.addActionListener(this);
pnl.add(btnTg);
btnPI = new JButton("PI");
btnPI.addActionListener(this);
pnl.add(btnPI);
btnSqrt = new JButton("Sqrt");
btnSqrt.addActionListener(this);
pnl.add(btnSqrt);
btnResult = new JButton("=");
btnResult.addActionListener(this);
pnl.add(btnResult);
btnPow = new JButton("x^y");
btnPow.addActionListener(this);
pnl.add(btnPow);
btnRev = new JButton("1/x");
btnRev.addActionListener(this);
pnl.add(btnRev);
btnPoint = new JButton(".");
btnPoint.addActionListener(this);
pnl.add(btnPoint);
btnReset = new JButton("C");
btnReset.addActionListener(this);
pnl.add(btnReset);
operatorState = true;
operator = -1;
oldIterator = 0;
}
public void actionPerformed(ActionEvent ae)
{
float result;
float newIterator = Float.parseFloat(lbl.getText());
if (ae.getSource()==btnResult)
{
switch(operator)
{
case 0:
result = oldIterator + newIterator;
lbl.setText(String.valueOf(result));
break;
case 1:
result = oldIterator - newIterator;
lbl.setText(String.valueOf(result));
break;
case 2:
result = oldIterator * newIterator;
lbl.setText(String.valueOf(result));
break;
case 3:
if (newIterator != 0)
{ result = oldIterator / newIterator;
lbl.setText(String.valueOf(result));
}
break;
case 4:
result = (float)Math.pow(oldIterator,newIterator);
lbl.setText(String.valueOf(result));
break;
}
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource() == btnRev)
{
newIterator = Float.parseFloat(lbl.getText());
if (newIterator != 0)
{
result = (float)1/newIterator;
lbl.setText(String.valueOf(result));
}
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource()==btnPI)
{
float tmp = (float)Math.PI;
if (operatorState)
{
lbl.setText(String.valueOf(tmp));
operatorState = false;
}
else
{
result = tmp;
lbl.setText(String.valueOf(result));
operator = -1;
operatorState = true;
return ;
}
}
if (ae.getSource()==btnSin)
{
newIterator = Float.parseFloat(lbl.getText());
result = (float)Math.sin(newIterator);
lbl.setText(String.valueOf(result));
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource()==btnCos)
{
result = (float)Math.cos(Double.parseDouble(lbl.getText()));
lbl.setText(String.valueOf(result));
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource()==btnTg)
{
newIterator = Float.parseFloat(lbl.getText());
if (newIterator % (float)Math.PI == (float)Math.PI/2)
JOptionPane.showMessageDialog(this,"Can't compute");
else
{
result = (float)Math.tan(newIterator);
lbl.setText(String.valueOf(result));
}
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource()==btnNeg)
{
newIterator = Float.parseFloat(lbl.getText());
result = -newIterator;
lbl.setText(String.valueOf(result));
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource() == btnSqrt)
{
newIterator = Float.parseFloat(lbl.getText());
if (newIterator >= 0)
{
result = (float)Math.sqrt(newIterator);
lbl.setText(String.valueOf(result));
}
else
JOptionPane.showMessageDialog(this,"The number is smaller than 0");
operator = -1;
operatorState = true;
return ;
}
if (ae.getSource() == btnPoint)
{
String tmp = lbl.getText();
if (tmp.contains("."))
{ JOptionPane.showMessageDialog(this,"Illigal number");
lbl.setText(tmp);
}
else
lbl.setText(tmp+".");
return ;
}
if (ae.getSource()==btnAdd)
{
operator = 0;
operatorState = true;
oldIterator = Float.parseFloat(lbl.getText());
return ;
}
if (ae.getSource()==btnSub)
{
operator = 1;
operatorState = true;
oldIterator = Float.parseFloat(lbl.getText());
return ;
}
if (ae.getSource()==btnMul)
{
operator = 2;
operatorState = true;
oldIterator = Float.parseFloat(lbl.getText());
return ;
}
if (ae.getSource()==btnDiv)
{
operator = 3;
operatorState = true;
oldIterator = Float.parseFloat(lbl.getText());
return ;
}
if (ae.getSource()==btnPow)
{
operator = 4;
operatorState = true;
oldIterator = Float.parseFloat(lbl.getText());
return ;
}
if (ae.getSource()==btnReset)
{
operator = -1;
operatorState = true;
oldIterator = 0;
lbl.setText("0");
return ;
}
if (operatorState)
{
lbl.setText(ae.getActionCommand());
operatorState = false;
}
else
{
if (ae.getSource()==btnPI)
lbl.setText(String.valueOf((float)Math.PI));
else
lbl.setText(lbl.getText()+ae.getActionCommand());
}
}
public static void create()
{
JFrame frame = new JFrame ("Caculator");
frame.setBounds(50,50,350,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Bai02JFC bai02 = new Bai02JFC();
frame.setContentPane(bai02);
frame.setVisible(true);
}
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
create();
}
});
}
}
import java.lang.*;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
public class TCPChat implements Runnable {
// Khoi tao cac trang thai ket noi.
public final static int NULL = 0;
public final static int DISCONNECTED = 1;
public final static int DISCONNECTING = 2;
public final static int BEGIN_CONNECT = 3;
public final static int CONNECTED = 4;
// Khoi tao mot so hang so.
public final static String statusMessages[] = {
" Error! Could not connect!", " Disconnected",
" Disconnecting...", " Connecting...", " Connected"
};
public final static TCPChat tcpObj = new TCPChat();
public final static String END_CHAT_SESSION =
new Character((char)0).toString(); // Ket thuc phien chat.
// Thong tin ket noi.
public static String hostIP = "localhost";
public static int port = 1234;
public static int connectionStatus = DISCONNECTED;
public static boolean isHost = true;
public static String statusString = statusMessages[connectionStatus];
public static StringBuffer toAppend = new StringBuffer("");
public static StringBuffer toSend = new StringBuffer("");
// Khai báo các thành phan giao dien
public static JFrame mainFrame = null;
public static JTextArea chatText = null;
public static JTextField chatLine = null;
public static JPanel statusBar = null;
public static JLabel statusField = null;
public static JTextField statusColor = null;
public static JTextField ipField = null;
public static JTextField portField = null;
public static JRadioButton hostOption = null;
public static JRadioButton guestOption = null;
public static JButton connectButton = null;
public static JButton disconnectButton = null;
// Khai báo các thành phan TCP
public static ServerSocket hostServer = null;
public static Socket socket = null;
public static BufferedReader in = null;
public static PrintWriter out = null;
/////////////////////////////////////////////////////////////////
private static JPanel initOptionsPane() {
JPanel pane = null;
ActionAdapter buttonListener = null;
// Tao JPanel
JPanel optionsPane = new JPanel(new GridLayout(4, 1));
// IP
pane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
pane.add(new JLabel("Host IP:"));
ipField = new JTextField(10); ipField.setText(hostIP);
ipField.setEnabled(false);
ipField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
ipField.selectAll();
// khi ngat ket noi moi dc sua.
if (connectionStatus != DISCONNECTED) {
changeStatusNTS(NULL, true);
}
else {
hostIP = ipField.getText();
}
}
});
pane.add(ipField);
optionsPane.add(pane);
// Cong.
pane = new JPanel(new FlowLayout(FlowLayout.RIGHT));
pane.add(new JLabel("Port:"));
portField = new JTextField(10); portField.setEditable(true);
portField.setText((new Integer(port)).toString());
portField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent e) {
// chi duoc sua khi da ngat ket noi.
if (connectionStatus != DISCONNECTED) {
changeStatusNTS(NULL, true);
}
else {
int temp;
try {
temp = Integer.parseInt(portField.getText());
port = temp;
}
catch (NumberFormatException nfe) {
portField.setText((new Integer(port)).toString());
mainFrame.repaint();
}
}
}
});
pane.add(portField);
optionsPane.add(pane);
// lua chon host cua Guest
buttonListener = new ActionAdapter() {
public void actionPerformed(ActionEvent e) {
if (connectionStatus != DISCONNECTED) {
changeStatusNTS(NULL, true);
}
else {
isHost = e.getActionCommand().equals("host");
// Khong the sua host neu da duoc chon.
if (isHost) {
ipField.setEnabled(false);
ipField.setText("localhost");
hostIP = "localhost";
}
else {
ipField.setEnabled(true);
}
}
}
};
ButtonGroup bg = new ButtonGroup();
hostOption = new JRadioButton("Host", true);
hostOption.setMnemonic(KeyEvent.VK_H);
hostOption.setActionCommand("host");
hostOption.addActionListener(buttonListener);
guestOption = new JRadioButton("Guest", false);
guestOption.setMnemonic(KeyEvent.VK_G);
guestOption.setActionCommand("guest");
guestOption.addActionListener(buttonListener);
bg.add(hostOption);
bg.add(guestOption);
pane = new JPanel(new GridLayout(1, 2));
pane.add(hostOption);
pane.add(guestOption);
optionsPane.add(pane);
// Nut ket noi va ngat ket noi.
JPanel buttonPane = new JPanel(new GridLayout(1, 2));
buttonListener = new ActionAdapter() {
public void actionPerformed(ActionEvent e) {
// Yeu cau khoi tao ket noi.
if (e.getActionCommand().equals("connect")) {
changeStatusNTS(BEGIN_CONNECT, true);
}
// Ngat ket noi.
else {
changeStatusNTS(DISCONNECTING, true);
}
}
};
connectButton = new JButton("Connect");
connectButton.setMnemonic(KeyEvent.VK_C);
connectButton.setActionCommand("connect");
connectButton.addActionListener(buttonListener);
connectButton.setEnabled(true);
disconnectButton = new JButton("Disconnect");
disconnectButton.setMnemonic(KeyEvent.VK_D);
disconnectButton.setActionCommand("disconnect");
disconnectButton.addActionListener(buttonListener);
disconnectButton.setEnabled(false);
buttonPane.add(connectButton);
buttonPane.add(disconnectButton);
optionsPane.add(buttonPane);
return optionsPane;
}
/////////////////////////////////////////////////////////////////
// Khoi tao giao dien.
private static void initGUI() {
// Cai dat trang thai.
statusField = new JLabel();
statusField.setText(statusMessages[DISCONNECTED]);
statusColor = new JTextField(1);
statusColor.setBackground(Color.red);
statusColor.setEditable(false);
statusBar = new JPanel(new BorderLayout());
statusBar.add(statusColor, BorderLayout.WEST);
statusBar.add(statusField, BorderLayout.CENTER);
JPanel optionsPane = initOptionsPane();
// Cai dat panel chat
JPanel chatPane = new JPanel(new BorderLayout());
chatText = new JTextArea(10, 20);
chatText.setLineWrap(true);
chatText.setEditable(false);
chatText.setForeground(Color.blue);
JScrollPane chatTextPane = new JScrollPane(chatText,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
chatLine = new JTextField();
chatLine.setEnabled(false);
chatLine.addActionListener(new ActionAdapter() {
public void actionPerformed(ActionEvent e) {
String s = chatLine.getText();
if (!s.equals("")) {
appendToChatBox("OUTGOING: " + s + "\n");
chatLine.selectAll();
// Gui tin chat
sendString(s);
}
}
});
chatPane.add(chatLine, BorderLayout.SOUTH);
chatPane.add(chatTextPane, BorderLayout.CENTER);
chatPane.setPreferredSize(new Dimension(200, 200));
// Cài dat panel chính
JPanel mainPane = new JPanel(new BorderLayout());
mainPane.add(statusBar, BorderLayout.SOUTH);
mainPane.add(optionsPane, BorderLayout.WEST);
mainPane.add(chatPane, BorderLayout.CENTER);
// Cài dat Frame chính
mainFrame = new JFrame("Simple TCP Chat");
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setContentPane(mainPane);
mainFrame.setSize(mainFrame.getPreferredSize());
mainFrame.setLocation(200, 200);
mainFrame.pack();
mainFrame.setVisible(true);
}
/////////////////////////////////////////////////////////////////
// thay doi trang thái
private static void changeStatusTS(int newConnectStatus, boolean noError) {
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
// Neu co loi thong bao o phan trang thai.
if (noError) {
statusString = statusMessages[connectionStatus];
}
else {
statusString = statusMessages[NULL];
}
SwingUtilities.invokeLater(tcpObj);
}
//////////////////////////////////
private static void changeStatusNTS(int newConnectStatus, boolean noError) {
if (newConnectStatus != NULL) {
connectionStatus = newConnectStatus;
}
if (noError) {
statusString = statusMessages[connectionStatus];
}
else {
statusString = statusMessages[NULL];
}
tcpObj.run();
}
/////////////////////////////////////////////////////////////////
private static void appendToChatBox(String s) {
synchronized (toAppend) {
toAppend.append(s);
}
}
/////////////////////////////////////////////////////////////////
private static void sendString(String s) {
synchronized (toSend) {
toSend.append(s + "\n");
}
}
/////////////////////////////////////////////////////////////////
private static void cleanUp() {
try {
if (hostServer != null) {
hostServer.close();
hostServer = null;
}
}
catch (IOException e) {
hostServer = null;
}
try {
if (socket != null) {
socket.close();
socket = null;
}
}
catch (IOException e) { socket = null; }
try {
if (in != null) {
in.close();
in = null;
}
}
catch (IOException e) {
in = null;
}
if (out != null) {
out.close();
out = null;
}
}
/////////////////////////////////////////////////////////////////
public void run() {
switch (connectionStatus) {
case DISCONNECTED:
connectButton.setEnabled(true);
disconnectButton.setEnabled(false);
ipField.setEnabled(true);
portField.setEnabled(true);
hostOption.setEnabled(true);
guestOption.setEnabled(true);
chatLine.setText(""); chatLine.setEnabled(false);
statusColor.setBackground(Color.red);
break;
case DISCONNECTING:
connectButton.setEnabled(false);
disconnectButton.setEnabled(false);
ipField.setEnabled(false);
portField.setEnabled(false);
hostOption.setEnabled(false);
guestOption.setEnabled(false);
chatLine.setEnabled(false);
statusColor.setBackground(Color.orange);
break;
case CONNECTED:
connectButton.setEnabled(false);
disconnectButton.setEnabled(true);
ipField.setEnabled(false);
portField.setEnabled(false);
hostOption.setEnabled(false);
guestOption.setEnabled(false);
chatLine.setEnabled(true);
statusColor.setBackground(Color.green);
break;
case BEGIN_CONNECT:
connectButton.setEnabled(false);
disconnectButton.setEnabled(false);
ipField.setEnabled(false);
portField.setEnabled(false);
hostOption.setEnabled(false);
guestOption.setEnabled(false);
chatLine.setEnabled(false);
chatLine.grabFocus();
statusColor.setBackground(Color.orange);
break;
}
ipField.setText(hostIP);
portField.setText((new Integer(port)).toString());
hostOption.setSelected(isHost);
guestOption.setSelected(!isHost);
statusField.setText(statusString);
chatText.append(toAppend.toString());
toAppend.setLength(0);
mainFrame.repaint();
}
/////////////////////////////////////////////////////////////////
// hàm chính
public static void main(String args[]) {
String s;
initGUI();
while (true) {
try { // tam dung 10/1000 giây
Thread.sleep(10);
}
catch (InterruptedException e) {}
switch (connectionStatus) {
case BEGIN_CONNECT:
try {
// ket noi den host
if (isHost) {
hostServer = new ServerSocket(port);
socket = hostServer.accept();
}
// ket noi den server
else {
socket = new Socket(hostIP, port);
}
in = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
changeStatusTS(CONNECTED, true);
}
// Neu loi thi xuat thong bao
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case CONNECTED:
try {
// Gui du lieu.
if (toSend.length() != 0) {
out.print(toSend); out.flush();
toSend.setLength(0);
changeStatusTS(NULL, true);
}
// Nhan du lieu
if (in.ready()) {
s = in.readLine();
if ((s != null) && (s.length() != 0)) {
if (s.equals(END_CHAT_SESSION)) {
changeStatusTS(DISCONNECTING, true);
}
// Nhan tin
else {
appendToChatBox("INCOMING: " + s + "\n");
changeStatusTS(NULL, true);
}
}
}
}
catch (IOException e) {
cleanUp();
changeStatusTS(DISCONNECTED, false);
}
break;
case DISCONNECTING:
//thông báo trang thai ngat ket noi.
out.print(END_CHAT_SESSION); out.flush();
//xóa
cleanUp();
changeStatusTS(DISCONNECTED, true);
break;
default: break; // thoát
}
}
}
}
////////////////////////////////////////////////////////////////////
class ActionAdapter implements ActionListener {
public void actionPerformed(ActionEvent e) {}
}