新聞中心
求幾個JAVA小項目源代碼,供自己學習參考
package com.test01;
成都創(chuàng)新互聯專注于企業(yè)成都全網營銷推廣、網站重做改版、青陽網站定制設計、自適應品牌網站建設、H5響應式網站、購物商城網站建設、集團公司官網建設、外貿網站建設、高端網站制作、響應式網頁設計等建站業(yè)務,價格優(yōu)惠性價比高,為青陽等各大城市提供網站開發(fā)制作服務。
import java.util.Scanner;
public class oop5 { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// int x = 9;
// int y = 1;
int x = sc.nextInt();
int y = sc.nextInt();
int z;
z = add(x, y);
System.out.println("x的值為:" + x);
System.out.println("y的值為:" + y);
System.out.println("二者之和為:" + z);
}
/** 四種小算法 */
// 加法運算
public static int add(int a, int b) {
int c;
c = a + b;
return c;
}
// 減法運算
public static int jian(int d, int v) {
int m;
m = d - v;
return m;
}
// 乘積運算
public static int addAdd(int q, int w) {
int e;
e = q * w;
return e;
}
// 除法運算
public static int chu(int p, int k) {
int f;
f = p / k;
return f;
}
}
求一個完整的javaweb項目的購物網站源代碼
JAVA WEB項目的網絡購物網站源代碼的話,很復雜的話,肯定是沒有的,你可以去eoe或者安卓巴士網站看看有沒有源碼
求java小游戲源代碼
表1. CheckerDrag.java
// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{ // Dimension of checkerboard square. // 棋盤上每個小方格的尺寸 final static int SQUAREDIM = 40; // Dimension of checkerboard -- includes black outline. // 棋盤的尺寸 – 包括黑色的輪廓線 final static int BOARDDIM = 8 * SQUAREDIM + 2; // Dimension of checker -- 3/4 the dimension of a square. // 棋子的尺寸 – 方格尺寸的3/4 final static int CHECKERDIM = 3 * SQUAREDIM / 4; // Square colors are dark green or white. // 方格的顏色為深綠色或者白色 final static Color darkGreen = new Color (0, 128, 0); // Dragging flag -- set to true when user presses mouse button over checker // and cleared to false when user releases mouse button. // 拖動標記 --當用戶在棋子上按下鼠標按鍵時設為true, // 釋放鼠標按鍵時設為false boolean inDrag = false; // Left coordinate of checkerboard's upper-left corner. // 棋盤左上角的左方向坐標 int boardx; // Top coordinate of checkerboard's upper-left corner. //棋盤左上角的上方向坐標 int boardy; // Left coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原點(左上角)的左方向坐標 int ox; // Top coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原點(左上角)的上方向坐標 int oy; // Left displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按鍵時的鼠標坐標與棋子矩形原點之間的左方向位移 int relx; // Top displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按鍵時的鼠標坐標與棋子矩形原點之間的上方向位移 int rely; // Width of applet drawing area. // applet繪圖區(qū)域的寬度 int width; // Height of applet drawing area. // applet繪圖區(qū)域的高度 int height; // Image buffer. // 圖像緩沖 Image imBuffer; // Graphics context associated with image buffer. // 圖像緩沖相關聯的圖形背景 Graphics imG; public void init () { // Obtain the size of the applet's drawing area. // 獲取applet繪圖區(qū)域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 創(chuàng)建圖像緩沖 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出圖像緩沖相關聯的圖形背景 imG = imBuffer.getGraphics (); // Initialize checkerboard's origin, so that board is centered. // 初始化棋盤的原點,使棋盤在屏幕上居中 boardx = (width - BOARDDIM) / 2 + 1; boardy = (height - BOARDDIM) / 2 + 1; // Initialize checker's rectangle's starting origin so that checker is // centered in the square located in the top row and second column from // the left. // 初始化棋子矩形的起始原點,使得棋子在第一行左數第二列的方格里居中 ox = boardx + SQUAREDIM + (SQUAREDIM - CHECKERDIM) / 2 + 1; oy = boardy + (SQUAREDIM - CHECKERDIM) / 2 + 1; // Attach a mouse listener to the applet. That listener listens for // mouse-button press and mouse-button release events. // 向applet添加一個用來監(jiān)聽鼠標按鍵的按下和釋放事件的鼠標監(jiān)聽器 addMouseListener (new MouseAdapter () { public void mousePressed (MouseEvent e) { // Obtain mouse coordinates at time of press. // 獲取按鍵時的鼠標坐標 int x = e.getX (); int y = e.getY (); // If mouse is over draggable checker at time // of press (i.e., contains (x, y) returns // true), save distance between current mouse // coordinates and draggable checker origin // (which will always be positive) and set drag // flag to true (to indicate drag in progress). // 在按鍵時如果鼠標位于可拖動的棋子上方 // (也就是contains (x, y)返回true),則保存當前 // 鼠標坐標與棋子的原點之間的距離(始終為正值)并且 // 將拖動標志設為true(用來表明正處在拖動過程中) if (contains (x, y)) { relx = x - ox; rely = y - oy; inDrag = true; } } boolean contains (int x, int y) { // Calculate center of draggable checker. // 計算棋子的中心位置 int cox = ox + CHECKERDIM / 2; int coy = oy + CHECKERDIM / 2; // Return true if (x, y) locates with bounds // of draggable checker. CHECKERDIM / 2 is the // radius. // 如果(x, y)仍處于棋子范圍內則返回true // CHECKERDIM / 2為半徑 return (cox - x) * (cox - x) + (coy - y) * (coy - y) CHECKERDIM / 2 * CHECKERDIM / 2; } public void mouseReleased (MouseEvent e) { // When mouse is released, clear inDrag (to // indicate no drag in progress) if inDrag is // already set. // 當鼠標按鍵被釋放時,如果inDrag已經為true, // 則將其置為false(用來表明不在拖動過程中) if (inDrag) inDrag = false; } }); // Attach a mouse motion listener to the applet. That listener listens // for mouse drag events. //向applet添加一個用來監(jiān)聽鼠標拖動事件的鼠標運動監(jiān)聽器 addMouseMotionListener (new MouseMotionAdapter () { public void mouseDragged (MouseEvent e) { if (inDrag) { // Calculate draggable checker's new // origin (the upper-left corner of // the checker rectangle). // 計算棋子新的原點(棋子矩形的左上角) int tmpox = e.getX () - relx; int tmpoy = e.getY () - rely; // If the checker is not being moved // (at least partly) off board, // assign the previously calculated // origin (tmpox, tmpoy) as the // permanent origin (ox, oy), and // redraw the display area (with the // draggable checker at the new // coordinates). // 如果棋子(至少是棋子的一部分)沒有被 // 移出棋盤,則將之前計算的原點 // (tmpox, tmpoy)賦值給永久性的原點(ox, oy), // 并且刷新顯示區(qū)域(此時的棋子已經位于新坐標上) if (tmpox boardx tmpoy boardy tmpox + CHECKERDIM boardx + BOARDDIM tmpoy + CHECKERDIM boardy + BOARDDIM) { ox = tmpox; oy = tmpoy; repaint (); } } } }); } public void paint (Graphics g) { // Paint the checkerboard over which the checker will be dragged. // 在棋子將要被拖動的位置上繪制棋盤 paintCheckerBoard (imG, boardx, boardy); // Paint the checker that will be dragged. // 繪制即將被拖動的棋子 paintChecker (imG, ox, oy); // Draw contents of image buffer. // 繪制圖像緩沖的內容 g.drawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color. // 設置棋子陰影的顏色 g.setColor (Color.black); // Paint checker shadow. // 繪制棋子的陰影 g.fillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color. // 設置棋子顏色 g.setColor (Color.red); // Paint checker. // 繪制棋子 g.fillOval (x, y, CHECKERDIM - CHECKERDIM / 13, CHECKERDIM - CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline. // 繪制棋盤輪廓線 g.setColor (Color.black); g.drawRect (x, y, 8 * SQUAREDIM + 1, 8 * SQUAREDIM + 1); // Paint checkerboard. // 繪制棋盤 for (int row = 0; row 8; row++) { g.setColor (((row 1) != 0) ? darkGreen : Color.white); for (int col = 0; col 8; col++) { g.fillRect (x + 1 + col * SQUAREDIM, y + 1 + row * SQUAREDIM, SQUAREDIM, SQUAREDIM); g.setColor ((g.getColor () == darkGreen) ? Color.white : darkGreen); } } } // The AWT invokes the update() method in response to the repaint() method // calls that are made as a checker is dragged. The default implementation // of this method, which is inherited from the Container class, clears the // applet's drawing area to the background color prior to calling paint(). // This clearing followed by drawing causes flicker. CheckerDrag overrides // update() to prevent the background from being cleared, which eliminates // the flicker. // AWT調用了update()方法來響應拖動棋子時所調用的repaint()方法。該方法從 // Container類繼承的默認實現會在調用paint()之前,將applet的繪圖區(qū)域清除 // 為背景色,這種繪制之后的清除就導致了閃爍。CheckerDrag重寫了update()來 // 防止背景被清除,從而消除了閃爍。 public void update (Graphics g) { paint (g); }}
怎樣把一個java源代碼做成一個軟件成品?
1.其實就是用一個外部程序 調用java虛擬機運行你的java程序。
2.可以做一個批處理文件,在里面調用java 虛擬機運行你的java程序。
3.也可以用某種編程語言,像vb ,c 或c++編個程序,生成exe,能調用java虛擬機運行你的程序,很簡單的。
【源代碼】
源代碼(也稱源程序),是指一系列人類可讀的計算機語言指令。 在現代程序語言中,源代碼可以是以書籍或者磁帶的形式出現,但最為常用的格式是文本文件,這種典型格式的目的是為了編譯出計算機程序。
延展閱讀;
Java是一門面向對象編程語言,不僅吸收了C++語言的各種優(yōu)點,還摒棄了C++里難以理解的多繼承、指針等概念,因此Java語言具有功能強大和簡單易用兩個特征。Java語言作為靜態(tài)面向對象編程語言的代表,極好地實現了面向對象理論,允許程序員以優(yōu)雅的思維方式進行復雜的編程。
求一套完整的JAVA WEB項目的網絡購物網站源代碼
/**
*?@description:?
*?@author?chenshiqiang?E-mail:csqwyyx@163.com
*?@date?2014年9月7日?下午2:51:50???
*?@version?1.0???
*/
package?com.example.baidumap;
import?java.util.ArrayList;
import?java.util.Collections;
import?java.util.HashSet;
import?java.util.List;
import?android.app.Activity;
import?android.os.Bundle;
import?android.support.v4.view.PagerAdapter;
import?android.support.v4.view.PagerTabStrip;
import?android.support.v4.view.ViewPager;
import?android.text.Editable;
import?android.util.Log;
import?android.view.LayoutInflater;
import?android.view.View;
import?android.view.ViewGroup;
import?android.widget.ExpandableListView;
import?android.widget.ListView;
import?com.baidu.mapapi.map.offline.MKOLSearchRecord;
import?com.baidu.mapapi.map.offline.MKOLUpdateElement;
import?com.baidu.mapapi.map.offline.MKOfflineMap;
import?com.baidu.mapapi.map.offline.MKOfflineMapListener;
import?com.example.baidumap.adapters.OfflineExpandableListAdapter;
import?com.example.baidumap.adapters.OfflineMapAdapter;
import?com.example.baidumap.adapters.OfflineMapManagerAdapter;
import?com.example.baidumap.interfaces.OnOfflineItemStatusChangeListener;
import?com.example.baidumap.models.OfflineMapItem;
import?com.example.baidumap.utils.CsqBackgroundTask;
import?com.example.baidumap.utils.ToastUtil;
import?com.example.system.R;
public?class?BaiduOfflineMapActivity?extends?Activity?implements?MKOfflineMapListener,?OnOfflineItemStatusChangeListener
{
//?------------------------?Constants?------------------------
//?-------------------------?Fields?--------------------------
private?ViewPager?viewpager;
private?PagerTabStrip?pagertab;
private?MySearchView?svDown;
private?ListView?lvDown;
private?MySearchView?svAll;
private?ExpandableListView?lvWholeCountry;
private?ListView?lvSearchResult;
private?ListView?views?=?new?ArrayListView(2);
private?ListString?titles?=?new?ArrayListString(2);
private?MKOfflineMap?mOffline?=?null;
private?OfflineMapManagerAdapter?downAdapter;
private?OfflineMapAdapter?allSearchAdapter;
private?OfflineExpandableListAdapter?allCountryAdapter;
private?ListOfflineMapItem?itemsDown;?//?下載或下載中城市
private?ListOfflineMapItem?itemsAll;?//?所有城市,與熱門城市及下載管理對象相同
private?ListOfflineMapItem?itemsProvince;
private?ListListOfflineMapItem?itemsProvinceCity;
//?-----------------------?Constructors?----------------------
//?--------?Methods?for/from?SuperClass/Interfaces?-----------
@Override
protected?void?onCreate(Bundle?savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_offline_map);
// final?String?packname?=?this.getPackageName();
// PackageInfo?packageInfo;
// try
// {
// packageInfo?=?this.getPackageManager().getPackageInfo(packname,?PackageManager.GET_SIGNATURES);
//
//
// if?(code?==?-00)
// {
//?初始化離線地圖管理
mOffline?=?new?MKOfflineMap();
mOffline.init(this);
initViews();
viewpager.setCurrentItem(1);
// }
// }
// catch?(NameNotFoundException?e)
// {
// e.printStackTrace();
// }
}
private?boolean?isResumed?=?false;
@Override
protected?void?onResume()
{
super.onResume();
if?(!isResumed)
{
isResumed?=?true;
loadData();
}
}
@Override
protected?void?onDestroy()
{
super.onDestroy();
mOffline.destroy();
}
/**
?*?
?*?@author?chenshiqiang?E-mail:csqwyyx@163.com
?*?@param?type
?*????????????事件類型:?MKOfflineMap.TYPE_NEW_OFFLINE,?MKOfflineMap.TYPE_DOWNLOAD_UPDATE,?MKOfflineMap.TYPE_VER_UPDATE.
?*?@param?state
?*????????????事件狀態(tài):?當type為TYPE_NEW_OFFLINE時,表示新安裝的離線地圖數目.?當type為TYPE_DOWNLOAD_UPDATE時,表示更新的城市ID.
?*/
@Override
public?void?onGetOfflineMapState(int?type,?int?state)
{
switch?(type)
{
case?MKOfflineMap.TYPE_DOWNLOAD_UPDATE:
MKOLUpdateElement?update?=?mOffline.getUpdateInfo(state);
if?(setElement(update,?true)?!=?null)
{
if?(itemsDown?!=?null??itemsDown.size()??1)
{
Collections.sort(itemsDown);
}
refreshDownList();
}
else
{
downAdapter.notifyDataSetChanged();
}
allSearchAdapter.notifyDataSetChanged();
allCountryAdapter.notifyDataSetChanged();
break;
case?MKOfflineMap.TYPE_NEW_OFFLINE:
//?有新離線地圖安裝
Log.d("OfflineDemo",?String.format("add?offlinemap?num:%d",?state));
break;
case?MKOfflineMap.TYPE_VER_UPDATE:
//?版本更新提示
break;
}
}
/**
?*?百度下載狀態(tài)改變(暫停--》恢復)居然不回調,所以改變狀態(tài)時自己得增加接口監(jiān)聽狀態(tài)改變刷新界面
?*?
?*?@author?chenshiqiang?E-mail:csqwyyx@163.com
?*?@param?item
?*????????????有狀態(tài)改變的item
?*?@param?removed
?*????????????item是否被刪除
?*/
@Override
public?void?statusChanged(OfflineMapItem?item,?boolean?removed)
{
if?(removed)
{
for?(int?i?=?itemsDown.size()?-?1;?i?=?0;?i--)
{
OfflineMapItem?temp?=?itemsDown.get(i);
if?(temp.getCityId()?==?item.getCityId())
{
itemsDown.remove(i);
}
}
refreshDownList();
}
else
{
loadData();
downAdapter.notifyDataSetChanged();
}
allSearchAdapter.notifyDataSetChanged();
allCountryAdapter.notifyDataSetChanged();
}
//?---------------------?Methods?public?----------------------
public?void?toDownloadPage()
{
viewpager.setCurrentItem(0);
}
//?---------------------?Methods?private?---------------------
private?void?initViews()
{
//?TODO
viewpager?=?(ViewPager)?findViewById(R.id.viewpager);
pagertab?=?(PagerTabStrip)?findViewById(R.id.pagertab);
LayoutInflater?inf?=?LayoutInflater.from(this);
View?v1?=?inf.inflate(R.layout.view_offline_download,?null,?false);
svDown?=?(MySearchView)?v1.findViewById(R.id.svDown);
lvDown?=?(ListView)?v1.findViewById(R.id.lvDown);
views.add(v1);
View?v2?=?inf.inflate(R.layout.view_offline_countrys,?null,?false);
svAll?=?(MySearchView)?v2.findViewById(R.id.svAll);
lvWholeCountry?=?(ExpandableListView)?v2.findViewById(R.id.lvWholeCountry);
lvSearchResult?=?(ListView)?v2.findViewById(R.id.lvSearchResult);
views.add(v2);
titles.add("下載管理");
titles.add("城市列表");
pagertab.setTabIndicatorColor(0xff00cccc);
pagertab.setDrawFullUnderline(false);
pagertab.setBackgroundColor(0xFF38B0DE);
pagertab.setTextSpacing(50);
viewpager.setOffscreenPageLimit(2);
viewpager.setAdapter(new?MyPagerAdapter());
svDown.setSearchListener(new?MySearchView.SearchListener()
{
@Override
public?void?afterTextChanged(Editable?text)
{
refreshDownList();
}
@Override
public?void?search(String?text)
{
}
});
svAll.setSearchListener(new?MySearchView.SearchListener()
{
@Override
public?void?afterTextChanged(Editable?text)
{
refreshAllSearchList();
}
@Override
public?void?search(String?text)
{
}
});
downAdapter?=?new?OfflineMapManagerAdapter(this,?mOffline,?this);
lvDown.setAdapter(downAdapter);
allSearchAdapter?=?new?OfflineMapAdapter(this,?mOffline,?this);
lvSearchResult.setAdapter(allSearchAdapter);
allCountryAdapter?=?new?OfflineExpandableListAdapter(this,?mOffline,?this);
lvWholeCountry.setAdapter(allCountryAdapter);
lvWholeCountry.setGroupIndicator(null);
}
/**
?*?刷新下載列表,?根據搜索關鍵字及itemsDown?下載管理數量變動時調用
?*/
private?void?refreshDownList()
{
String?key?=?svDown.getInputText();
if?(key?==?null?||?key.length()??1)
{
downAdapter.setDatas(itemsDown);
}
else
{
ListOfflineMapItem?filterList?=?new?ArrayListOfflineMapItem();
if?(itemsDown?!=?null??!itemsDown.isEmpty())
{
for?(OfflineMapItem?i?:?itemsDown)
{
if?(i.getCityName().contains(key))
{
filterList.add(i);
}
}
}
downAdapter.setDatas(filterList);
}
}
/**
?*?刷新所有城市搜索結果
?*/
private?void?refreshAllSearchList()
{
String?key?=?svAll.getInputText();
if?(key?==?null?||?key.length()??1)
{
lvSearchResult.setVisibility(View.GONE);
lvWholeCountry.setVisibility(View.VISIBLE);
allSearchAdapter.setDatas(null);
}
else
{
lvSearchResult.setVisibility(View.VISIBLE);
lvWholeCountry.setVisibility(View.GONE);
ListOfflineMapItem?filterList?=?new?ArrayListOfflineMapItem();
if?(itemsAll?!=?null??!itemsAll.isEmpty())
{
for?(OfflineMapItem?i?:?itemsAll)
{
if?(i.getCityName().contains(key))
{
filterList.add(i);
}
}
}
allSearchAdapter.setDatas(filterList);
}
}
private?void?loadData()
{
new?CsqBackgroundTaskVoid(this)
{
@Override
protected?Void?onRun()
{
//?TODO?Auto-generated?method?stub
//?導入離線地圖包
//?將從官網下載的離線包解壓,把vmp文件夾拷入SD卡根目錄下的BaiduMapSdk文件夾內。
//?把網站上下載的文件解壓,將\BaiduMap\vmp\l里面的.dat_svc文件,拷貝到手機BaiduMapSDK/vmp/h目錄下
int?num?=?mOffline.importOfflineData();
if?(num??0)
{
ToastUtil.showToastInfo(BaiduOfflineMapActivity.this,?"成功導入"?+?num?+?"個離線包",?false);
}
ListMKOLSearchRecord?all?=?null;
try
{
all?=?mOffline.getOfflineCityList();
}
catch?(Exception?e)
{
e.printStackTrace();
}
if?(all?==?null?||?all.isEmpty())
{
ToastUtil.showToastInfo(BaiduOfflineMapActivity.this,?"未獲取到離線地圖城市數據,可能有其他應用正在使用百度離線地圖功能!",?false);
return?null;
}
ListMKOLSearchRecord?hotCity?=?mOffline.getHotCityList();
HashSetInteger?hotCityIds?=?new?HashSetInteger();
if?(!hotCity.isEmpty())
{
for?(MKOLSearchRecord?r?:?hotCity)
{
hotCityIds.add(r.cityID);
}
}
itemsAll?=?new?ArrayListOfflineMapItem();
itemsDown?=?new?ArrayListOfflineMapItem();
itemsProvince?=?new?ArrayListOfflineMapItem();
itemsProvinceCity?=?new?ArrayListListOfflineMapItem();
//?cityType?0:全國;1:省份;2:城市,如果是省份,可以通過childCities得到子城市列表
//?全國概略圖、直轄市、港澳?子城市列表
ArrayListMKOLSearchRecord?childMunicipalities?=?new?ArrayListMKOLSearchRecord();
proHot.cityName?=?"熱門城市";
proHot.childCities?=?cs;
ListMKOLUpdateElement?updates?=?mOffline.getAllUpdateInfo();
if?(updates?!=?null??updates.size()??0)
{
}
@Override
protected?void?onResult(Void?result)
{
//?TODO?Auto-generated?method?stub
refreshDownList();
refreshAllSearchList();
allCountryAdapter.setDatas(itemsProvince,?itemsProvinceCity);
}
}.execute();
}
急求JAVA源代碼,小游戲或者別的
//這是個聊天程序, 在ECLIPSE 運行 Client.java 就可以了。 連接是:localhost
//Server 代碼,
package message;
import java.io.*;
import java.net.*;
import java.util.*;
public class Server {
public static void main(String[] args) throws Exception{
System.out.print("Server");
ServerSocket socket=new ServerSocket(8888);
Vector v=new Vector();
while(true){
Socket sk=socket.accept();
DataInputStream in=new DataInputStream(sk.getInputStream());
DataOutputStream out=new DataOutputStream(sk.getOutputStream());
v.add(sk);
new ServerThread(in,v).start();
}
}
}
//ServerThread.java 代碼
package message;
import java.net.*;
import java.io.*;
import java.util.*;
public class ServerThread extends Thread{
DataInputStream in;
Vector all;
public ServerThread(DataInputStream in,Vector v){
this.in=in;
this.all=v;
}
public void run()
{
while(true)
{
try{
String s1=in.readUTF();
for(int i=0;iall.size();i++)
{
Object obj=all.get(i);
Socket socket=(Socket)obj;
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
out.writeUTF(s1);
System.out.print(i);
out.flush();
}
System.out.print("Message send over!");
}catch(Exception e){e.printStackTrace();};
}
}
}
//ClientFrame.java 代碼
package message;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ClientFrame extends JFrame implements ActionListener{
JButton b1=new JButton ("SendMessage");
JButton b2=new JButton("Link Server");
JTextField t1=new JTextField(20);
JTextField t2=new JTextField(20);
JLabel l=new JLabel("輸入服務器名字:");
JTextArea area=new JTextArea(10,20);
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JPanel p4=new JPanel();
Socket socket;
public ClientFrame()
{
this.getContentPane().add(p1);
p2.add(new JScrollPane(area));
p3.add(t1);
p3.add(b1);
p4.add(l);
p4.add(t2);
p4.add(b2);
p2.setLayout(new FlowLayout());
p3.setLayout(new FlowLayout());
p4.setLayout(new FlowLayout());
p1.setLayout(new BorderLayout());
p1.add("North",p2);
p1.add("Center",p3);
p1.add("South",p4);
b1.addActionListener(this);
b2.addActionListener(this);
this.pack();
show();
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equals("Link Server"))
{
try{
socket=new Socket(t2.getText(),8888);
b2.setEnabled(false);
JOptionPane.showMessageDialog(this, "Connection Success");
DataInputStream in=new DataInputStream(socket.getInputStream());
new ClientThread(in,area).start();
}
catch(Exception e1){
JOptionPane.showMessageDialog(this, "Connection Error");
e1.printStackTrace();};
}
else if(e.getActionCommand().equals("SendMessage"))
{
try{
DataOutputStream out=new DataOutputStream(socket.getOutputStream());
out.writeUTF(t1.getText());
t1.setText("");
}catch(Exception e1){e1.printStackTrace();};
}
}
}
//ClientThread.java 代碼
package message;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class ClientThread extends Thread {
DataInputStream in;
JTextArea area;
public ClientThread(DataInputStream in,JTextArea area){
this.in=in;
this.area=area;
}
public void run()
{
while(true){
try{
String s=in.readUTF();
area.append(s);
}
catch(Exception e){e.printStackTrace();};
}
}
}
//Client.java代碼
package message;
public class Client {
/**
* @param args
*/
public static void main(String[] args) {
new ClientFrame();
}
}
// 每段代碼都是個類,不要弄在一個文件里。 運行 Client.java
good luck to you!
網頁標題:仿閑魚+java源代碼 閑魚源碼網
分享鏈接:http://ef60e0e.cn/article/docdshd.html