Lập trình

thuthuy

New member
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
 

hp_style

Active member
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

hi, ấy đang học java à, trường nào vậy.Cũng phải công nhận là cái môn này cũng khô khan lắm.Java tớ cũng học qua roài nè. Nhưng mà h cũng quên mất nhiều roài,học linh tinh phết ^^

Đây là 1 ví dụ đơn giản về tính tổng,hiệu, tích, thương 2 số, có giao diện đồ họa.
Mã:
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();
			}
		});
	}
}
 
Sửa lần cuối:

hp_style

Active member
Thêm 1 bài nữa nè.

bài có giao diện và chức năng như 1 cái máy tính có +,-,*,/ ,sin,cos,tag,....

Mã:
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();
			}
		});
	}
}

Chán, chẳng có mem nào học về lập trình cả, Vào học hỏi thêm mà chẳng thấy có ai cả .:d
 
Sửa lần cuối:

hp_style

Active member
TCPChat.java

Mời các bạn vào tham khảo nhé ^^
Mã:
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) {}

}
 

thuthuy

New member
đây là 1 trong những đề trắc nghiệm trong đĩa ôn tập Java tụi tớ link
bạn nào cần nữa thì mình share tiếp cả mấy môn nữa như: hệ điều hành, windows, cấu trúc rời rạc, anh văn chuyên ngành, c /c++, sql, cnpm...nói chung là bên chuyên ngành phần mềm

ko biết trường cậu thi ntn chứ thi lý thuyết như kiểu này ở trường tớ thì mệt oài, hi'...

ah cậu có theo bên c# ko?, tớ đang phải làm 3 đề tài tiểu luận bằng ngôn ngữ c#, môn Windows cb, Windows nc, công nghệ phần mềm, môn windows thì đề tài ql thư viện, còn cnpm thì tùy thầy, hi'...cậu có ý tưởng nào hay trong thiết kế giao diện như form, button... thì share nhé,
 
Sửa lần cuối:

hp_style

Active member
Đề tài tiểu luận bằng C# à, nhưng Thúy làm về cái gì, trước bọn tớ cũng làm rùi, tớ làm về quản lý sinh viên, rùi bài thức tập thì làm về quản lý thư viện bằng C#, đóng gói rùi, vẫn còn bộ cài và code nè, lấy ko bạn send cho nhé......
 

thuthuy

New member
thì tớ nói là làm về ql thư viện, bộ cài đặt thì có rồi, còn hơi bí cái giao diện thiết kế cho nó đẹp mắt tí,hi'... có thì share code cho anh em học hỏi nha,
 
Sửa lần cuối:

thuthuy

New member
tớ đang hỏi cậu về cái giao diện mà, thôi để cn này tớ nộp 1 cái tiểu luận cho thầy rồi tớ up lên tất cả coi thử ha.
 

hp_style

Active member
okie men !!! có gì up lên rùi tớ up luôn cái giao diện của tớ, hi`hi`, cái phần mà in ra ý, thì tớ in luôn ra word , cũng dc....:D
 

thuthuy

New member
đây là mấy Form ban đầu hơi chuối tí, hi'...về cách sắp xếp cũng như làm đẹp cái giao diện tớ hơi gà. uhm, cậu up lên đi cho tớ học hỏi, thanks trước nha


t1.jpg


1-10.jpg


t3.jpg
 

thuthuy

New member
Bạn muốn học C# ah, theo mình bạn nên học cuốn net framework trong cuốn này rất hay nó vừa dậy bạn viết C# và VB song song
tài liệu tiếng anh ha LINK DOWNLOAD
còn đây là bài tập
ah quên tớ thấy thầy tớ ca ngợi Share Point lắm và cũng có mấy nhóm ở khoa tớ đang làm đồ án học phần về nó đấy, nó là sự kết hợp của C# và ASP.NET, anh em ta cũng cùng học hỏi về Share Point nữa ha
 
Sửa lần cuối:

duckhai_hp

New member
c# phat trien tren c thoi hoc tot c thi c# la ok

ai có tài liệu lập trình phần mền chat giữa 2 máy tính bằng mạng lan và viết chương trình giao tiếp giữa máy tính và vđk bằng qua cổng com or usb bằng c# không?
 
Sửa lần cuối:

hp_style

Active member
Thuy ơi, bài này của thuy là ở trên mạng , Tuấn cũng down bài này về xem rùi .....:D

Đầu tiên là form đăng nhập :
67613_110686168995220_100001615134245_84750_995932_n.jpg


Form Main:
68756_110685765661927_100001615134245_84734_7053816_n.jpg


67635_110686055661898_100001615134245_84746_3964181_n.jpg


64982_110686112328559_100001615134245_84748_7342298_n.jpg


72177_110686145661889_100001615134245_84749_4191224_n.jpg


Danh mục nhân viên:
71976_110685818995255_100001615134245_84735_7616121_n.jpg


Danh mục độc giả :
37164_110685838995253_100001615134245_84736_100008_n.jpg


Danh mục nhà xuất bản :
33639_110685848995252_100001615134245_84737_867235_n.jpg


Loại SÁch:
68824_110685865661917_100001615134245_84738_6977573_n.jpg


Sách :
66284_110685898995247_100001615134245_84739_2011397_n.jpg


Mượn sách :
71737_110685922328578_100001615134245_84740_1803964_n.jpg



Trả sách:Bạn chỉ cần gõ mã số phiếu mượn ra là nó sẽ tìm dc đúng tên người mượn.....
68725_110685942328576_100001615134245_84741_4060753_n.jpg


Tìm độc giả :Bạn tìm theo các chức năng đều được, mình ví dụ tìm theo tên...
64952_110685955661908_100001615134245_84742_6842185_n.jpg


Tìm sách :bạn có thể tìm theo 1 trong các chức năng trong đó đều dc, mình ví dụ là tìm theo tên sách.....
37117_110685965661907_100001615134245_84743_7349987_n.jpg


Tìm sách mượn :
71760_110686002328570_100001615134245_84744_5113587_n.jpg


In kết quả : Ở đây mình in ra word...
65733_110686032328567_100001615134245_84745_2297093_n.jpg


Thuy xem đi nhé, nếu okie thì tuấn share cho code và bộ cài luôn, Tuấn đã đóng gói rùi. ....:D
 
Sửa lần cuối:

thuthuy

New member
Cám ơn Tuấn nhiều, h tớ mới làm cơ sở dữ liệu ah, hi', Thúy nói xạo để coi tác phẩm của Tuấn đấy mà, hehe, uhm, share cho tớ xin ha, cảm ơn cậu lần nữa nha.
 
Sửa lần cuối:
Top