5.Java GridLayout的综合使用(java小计算器的设计)... 28
1.Java的LinkedListTest的使用... 32
4.ObjectInputStream 与 ObjectOutputStream的使用... 57
2.下面是一个赛跑问题,Runnable创建线程... 61
3.Runnable两个小球,一个平抛,另一个自由落体... 63
8.Synchnorized的使用,一个线程调用了它,这个线程运行结束后,其它线程才会开始 74
9.Wait 与 synchronized的用法... 77
1.多客户端与服务器端通信(一个客户端可以和用户多次交互... 79
2.服务器端与客户端在交互时,用的方法要一致,否则会出现异常... 82
3.带有图形界面的客户端与服务器端交互(计算三角形面积)... 85
4.客户端服务器端与服务器交互(可以多客户端多次交互)... 89
1.星期的做法
public class DayOfWeekCalendar {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("日 一 二 三 四 五 六");
Calendar calendar=Calendar.getInstance();
//将日历翻至2011年7月1日
calendar.set(20011,6,1);
//获取1日是星期几(get方法返回的是1表示星期日,星期六返回的是七)
int DayOfWeek=calendar.get(Calendar.DAY_OF_WEEK)-1;
String[] a=new String[31+DayOfWeek];
for(int i=0;i<DayOfWeek;i++){
a[i]=" ";
}
for(int i=DayOfWeek,n=1;i<31+DayOfWeek;i++,n++){
if(n<=9){
//加字是三个空格
a[i]=String.valueOf(n)+" ";
}
else{
a[i]=String.valueOf(n)+" ";
}
}
for(int j=0;j<a.length;j++){
if(j%7==0){
System.out.println("");
}
System.out.print(a[j]);
}
//了解random
System.out.println("");
int num=(int)(Math.random()*100);
System.out.println("random在0--1之间:"+num);
//round返回最接近的整数
int num1=(int) Math.round(213.23);
System.out.println(num1);
}
}
--------------------------------------------------------------------------------------------------------
2.字符形式的日期转化为期格式
public class PureDate {
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* Date在现在已有些过时,大多时候用Calendar的方法
*/
Date date=new Date();
System.out.println(date);
Date date1=new Date(1000);
System.out.println(date1);
Date date2=new Date();
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String rr=format.format(date2);
System.out.println(format.format(date2));
try {
Date dd=format.parse(rr);
System.out.println("dd="+dd);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//目前时刻的毫秒数,是一个长整型北京时区
System.out.println(System.currentTimeMillis());
}
}
------------------------------------------------------------------------------------
3.Calender 的使用
public class TestCalendar {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
* Calendar 类是一个抽象类,
* 它为特定瞬间与一组诸如 YEAR、MONTH、DAY_OF_MONTH、HOUR 等 日历字段之间的转换
* 提供了一些方法,并为操作日历字段(例如获得下星期的日期)提供了一些方法。瞬间可
* 用毫秒值来表示,
* 它是距历元(即格林威治标准时间 1970 年 1 月 1 日的 00:00:00.000,格里高利历)的偏移量。
*/
//获得Calendar一个通用的对象或初始化一个日历对象
Calendar calendar=Calendar.getInstance();
//获取毫秒数
long milSecond=calendar.getTimeInMillis();
System.out.println("毫秒数为:"+milSecond);
String year=String.valueOf(calendar.get(Calendar.YEAR)),
//注意求月数要加一
month=String.valueOf(calendar.get(Calendar.MONTH)+1),
day=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
int hour=calendar.get(Calendar.HOUR_OF_DAY),
minute=calendar.get(Calendar.MINUTE),
second=calendar.get(Calendar.SECOND);
System.out.println("现在的时间是:");
System.out.println(year+"年"+month+"月"+day+"日"+hour+"时"+minute+"分"+second+"秒");
//计算两个时间类相隔的时间
calendar.set(2011,7,13,19,10,20);
long time2011s=calendar.getTimeInMillis();
calendar.set(2011,7,15,20,15,28);
long time20117=calendar.getTimeInMillis();
long saday=(time20117-time2011s)/(1000*60*60*24);
System.out.println("2011年7月13日19时10分20秒和2011年7月15日20时10分20秒相隔"+saday+"天");
}
}
JAVA.awt
1.CardLayou的特殊使用
class WindowMouseListener extends JFrame implements ItemListener{
private JComboBox choice;
private JTextArea textarea;
private JPanel pane1,pane,pane3;
int index;
String[] content={"","软件开发工程师","熟识编程语言开发技巧","3年","本科","软件设计师中级"};
GridLayout grid;
CardLayout card;
public WindowMouseListener(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
grid=new GridLayout(1,2);
card=new CardLayout();
pane1=new JPanel(new GridLayout(3,1,0,150));
pane1.add(new JLabel(""));
pane3=new JPanel();
pane3.add(new JLabel("简历说明立项:"));
pane=new JPanel();
pane.setLayout(card);
this.choice=new JComboBox();
this.choice.addItem("----选项----");
this.choice.addItem("Object");
this.choice.addItem("Qualification");
this.choice.addItem("Work experience");
this.choice.addItem("Education");
this.choice.addItem("Certification");
choice.setLocation(50, 300);
pane3.add(choice);
pane1.add(pane3);
pane1.add(new JLabel(""));
Container con=getContentPane();
con.setLayout(grid);
con.add(pane1,BorderLayout.WEST);
con.add(pane,BorderLayout.EAST);
this.choice.addItemListener(this);
index=this.choice.getItemCount();
for(int i=0;i<index;i++){
textarea=new JTextArea();
textarea.setText(content[i]);
card.next(pane);
pane.add(textarea,content[i]);
}
card.first(pane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
validate();
}
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method s
if(e.getItemSelectable()==this.choice){
CardLayout car=(CardLayout) this.pane.getLayout();
car.show(pane,content[this.choice.getSelectedIndex()]);
/*
* 下面的方法也可以
textarea=new JTextArea();
int indextemp=this.choice.getSelectedIndex();
textarea.setText(content[indextemp]);
card.next(pane);
pane.add(textarea,"添加文本区");*/
}
}
}
public class ResumeFrame {
public static void main(String[] args) {
// TODO Auto-generated method stub
new WindowMouseListener("这是一个简历布局");
}
}
Java菜单的综合使用包括快捷键 打开 保存 剪切 复制 关于 粘贴
class FirstWindow extends Frame {
Dialog diag;
Clipboard clipboard; //剪切板
//PopupMenu此类实现能够在组件中的指定位置上动态弹出的菜单。
//正如继承层次关系所暗示的那样,任何可以使用 Menu 的地方都可以使用 PopupMenu。但是,如果使用像 Menu 这样的 PopupMenu
//(例如,将其添加到 MenuBar),则不能调用该 PopupMenu 的 show。
PopupMenu pop;//右键鼠标促发的事件
class MenuActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==item12){
FileDialog dialog=new FileDialog(FirstWindow.this,"打开文件",FileDialog.LOAD);
dialog.setVisible(true);
}
if(e.getSource()==item13){
FileDialog dialog=new FileDialog(FirstWindow.this,"保存文件",FileDialog.SAVE);
dialog.setVisible(true);
}
if(e.getSource()==item14){
diag = new Dialog(FirstWindow.this,"关于",true);
diag.setLayout(new GridLayout(3,1,10,10));
diag.add(new Label("软件名称:山寨记事本"));
diag.add(new Label("版本号:1.0"));
Panel p = new Panel();
Button b = new Button("ok");
b.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
diag.setVisible(false);
}
});
p.add(b);
diag.add(p);
diag.setBounds(300, 300, 300, 150);
diag.setVisible(true);
}
if(e.getSource()==item15){
FirstWindow.this.setVisible(false);
FirstWindow.this.dispose();
System.exit(0);
}
if(e.getSource()==item22){
String temp=area.getSelectedText();
StringSelection text=new StringSelection(temp);
clipboard.setContents(text, null);
int start=area.getSelectionStart();
int end=area.getSelectionEnd();
area.replaceRange("", start, end);
}
if(e.getSource()==item23){
//从剪切板获得数据
Transferable contents=clipboard.getContents(this);
DataFlavor flavor=DataFlavor.stringFlavor;
if(contents.isDataFlavorSupported(flavor))
try{
String str;
str=(String) contents.getTransferData(flavor);
area.append(str);
}
catch(Exception ee){
ee.printStackTrace();
}
}
if(e.getSource()==item24){
String temp=area.getSelectedText();
StringSelection text=new StringSelection(temp);
clipboard.setContents(text, null);
}
}
}
MenuBar menubar;
Menu menu1,menu2,menu3,menu4,menu5,menu32;
MenuItem item11,item12,item13,item14,item15,item21,item22,item23,item24,item31,
item32,item41,item51,item52,menuItem301,menuItem302,menuItem303;
TextArea area;
public FirstWindow(String s) {
setTitle(s);
//获得屏幕大小
Toolkit tool=getToolkit();
Dimension dim=tool.getScreenSize();
setBounds(0,0,dim.width,dim.height/2);
clipboard=getToolkit().getSystemClipboard();//获取系统剪切板
menubar=new MenuBar();
area=new TextArea();
menu1=new Menu("文件");
menu2=new Menu("编辑");
menu3=new Menu("格式");
menu4=new Menu("查看");
menu5=new Menu("帮助");
item11=new MenuItem("新建");
item12=new MenuItem("打开(O)",new MenuShortcut(KeyEvent.VK_O));
//item12.setShortcut(new MenuShortcut(KeyEvent.VK_O));
//this.item12.setAccelerator(KeyStroke.getKeyStroke('O'));
item12.addActionListener(new MenuActionListener());
item13=new MenuItem("保存(S)",new MenuShortcut(KeyEvent.VK_S));
item13.addActionListener(new MenuActionListener());
item14=new MenuItem("打印",new MenuShortcut(KeyEvent.VK_P));
item14.addActionListener(new MenuActionListener());
item15=new MenuItem("退出",new MenuShortcut(KeyEvent.VK_E));
item15.addActionListener(new MenuActionListener());
item21=new MenuItem("撤销");
item22=new MenuItem("剪切");
item22.addActionListener(new MenuActionListener());
item23=new MenuItem("粘贴");
item23.addActionListener(new MenuActionListener());
item24=new MenuItem("复制");
item24.addActionListener(new MenuActionListener());
item31=new MenuItem("自动换行");
menu32=new Menu("字体");
menuItem301=new MenuItem("左对齐");
menuItem302=new MenuItem("中对齐");
menuItem303=new MenuItem("右对齐");
menu32.add(menuItem301);
menu32.add(menuItem302);
menu32.add(menuItem303);
item41=new MenuItem("状态栏");
item51=new MenuItem("帮助主题");
item52=new MenuItem("关于记事本");
item52.addActionListener(new MenuActionListener());
menu1.add(item11);
menu1.add(item12);
menu1.add(item13);
menu1.add(item14);
menu1.add(item15);
menu2.add(item21);
menu2.add(item22);
menu2.add(item23);
menu2.add(item24);
menu3.add(item31);
menu3.add(menu32);
menu4.add(item41);
menu5.add(item51);
menu5.add(item52);
menubar.add(menu1);
menubar.add(menu2);
menubar.add(menu3);
menubar.add(menu4);
menubar.add(menu5);
pop=new PopupMenu("鼠标右键菜单");
pop.add("剪切");
pop.add("复制");
pop.add("粘贴");
FirstWindow.this.addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
if(e.isPopupTrigger()){
System.out.println("dfdgdf:"+e.getX());
pop.show(e.getComponent(),e.getX(),e.getY());
}
}
});
//this.add(pop);
setMenuBar(menubar);
add(area,BorderLayout.CENTER);
setBackground(Color.gray);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
//System.exit(0);
dispose();
}
});
setVisible(true);
}
}
public class MyWindowMenuItem {
public static void main(String[] args) {
// TODO Auto-generated method stub
FirstWindow first=new FirstWindow("一个带菜单的窗口");
}
}
2.鼠标事件
class WindowMouseMotion extends JFrame implements ActionListener,MouseListener,MouseMotionListener{
JButton button1,button2;
JLabel label1;
JTextField text;
JPanel east,west;
int x,y;
public WindowMouseMotion(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
Container con=getContentPane();
//案例一 可以碰撞移动
east=new JPanel(new FlowLayout(FlowLayout.LEFT,150,0));
east.setLocation(0, 200);
button1=new JButton("横纵坐标移动");
button1.addActionListener(this);
button1.addMouseListener(this);
button1.addMouseMotionListener(this);
label1=new JLabel("可以被碰掉");
label1.addMouseListener(this);
label1.addMouseMotionListener(this);
east.add(button1);
east.add(label1);
con.add(east,BorderLayout.WEST);
//案例二,可以被拖曳
west=new JPanel(new FlowLayout(FlowLayout.LEFT,50,0));
west.setLocation(600, 100);
button2=new JButton("鼠标移动坐标");
button2.addMouseListener(this);
button2.addMouseMotionListener(this);
text=new JTextField("文本框的鼠标移动",10);
text.addMouseListener(this);
text.addMouseMotionListener(this);
west.add(button2);
west.add(text);
con.add(west,BorderLayout.EAST);
setSize(1000,800);
setVisible(true);
validate();
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
Component com=null;
com=(Component) e.getSource();
x=e.getX();
y=e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
Component com=null;
com=(Component) e.getSource();
//x是组件相对于所包含容器的左边界
//返回事件相对于源组件的水平 x 坐标。
x=e.getX();
System.out.println("x:"+x);
//返回事件相对于源组件的垂直 y 坐标。
y=e.getY();
//this.getHeight返回组件的当前高度。此方法优于 component.getBounds().height
//或 component.getSize().height 方法,因为它不会导致任何的堆分配。
int a=(int) com.getLocation().getX();
System.out.println("a:"+a);
if(x==0 ){
com.setLocation(0,y);
return;
}
if(y==0){
com.setLocation(x, 0);
return;
}
int w=com.getSize().width,
h=com.getSize().height;
com.setLocation(x-w/2,y-h/2);
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==button1){
//以 Rectangle 对象的形式获取组件的边界。边界指定此组件的宽度、高度和相对于其父级的位置。
//表示组件边界的矩形
Rectangle rect=button1.getBounds();
x=(int) rect.getX();
y=(int) rect.getY();
//intersects 计算此 Rectangle 与指定 Rectangle 的交集
// while(true){
if(rect.intersects(label1.getBounds())){
label1.setVisible(false);
//break;
}
if(label1.isVisible()){
x=x+5;
button1.setLocation(x, y);
}
else if(!label1.isVisible()){
y=y+5;
button1.setLocation(x,y);
}
/* if(y==WindowMouseMotion.this.getHeight()-rect.getHeight()){
x=(int) rect.getX();
label1.setVisible(true);
y=(int) rect.getY();
button1.setLocation(x,y);
}
try {
Thread.sleep(10);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}*/
}
}
}
public class MouseMotionListenerDragAndMove {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new WindowMouseMotion("这是一个鼠标拖曳事件");
}
}
class WindowMouse extends JFrame{
int x0=0,y0=0,x=0,y=0,left=-1,right=-1;
public WindowMouse(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
setSize(800,800);
Container con=getContentPane();
MyCanvas canva=new MyCanvas();
canva.setBackground(Color.LIGHT_GRAY);
con.add(canva,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
validate();
}
class MyCanvas extends Canvas implements MouseListener,MouseMotionListener{
MyCanvas(){
//注意鼠标监听器需要有两个
addMouseListener(this);
addMouseMotionListener(this);
}
/* public void paint(Graphics g){
if(left==1){
//g.fillOval(x, y, 100, 100);
//g.drawString("-", x, y);
g.setColor(Color.blue);
g.drawLine(x0, y0, x, y);
}
if(right==1){
//g.fillRect(x, y+100, 100, 100);
g.drawString("-", x, y);
g.setColor(Color.red);
}
}
public void update(Graphics g){
if(left==1 || right==1){
paint(g);
}
else{
super.update(g);
}
}*/
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
x0=e.getX();
y0=e.getY();
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
right=-1;
left=-1;
repaint();
}
public void mouseDragged(MouseEvent e){
System.out.println("这是一个鼠标拖曳的程序");
x=e.getX();
y=e.getY();
if(e.getModifiers()==InputEvent.BUTTON1_MASK){
left=1;
right=-1;
//repaint();
Graphics g = MyCanvas.this.getGraphics();
g.setColor(Color.red);
g.drawLine(x0, y0, x, y);
x0=x;
y0=y;
}
else if(e.getModifiers()==InputEvent.BUTTON3_MASK){
right=1;
left=-1;
repaint();
x0=x;
y0=y;
}
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}
public class MouseListenerTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new WindowMouse("这是一个鼠标监听事件");
}
}
3.键盘事件
public class KeyBoardBallPlayer extends JFrame{
private int x=(int) this.getLocation().getX()+100,y=(int) this.getLocation().getY(),position=-1;
class WindowBall extends Canvas implements KeyListener{
public WindowBall(){
addKeyListener(this);
}
public void paint(Graphics g){
g.setColor(Color.BLUE);
g.fillArc(x, y, 50, 50, 0, 360);
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
//用此方法,鼠标应该也在区域里面
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println("dfdgf");
if(e.getKeyCode()==KeyEvent.VK_UP){
if(y<=KeyBoardBallPlayer.this.getLocation().getY()){
y=(int) KeyBoardBallPlayer.this.getLocation().getY();
}
position=1;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN){
if(y>= KeyBoardBallPlayer.this.getHeight()){
y=KeyBoardBallPlayer.this.getHeight();
}
position=0;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT){
System.out.println("dfdgf1213");
if(x<=KeyBoardBallPlayer.this.getLocation().getX()){
x=(int) KeyBoardBallPlayer.this.getLocation().getX();
}
position=-2;
}
else if(e.getKeyCode()==KeyEvent.VK_RIGHT){
if(x>=KeyBoardBallPlayer.this.getHeight()){
x=KeyBoardBallPlayer.this.getHeight();
}
position=2;
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
public KeyBoardBallPlayer(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
Container con=getContentPane();
WindowBall ball=new WindowBall();
con.add(ball,BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
setVisible(true);
validate();
while(true){
if(position==2){
x=x+2;
}
if(position==-2){
x=x-2;
}
if(position==0){
y=y+2;
}
else if(position==1){
y=y-2;
}
if(x<=(int) this.getLocation().getX()-150){
x=(int) this.getLocation().getX()-150;
position=2;
}
if(x>=this.getWidth()-50){
x=this.getWidth()-50;
position=-2;
}
if(y>=this.getHeight()-75){
y=this.getHeight()-75;
position=1;
x=(int) (Math.random()*500);
}
else if(y<=(int) this.getLocation().getY()){
y=(int) this.getLocation().getY();
position=0;
x=(int) (Math.random()*500);
}
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ball.repaint();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new KeyBoardBallPlayer("这是一个滚球游戏");
}
}
4.GUI综合使用(包括组件及事件处理)
public class MusicPanel extends JPanel {
private JTabbedPane tabMusic;
private JComboBox arealist;
//JList显示对象列表并且允许用户选择一个或多个项的组件。
//单独的模型 ListModel 维护列表的内容。
private JList biglist;
private JLabel choiceareaLabel;
private JButton detail,clear,exit;
private JPanel north,listPane,south,bigPane;
private CardLayout card;
MusicDetailsDialog musicdialog;
String name=null;
String selectedAreaname=null;
MusicDataClient mclient=new MusicDataClient();
int b;
//String[][] area={{},{"张学友,给我亲爱的","顺子, 顺子","迪克牛仔, 我这个你不爱的人","林子祥, 十三子祥"},{"胡彦斌, 文武双全","那英, 征服","阿杜, 天黑"},{"Mozart, Amadeus, 欧美","Motley Crue, Greatest Hits, 欧美","Shania Twain, Come On Over, 欧美","Tchaikovsky, Nutcracker, 欧美"},{"孙燕姿, 完美一天"}};
public MusicPanel(){
this.setLayout(new GridLayout(1,1));
north=new JPanel(new FlowLayout(FlowLayout.LEFT));
choiceareaLabel=new JLabel("选择音乐目录",JLabel.LEFT);
Set<String> cityarea=mclient.getAreanames();
Vector<String> area=new Vector<String>();
Iterator<String> area1=cityarea.iterator();
area.add("-----------");
while(area1.hasNext()){
String area2=area1.next();
area.add(area2);
}
arealist=new JComboBox(area);
arealist.addItemListener(new ListItemListener());
north.add(choiceareaLabel);
north.add(arealist);
listPane=new JPanel();
card=new CardLayout();
listPane.setLayout(card);
detail=new JButton("详细");
//setEnable设置按钮是否可被激活
detail.setEnabled(false);
clear=new JButton("清除");
clear.setEnabled(false);
exit=new JButton("退出");
exit.addActionListener(new ButtonListener());
south=new JPanel();
south.add(detail);
south.add(clear);
south.add(exit);
bigPane=new JPanel();
bigPane.setLayout(new BorderLayout());
bigPane.add(north,BorderLayout.NORTH);
bigPane.add(listPane,BorderLayout.CENTER);
bigPane.add(south,BorderLayout.SOUTH);
tabMusic=new JTabbedPane();
tabMusic.setLayout(new BorderLayout());
tabMusic.add("音乐",bigPane);
this.add(tabMusic,BorderLayout.CENTER);
setVisible(true);
}
public class WindowMouseListener implements MouseListener {
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
int count=e.getClickCount();
if(count==2){
while(b>=1){
musicdialog=new MusicDetailsDialog(MusicPanel.this,"光盘详细信息 "+name,true);
musicdialog.delWith(name,selectedAreaname,mclient);
musicdialog.setVisible(true);
b--;
}
}
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
}
class ButtonListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==exit){
MusicPanel.this.setVisible(false);
System.exit(0);
}
else if(e.getSource()==detail){
while(b>=1){
musicdialog=new MusicDetailsDialog(MusicPanel.this,"光盘详细信息 "+name,true);
musicdialog.delWith(name,selectedAreaname,mclient);
b--;
}
}
else if(e.getSource()==clear){
System.out.println("remove all");
biglist.clearSelection();
biglist.setVisible(false);
//listPane.remove(biglist);
}
else{
System.out.println("双击下拉列表");
}
}
}
class ListItemListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==arealist){
int index1=arealist.getSelectedIndex();
selectedAreaname=(String) arealist.getSelectedItem();
if(index1==0){
biglist=new JList();
listPane.add(biglist,index1+"");
card.show(listPane,index1+"");
clear.setEnabled(false);
detail.setEnabled(false);
}
else{
System.out.println("index:"+index1);
String areaname=(String) arealist.getSelectedItem();
mclient.dealWithSendArea(areaname);
//应该在此选择一项,下拉列表添加一个集合
Vector<String> singername=mclient.dealWithSendArea(areaname);
System.out.println("用户界面读的singername"+singername);
System.out.println(singername);
biglist=new JList(singername);
//在知道特定的面板时card.next(listPane);不要用,不然不知道是哪个JList
//没法获得选择的值
listPane.add(biglist,index1+"");
card.show(listPane,index1+"");
//biglist=(JList) listPane.getComponent(index1);
biglist.addListSelectionListener(new JListItemListener());
clear.setEnabled(true);
clear.addActionListener(new ButtonListener());
detail.setEnabled(false);
}
}
}
}
class JListItemListener implements ListSelectionListener{
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
//if(!biglist.isSelectionEmpty()){
b=biglist.getSelectedValues().length;
System.out.println("b:"+b);
if(b==1){
biglist.addMouseListener(new WindowMouseListener());
}
name=(String) biglist.getSelectedValue();
System.out.println("选中的歌手名:"+name);
detail.setEnabled(true);
detail.addActionListener(new ButtonListener());
clear.setEnabled(true);
clear.addActionListener(new ButtonListener());
//biglist.removeListSelectionListener(this);
//}
}
}
}
package com.lzl.view;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import com.lzl.bean.MusicRecording;
import com.lzl.bean.Recording;
import com.lzl.bean.Track;
import com.lzl.deal.MusicDataClient;
public class MusicDetailsDialog extends JDialog implements ActionListener{
private JLabel singer,actname,type,length,price,personicon;
private JTextField tf_singer,tf_actname,tf_type,tf_length,tf_price;
private JList list;
private JScrollPane scroll;
private JButton ok;
private Icon icon;
boolean model;
Vector<String> titleandtime=new Vector<String>();
public MusicDetailsDialog(MusicPanel musicPanel, String string, boolean b){
this.setTitle(string);
model=b;
setLayout(null);
icon=new ImageIcon("image/03.jpg");
singer=new JLabel("歌手");
singer.setBounds(20,20,40,30);
actname=new JLabel("歌名");
actname.setBounds(20,65,40,30);
type=new JLabel("类型");
type.setBounds(20, 115, 40, 30);
length=new JLabel("长度");
length.setBounds(20,160,40,30);
price=new JLabel("价格");
price.setBounds(20, 215, 40, 30);
personicon=new JLabel(icon);
personicon.setBounds(130,0,280,270);
tf_singer=new JTextField(40);
tf_singer.setBorder(null);
tf_singer.setBounds(60,20,80,30);
tf_actname=new JTextField(40);
tf_actname.setBorder(null);
tf_actname.setBounds(60,65,80,30);
tf_type=new JTextField(40);
tf_type.setBorder(null);
tf_type.setBounds(60,115,80,30);
tf_length=new JTextField(40);
tf_length.setBorder(null);
tf_length.setBounds(60, 160, 80, 30);
tf_price=new JTextField(40);
tf_price.setBorder(null);
tf_price.setBounds(60,215,80,30);
add(singer);
add(personicon);
add(tf_singer);
add(actname);
add(tf_actname);
add(type);
add(tf_type);
add(length);
add(tf_length);
add(price);
add(tf_price);
//System.out.println();
list=new JList();
scroll=new JScrollPane(list);
scroll.setBorder(BorderFactory.createTitledBorder("音乐"));
scroll.setBounds(20,250,250,80);
ok=new JButton("ok");
ok.setBounds(150,345,50,30);
ok.setBackground(Color.blue);
ok.addActionListener(this);
//scroll.setBackground(Color.blue);
add(scroll);
add(ok);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
MusicDetailsDialog.this.setVisible(false);
MusicDetailsDialog.this.dispose();
//System.exit(0);
}
});
setBounds(200,200,400,410);
setVisible(true);
validate();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==ok){
MusicDetailsDialog.this.setVisible(false);
}
}
public void delWith(String name, String selectedAreaname,MusicDataClient mclient) {
// TODO Auto-generated method stub
String names[]=name.split("-");
String action=names[0].trim();
String singer=names[1].trim();
tf_singer.setText(action);
tf_actname.setText(singer);
tf_type.setText(selectedAreaname);
tf_price.setText((float)Math.random()*100+"元");
Map<String, Vector<MusicRecording>> areaRecord=mclient.areaRecord;
Vector<MusicRecording> areat=areaRecord.get(selectedAreaname);
Iterator<MusicRecording> itarea=areat.iterator();
while(itarea.hasNext()){
MusicRecording mu=itarea.next();
Recording muR=mu.getRecord();
if(muR.getSingername().equals(action)){
//注意图片名里的空格要去掉,最好用一个单独的变量接受之后再赋值
String singerP=mu.getSingerphoto().trim();
Icon icon=new ImageIcon("image/"+singerP);
//icon判断图片的有无,可以通过高度和宽度做
if(icon.getIconHeight()<0 && icon.getIconWidth()<0){
personicon.setIcon(new ImageIcon("image/暂无图片.jpg"));
}
else{
personicon.setIcon(icon);
}
Vector<Track> redioTrack=muR.getTrack();
Iterator<Track> track1=redioTrack.iterator();
int sum=0;
while(track1.hasNext()){
Track tr=track1.next();
int trtime=tr.getDuration().getTotaltime();
int hour1=trtime/3600;
int minute1=trtime%3600/60;
int second1=trtime%3600%60;
String formtTime=null;
if(hour1==0){
formtTime=formatT(minute1)+":"+formatT(second1);
}
else{
formtTime=formatT(hour1)+":"+formatT(minute1)+":"+formatT(second1);
}
titleandtime.add(tr.getTitle()+","+" "+formtTime);
sum=sum+tr.getDuration().getTotaltime();
}
int hour=sum/3600;
int minute=sum%3600/60;
int second=sum%3600%60;
String strlen=null;
if(hour==0){
strlen=format(minute)+"分"+format(second)+"秒";
}
else{
strlen=format(hour)+"时"+format(minute)+"分"+format(second)+"秒";
}
System.out.println("一张专辑的长度"+strlen);
System.out.println("一张专辑的歌曲"+titleandtime);
tf_length.setText(strlen);
list.setListData(titleandtime);
break;
}
}
}
private String formatT(int second1) {
// TODO Auto-generated method stub
if(second1==0) return "";
if(second1>0 && second1<=9) return "0"+second1;
return second1+"";
}
private String format(int second2) {
// TODO Auto-generated method stub
if(second2<=9 && second2>0) return "0"+second2;
if(second2==0) return "";
return second2+"";
}
}
5.Java GridLayout的综合使用(java小计算器的设计)
class WindowGridCalTool extends JFrame implements ActionListener{
JPanel p2;
JLabel label;
JTextField text;
JMenuBar bar;
JMenu menu1,menu2,menu3;
JButton but,buttonClear;
char operator='+';
StringBuffer buf=new StringBuffer();
Double a=0.0d,b=0.0d;
WindowGridCalTool(String s) {
// TODO Auto-generated constructor stub
setTitle(s);
Container con=getContentPane();
menu1=new JMenu("编辑");
menu2=new JMenu("查看");
menu3=new JMenu("帮助");
bar=new JMenuBar();
bar.add(menu1);
bar.add(menu2);
bar.add(menu3);
setJMenuBar(bar);
text=new JTextField(10);
p2=new JPanel();
GridLayout grid=new GridLayout(4,4);
p2.setLayout(grid);
buttonClear=new JButton("Clear");
buttonClear.addActionListener(this);
buttonClear.setSize(150,20);
char[] ch={'1','2','3','+','4','5','6','-','7','8','9','*','0','=','.','/'};
int k=0;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
but=new JButton(String.valueOf(ch[k++]));
but.addActionListener(this);
p2.add(but);
}
}
con.add(text,BorderLayout.NORTH);
con.add(p2,BorderLayout.CENTER);
con.add(buttonClear,BorderLayout.SOUTH);
setVisible(true);
setSize(250,300);
setResizable(false);
validate();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//判断数学符号串
public static boolean equalsOpe(char che){
switch(che){
case '+':return true;
case '-':return true;
case '*':return true;
case '/':return true;
default:return false;
}
}
//数据符号的操作
public double getCalDataOperator(double first,char operatorC,double second){
double apm=0.0d;
switch(operatorC){
case '+':apm=a+b;break;
case '-':apm=a-b;break;
case '*':apm=a*b;break;
case '/':apm=a/b;break;
default:apm=0.0d;
}
return apm;
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==buttonClear){
text.setText(0.0+"");
buf=new StringBuffer();
a=0.0d;b=0.0d;
}
else{
String butValue=e.getActionCommand();
char ch=butValue.charAt(0);
Character c=new Character(ch);
if(c.isDigit(ch) || c.equals('.')){
buf.append(butValue);
text.setText(buf.toString());
}
else if(c.equals('=')){
try {
b=Double.parseDouble(buf.toString());
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(b==0 && operator=='/'){
text.setText("除数不能为0");
}
else{
text.setText(String.valueOf(getCalDataOperator(a,operator,b)));
a=getCalDataOperator(a,operator,b);
}
buf=new StringBuffer();
buf.append(String.valueOf(getCalDataOperator(a,operator,b)));
}
else if(equalsOpe(ch)){
try {
if(a==0.0d){
a=Double.parseDouble(buf.toString());
}
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
operator=ch;
buf=new StringBuffer();
}
}
}
}
public class GridCalToolTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
new WindowGridCalTool("这是小计算器");
}
}
----------------------------------------------------------------------------
Java 集合的学习
1.Java的LinkedListTest的使用
public class LinkedListTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
WindowShop shop=new WindowShop("商品信息");
}
}
class Shop implements Serializable{
String name,price;
public Shop(String name, String price) {
super();
this.name = name;
this.price = price;
}
}
class WindowShop extends JFrame implements ActionListener{
LinkedList goodslist=null;
File file=new File("shop.dat");
JTextField name=new JTextField(20);
JTextField price=new JTextField(20);
JTextField deleteF=new JTextField(20);
JButton addshop=new JButton("添加商品");
JButton delshop=new JButton("删除商品");
JTextArea area=new JTextArea(10,5);
public WindowShop(String string) {
setTitle(string);
goodslist=new LinkedList();
Container con=this.getContentPane();
con.setLayout(new GridLayout(1,2));
//创建一个从上到下显示其组件的 Box。Box 包含的所有组件都有一个固定大小
Box box1=Box.createVerticalBox();
box1.add(new JLabel("输入名称:"));
box1.add(new JLabel("输入单价:"));
box1.add(new JLabel("单击添加:"));
box1.add(new JLabel("删除的名称:"));
box1.add(new JLabel("点击删除:"));
Box box2=Box.createVerticalBox();
box2.add(name);
box2.add(price);
box2.add(addshop);
addshop.addActionListener(this);
box2.add(deleteF);
deleteF.addActionListener(this);
box2.add(delshop);
delshop.addActionListener(this);
Box baseBox=Box.createHorizontalBox();
baseBox.add(box1);
baseBox.add(box2);
con.add(baseBox);
con.add(area);
setSize(400,100);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==addshop){
String names,prices;
names=name.getText();
prices=price.getText();
name.setText(null);
price.setText(null);
if(file.exists()){
if(names.length()>0 && prices.length()>0){
Shop shop=new Shop(names,prices);
try {
FileInputStream in=new FileInputStream(file);
ObjectInputStream inOb=new ObjectInputStream(in);
goodslist=(LinkedList) inOb.readObject();
inOb.close();
goodslist.add(shop);
FileOutputStream out=new FileOutputStream(file);
ObjectOutputStream outOb=new ObjectOutputStream(out);
outOb.writeObject(goodslist);
outOb.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (ClassNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
else{
name.setText("名称,价格必须输入值!");
}
}
else if(!file.exists()){
if(names.length()>0 && prices.length()>0){
Shop shop=new Shop(names,prices);
goodslist.add(shop);
FileOutputStream out;
try {
out = new FileOutputStream(file);
ObjectOutputStream outOb=new ObjectOutputStream(out);
outOb.writeObject(goodslist);
outOb.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
}
else{
name.setText("名称,价格必须输入值!");
}
}
showing();
}
if(e.getSource()==delshop){
String named=deleteF.getText();
FileInputStream in;
try {
in = new FileInputStream(file);
ObjectInputStream inOb=new ObjectInputStream(in);
goodslist=(LinkedList) inOb.readObject();
inOb.close();
for(int i=0;i<goodslist.size();i++){
Shop s=(Shop) goodslist.get(i);
if(s.name.equals(named)){
goodslist.remove(i);
}
}
FileOutputStream out=new FileOutputStream(file);
ObjectOutputStream outOb=new ObjectOutputStream(out);
outOb.writeObject(goodslist);
outOb.close();
deleteF.setText(null);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (ClassNotFoundException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
showing();
}
}
public void showing() {
// TODO Auto-generated method stub
area.setText(null);
FileInputStream in;
try {
in = new FileInputStream(file);
ObjectInputStream inOb=new ObjectInputStream(in);
goodslist=(LinkedList) inOb.readObject();
inOb.close();
Iterator<Shop> ss=goodslist.iterator();
while(ss.hasNext()){
Shop shops=ss.next();
area.append("商品名称是:"+shops.name+"\n");
area.append("商品价格是:"+shops.price+"\n");
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
--------------------------------
2.List集合
public class TestList {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//String的List集合 可以重复,按输入顺序输出
System.out.println("输出字符的集合!");
List<String> is=new ArrayList<String>();
is.add("liu");
is.add("li");
is.add("liu");
is.add("li");
System.out.println("整理前的List<String>列表!");
Iterator<String> it=is.iterator();
while(it.hasNext()){
String temp1=it.next();
System.out.println(temp1);
}
System.out.println("整理后的List<String>列表!");
Iterator<String> it1=is.iterator();
while(it1.hasNext()){
String temp=it1.next();
if("li".equals(temp)){
it1.remove();
continue;
}
System.out.println(temp);
}
//class对象集合
System.out.println("输出对象的集合!");
List<Student> lis=new ArrayList<Student>();
lis.add(new Student("liu",20));
lis.add(new Student("li",21));
lis.add(new Student("liu",20));
lis.add(new Student("li",21));
System.out.println("整理前的List列表!");
Iterator<Student> ite1=lis.iterator();
while(ite1.hasNext()){
Student tempStu0=ite1.next();
System.out.println("name:"+tempStu0.getName()+" "+"age:"+tempStu0.getAge());
}
int index,i,j=0,n=0;
for(i=0;i<lis.size();i++){
Student tempStu=(Student)lis.get(i);
index=i;
//n的值必须在外面定义,否则会出现数组越界
n=++i;
while(n<lis.size()){
if(compared(tempStu,(Student)(lis.get(n)))){
//移除列表中指定位置的元素(可选操作)。将所有的后续元素向左移动(将其索引减 1)。返回从列表中移除的元素。
lis.remove(n);
System.out.println("lis.size()的大小"+lis.size());
continue;
}
else{
n++;
}
}
if(n>=lis.size()){
//System.out.println("name:"+tempStu.getName()+" "+"age:"+tempStu.getAge());
i=index;
}
}
System.out.println("整理后的List列表!");
Iterator<Student> ite=lis.iterator();
while(ite.hasNext()){
Student tempStu1=ite.next();
System.out.println("name:"+tempStu1.getName()+" "+"age:"+tempStu1.getAge());
}
/*
* Iterator<Student> ite=lis.iterator();
* while(ite.hasNext()){
Student tempStu=ite.next();
while(ite.hasNext()){
if(compared(tempStu,ite.next())){
ite.remove();
continue;
}
}
if(!ite.hasNext()){
System.out.println("name:"+tempStu.getName()+" "+"age:"+tempStu.getAge());
}
}*/
}
private static boolean compared(Student tempStu, Student next) {
// TODO Auto-generated method stub
if(tempStu.getAge()==next.getAge()){
if(tempStu.getName().equals(next.getName())){
return true;
}
else{
return false;
}
}
else{
return false;
}
}
}
---------------------------------------
3.HashSet集合的使用
public class SetTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
*
* set集合无序:输入的元素和输出的元素不一致
* 不重复:有重复的元素,后一个会覆盖前一个,输出只有一个
*/
//字符元素
Set<String> set =new HashSet<String>();
System.out.println("set字符元素为:");
set.add("bb");
set.add("aa");
set.add("cc");
set.add("dd");
System.out.println("set集合整体输出:"+set);
//set.clear();
int a=set.size();
System.out.println("set集合长度:"+a);
Iterator<String> ie=set.iterator();
while(ie.hasNext()){
String temp1=ie.next();
System.out.println(temp1);
}
//对象
Set <Student> vr=new HashSet<Student>();
vr.add(new Student("aaa",23));
vr.add(new Student("bbb",22));
vr.add(new Student("ccc",21));
vr.add(new Student("ddd",20));
System.out.println("类整体输出:"+vr);
Iterator<Student> is=vr.iterator();
while(is.hasNext()){
Student ds=is.next();
System.out.println("name:"+ds.getName()+" "+"age:"+ds.getAge());
}
}
}
-----------------------------------------------------------------------------------------
4.TreeSet集合的使用
TreeSet要求要添加的对象具有排序的功能
public class TreeSortTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
/**
*
* TreeSet有排序功能,因此要求添加的类型必须可以比较大小
* 如果重复 后一个会覆盖前一个
* TreeSet可以定位第一位和最后一位
*/
// 构造一个新的空 set,该 set 根据其元素的自然顺序进行排序。
// 字符可以根据其字典顺序排序
TreeSet<String> tr = new TreeSet<String>();
tr.add("aa");
tr.add("bb");
tr.add("cc");
tr.add("dd");
tr.add("ee");
System.out.println("TreeSet集合整体输出:"+tr);
Iterator<String> ite = tr.iterator();
while (ite.hasNext()) {
String nd = ite.next();
System.out.println(nd);
}
// 由于<Student>对象本身不具有比较大小的功能,
// 1.可以使<Student>具有比较大小的功能
// 2.使集合具有比较大小的功能,使用匿名类
TreeSet<Student> ts = new TreeSet<Student>(new Comparator<Object>() {
public int compare(Object a, Object b) {
Student st1 = (Student) a;
Student st2 = (Student) b;
if (st1.getAge() == st2.getAge()) {
if (st1.getName().equals(st2.getName())) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
});
ts.add(new Student("aaa", 12));
ts.add(new Student("aaa", 12));
ts.add(new Student("ccc", 14));
ts.add(new Student("ddd", 15));
Iterator<Student> id = ts.iterator();
while (id.hasNext()) {
Student st = id.next();
System.out.println("name:" + st.getName() + " " + "age:"
+ st.getAge());
}
}
}
--------------------------------------------
5.Vector的使用
在java基础阶段,Vector用处较频繁一些,对于Jlist和JcomboBox中的数据都可用它
public class VectorTest {
public static void main(String[] args) {
//字符类型
//Vector 类可以实现可增长的对象数组
//构造一个空向量,使其内部数据数组的大小为 10,其标准容量增量为零。每次>3后以3倍增加
Vector<String> vc=new Vector<String>(4);
vc.add("1");
vc.add("2");
vc.add("3");
vc.add("4");
System.out.println("整体输出Vector:"+vc);
int a=vc.capacity();
/**
* 下面两效果一致,都是清空列表
*/
//vc.clear();
//vc.removeAllElements();
/**
* 实际删除的是第三个元素
*/
//vc.remove(2);
//vc.removeElementAt(2);
System.out.println("此集合的长度:"+a);
Iterator<String> it=vc.iterator();
while(it.hasNext()){
String temp0=it.next();
if(temp0.contains("1")){
it.remove(); //删除对象为1
continue;
}
System.out.println(temp0);
}
//对象类型
Vector<Student> vc1=new Vector<Student>();
vc1.add(new Student("k8",23));
vc1.add(new Student("k7",22));
vc1.add(new Student("k6",21));
vc1.add(new Student("k5",20));
Iterator<Student> it1=vc1.iterator();
while(it1.hasNext()){
Student df=it1.next();
if(df.getName().contains("k8") && (String.valueOf(df.getAge())).contains("23")){
it1.remove();
continue;
}
System.out.println("name:"+df.getName()+" "+"age:"+df.getAge());
}
//Vector的其它联系
Vector<Student> vca=new Vector<Student>(vc1);
Iterator<Student> ita=vca.iterator();
while(ita.hasNext()){
Student em=(Student) ita.next();
System.out.println("Vector 内套"+em.getName());
}
}
}
-----------------------------------------
6.HashMap的使用(key-value)
public class VectorTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//字符类型
//Vector 类可以实现可增长的对象数组
//构造一个空向量,使其内部数据数组的大小为 10,其标准容量增量为零。每次>3后以3倍增加
Vector<String> vc=new Vector<String>(4);
vc.add("1");
vc.add("2");
vc.add("3");
vc.add("4");
System.out.println("整体输出Vector:"+vc);
int a=vc.capacity();
/**
* 下面两效果一致,都是清空列表
*/
//vc.clear();
//vc.removeAllElements();
/**
* 实际删除的是第三个元素
*/
//vc.remove(2);
//vc.removeElementAt(2);
System.out.println("此集合的长度:"+a);
Iterator<String> it=vc.iterator();
while(it.hasNext()){
String temp0=it.next();
if(temp0.contains("1")){
it.remove(); //删除对象为1
continue;
}
System.out.println(temp0);
}
//对象类型
Vector<Student> vc1=new Vector<Student>();
vc1.add(new Student("k8",23));
vc1.add(new Student("k7",22));
vc1.add(new Student("k6",21));
vc1.add(new Student("k5",20));
Iterator<Student> it1=vc1.iterator();
while(it1.hasNext()){
Student df=it1.next();
if(df.getName().contains("k8") && (String.valueOf(df.getAge())).contains("23")){
it1.remove();
continue;
}
System.out.println("name:"+df.getName()+" "+"age:"+df.getAge());
}
//Vector的其它联系
Vector<Student> vca=new Vector<Student>(vc1);
Iterator<Student> ita=vca.iterator();
while(ita.hasNext()){
Student em=(Student) ita.next();
System.out.println("Vector 内套"+em.getName());
}
}
}
--------------------------------------------------------------------------
7.Java 集合的综合使用,包括如何读取文件
public class MusicDataAccessornew {
File ff=new File("music.db");
BufferedReader br;
String s=null;
Map<String,Vector<Track>> trackDuration=new HashMap<String,Vector<Track>>();
Map<String,Vector<NewMusicRecording>> musicRecord=new HashMap<String,Vector<NewMusicRecording>>();
String singername,singer,area;
public MusicDataAccessornew(){
try {
br=new BufferedReader(new InputStreamReader(new FileInputStream(ff)));
String[] firstLine=null;
int singerCount=0;
Vector<NewMusicRecording> musictotal = null;
//=new Vector<NewMusicRecording>();
while((s=br.readLine())!=null){
firstLine=s.split(",");
NewMusicRecording music=new NewMusicRecording();
//Recording record=new Recording();
singername=firstLine[0].trim();
singer=firstLine[1].trim();
area=firstLine[2].trim();
String singerPhoto=firstLine[3].trim();
String singercount=firstLine[4].trim();
music.setSingername(singername);
music.setRecordname(singer);
music.setArea(area);
music.setSingerphoto(singerPhoto);
try {
singerCount=Integer.parseInt(singercount);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
music.setSingercount(singerCount);
String nextNumLine[]=null;
Vector<Track> track1=new Vector<Track>();
for(int i=0;i<singerCount;i++){
s=br.readLine();
nextNumLine=s.split(",");
Track track=new Track(nextNumLine[0].trim(),new Duration(Integer.parseInt(nextNumLine[1].trim())));
track1.add(track);
}
trackDuration.put(singername+" - "+singer,track1);
music.setTrack(track1);
//music.setRecord(record);
if(musicRecord.get(area)==null){
musictotal=new Vector<NewMusicRecording>();
musictotal.add(music);
musicRecord.put(area, musictotal);
}
else if(musicRecord.get(area)!=null){
musictotal.add(music);
musicRecord.put(area, musictotal);
}
br.readLine();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//readFile(ff);
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("读取·music .record .集合");
readMusicRecord(musicRecord);
System.out.println("读取.record.track 集合");
readRecordTrack(trackDuration);
}
private void readRecordTrack(Map<String, Vector<Track>> trackDuration2) {
// TODO Auto-generated method stub
this.trackDuration=trackDuration2;
Set<Map.Entry<String, Vector<Track> >> redioTrack=trackDuration2.entrySet();
Iterator<Map.Entry<String,Vector<Track> > > itredioT=redioTrack.iterator();
while(itredioT.hasNext()){
Map.Entry<String,Vector<Track> > sT=itredioT.next();
System.out.println("key:"+sT.getKey()+"........");
Vector<Track> tr=trackDuration2.get(sT.getKey());
Iterator<Track> ittr=tr.iterator();
while(ittr.hasNext()){
Track ta=ittr.next();
System.out.print("标题:"+ta.getTitle()+"时间:"+ta.getDuration().getTotaltime()+">>>>>>>");
}
System.out.println();
}
}
private void readMusicRecord(
Map<String, Vector<NewMusicRecording>> musicRecord2) {
// TODO Auto-generated method stub
this.musicRecord=musicRecord2;
Set<Map.Entry<String, Vector<NewMusicRecording> >> mr1= musicRecord2.entrySet();
Iterator<Map.Entry<String, Vector<NewMusicRecording> >> mr2=mr1.iterator();
while(mr2.hasNext()){
Map.Entry<String, Vector<NewMusicRecording>> mr3=mr2.next();
System.out.println("key:"+mr3.getKey()+"---------");
Vector<NewMusicRecording> mr4=musicRecord2.get(mr3.getKey());
Iterator<NewMusicRecording> mr5=mr4.iterator();
while(mr5.hasNext()){
NewMusicRecording mr6=mr5.next();
System.out.println("歌手姓名歌曲:"+mr6.getSingername()+" - "+mr6.getSingername());
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new MusicDataAccessornew();
}
}
----------------------------------------
Java.io
1.文件名的过滤
class FileAccept implements FilenameFilter{
String str=null;
public FileAccept(String string) {
// TODO Auto-generated constructor stub
str="."+string;
}
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.endsWith(str);
}
}
public class FileCreateAndDelete {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File dir=new File("E:\\LZLWorkSpace\\exitJavaProgram");
File deletedFile=new File(dir,"A.java");
boolean boo=true;
if(!deletedFile.exists()) {
//必须用deletedFile.createNewFile()才能创建文件
boo=deletedFile.createNewFile();
System.out.println("创建文件:"+boo);
}
//FileAccept类获得特定类型的文件
FileAccept accept=new FileAccept("java");
//用File对象返回目录下的指定类
File fileName[]=dir.listFiles(accept);
//用String返回目录下的指定类型的所有文件
String[] filename=(String[]) dir.list(accept);
for(int i=0;i<fileName.length;i++){
System.out.println("文件名称:"+fileName[i].getName());
}
System.out.println("字符类型的文件名列表:");
for(int j=0;j<filename.length;j++){
System.out.println("文件名称:"+filename[j]);
}
boo=deletedFile.delete();
if(deletedFile.exists()){
//必须有deletedFile.delete()才能删除文件
System.out.println("文件"+deletedFile.getName()+"被删除"+deletedFile.delete());
}
}
}
--------------------------------------------
2.字符输入输出流
public class EnglishTestIO {
public static void main(String[] args) {
// TODO Auto-generated method stub
WindowInputStream win=new WindowInputStream("英语选择题");
}
}
class WindowInputStream extends JFrame implements ActionListener{
JLabel title,choiceanswer,yourscore;
JTextField titletext,tfscore;
JPanel p1,p2,p3,p4,p5;
JRadioButton box[];
JButton repeat,next;
File file=new File("E:/LZLWorkSpace/exitJavaProgram/02.txt");
FileReader inreader;
BufferedReader buf;
String s;
String str[]=new String[7];
int score;
public WindowInputStream(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
Container con=getContentPane();
con.setLayout(new BorderLayout());
title=new JLabel("题目");
titletext=new JTextField(50);
p1=new JPanel();
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
p1.add(title);p1.add(titletext);
choiceanswer=new JLabel("选择答案:");
box=new JRadioButton[4];
p2=new JPanel();p2.add(choiceanswer);
for(int i=0;i<4;i++){
box[i]=new JRadioButton("",false);
box[i].addActionListener(this);
//box[i].addItemListener(this);
p2.add(box[i]);
}
p3=new JPanel();
yourscore=new JLabel("你的得分:");
tfscore=new JTextField(20);
p3.add(yourscore);p3.add(tfscore);
p4=new JPanel();
p4.setLayout(new BorderLayout());
p4.add(p2,BorderLayout.CENTER);p4.add(p3,BorderLayout.SOUTH);
repeat=new JButton("重新练习");next=new JButton("下一题目");
repeat.addActionListener(this);next.addActionListener(this);
p5=new JPanel();
p5.add(repeat);p5.add(next);
con.add(p1,BorderLayout.NORTH);
con.add(p4,BorderLayout.CENTER);
con.add(p5,BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
try {
inreader=new FileReader(file);
buf=new BufferedReader(inreader);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
setSize(600,300);
setVisible(true);
reading();
validate();
}
public void reading(){
int i=0;
try {
s=buf.readLine();
while(!s.startsWith("endend")){
StringTokenizer token=new StringTokenizer(s,"#");
while(token.hasMoreElements()){
if(i>=7) break;
str[i]=token.nextToken();
i++;
}
titletext.setText(str[0]);
for(int j=1;j<=4;j++){
box[j-1].setText(str[j]);
}
}
if(s.startsWith("endend")){
titletext.setText("学习完毕!");
for(int j=0;j<4;j++){
box[j].setText("end");
buf.close();
inreader.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
titletext.setText("无试题文件!");
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==repeat){
System.out.println("重新做");
score=0;
tfscore.setText("得分:"+score);
try {
inreader=new FileReader(file);
buf=new BufferedReader(inreader);
} catch (FileNotFoundException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
reading();
}
else if(e.getSource()==next){
System.out.println("下一题");
reading();
for(int j=0;j<4;j++){
box[j].setEnabled(true);
}
}
else{
System.out.println(str[5]);
for(int i=0;i<4;i++){
System.out.println(box[i].getText());
if(box[i].getText().equals(str[5]) && box[i].isSelected()){
score++;
tfscore.setText("得分:"+score);
}
box[i].setEnabled(false);
}
}
}
}
3.带进度条的输入输出流(包括线程的使用)
public class TestProgressBar1 {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
new WindowFileProgress1("带进度条的文件拷贝系统");
}
}
class WindowFileProgress1 extends JFrame implements Runnable {
JProgressBar bar;
JLabel lbar,tf1,tf2;
JTextField f1,f2;
JButton start;
JPanel p1,p2;
JButton b1,b2;
Thread progressth,copy;
public WindowFileProgress1(String string) {
// TODO 自动生成构造函数存根
setTitle(string);
progressth=new Thread(this);
copy=new Thread(this);
Container con=getContentPane();
p1=new JPanel();
p1.setLayout(new GridLayout(3,3));
con.setLayout(new BorderLayout());
lbar=new JLabel("文件传送进度条:");
bar=new JProgressBar(JProgressBar.HORIZONTAL);
bar.setStringPainted(true);
bar.setString("程序加载中,请稍候......");
bar.setBackground(Color.cyan);
tf1=new JLabel("文件一:");
f1=new JTextField(20);
tf2=new JLabel("文件二:");
f2=new JTextField(20);
b1=new JButton("打开第一个文件");
b1.addActionListener(new ButtonActionListener());
b2=new JButton("打开第二个文件");
b2.addActionListener(new ButtonActionListener());
p1.add(lbar);p1.add(bar);p1.add(new JLabel(""));
p1.add(tf1);p1.add(f1);p1.add(b1);
p1.add(tf2);p1.add(f2);p1.add(b2);
p2=new JPanel();
start=new JButton("开始拷贝");
start.addActionListener(new ButtonActionListener());
bar.setMinimum(0);
bar.setMaximum(100);
p2.add(start);
con.add(p1,BorderLayout.CENTER);
con.add(p2,BorderLayout.SOUTH);
setVisible(true);
this.setSize(500,200);
validate();
}
public class ButtonActionListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
// TODO 自动生成方法存根
if(e.getSource()==start){
if(!progressth.isAlive()){
progressth=new Thread(WindowFileProgress1.this);
copy=new Thread(WindowFileProgress1.this);
}
progressth.start();
copy.start();
}
else{
JFileChooser fileC=new JFileChooser(new File("E:\\LZLjava勿删"));
fileC.showOpenDialog(WindowFileProgress1.this);
String filename=fileC.getSelectedFile().getAbsolutePath();
if(e.getSource()==b1){
f1.setText(filename);
}
else if(e.getSource()==b2){
f2.setText(filename);
}
}
}
}
public void run() {
// TODO Auto-generated method stub
if(Thread.currentThread()==progressth){
System.out.println("时间进度条");
for(int i=1;i<=100;i++){
int value=bar.getValue();
bar.setValue(value+1);
bar.setString((value+1)+"%");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}
}
else if(Thread.currentThread()==copy){
String filename1=f1.getText();
String filename2=f2.getText();
if(filename1.length()<=0 || filename2.length()<=0){
JOptionPane.showMessageDialog(null, "文件名不能为空");
return;
}
File f1=new File(filename1);
byte[] b=new byte[(int) f1.length()];
int c=0;
FileInputStream in=null;
FileOutputStream out=null;
BufferedInputStream bufin=null;
BufferedOutputStream outbuf=null;
int count=0;
try {
in=new FileInputStream(f1);
bufin=new BufferedInputStream(in);
//ProgressMonitorInputStream pp=new ProgressMonitorInputStream(bar,"读取文件",in);
//ProgressMonitor p=pp.getProgressMonitor();
out=new FileOutputStream(new File(filename2));
outbuf=new BufferedOutputStream(out);
//int length=bufin.read(b);
//b=null;
while((c=bufin.read(b,0,(int) (f1.length()/100)))!=-1){
outbuf.write(b);
outbuf.flush();
Thread.sleep(200);
}
}
catch(IOException e){
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bufin.close();
outbuf.close();
JOptionPane.showMessageDialog(null, "文件读取完成");
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
}
------------------------------------------------------------------------
4.ObjectInputStream 与 ObjectOutputStream的使用
对象输入输出流,要求输入输出的对象具有序列化,对于bean类要实现序列化(Serializable)
package com.lzl.io;
import java.io.*;
class Student implements Serializable{
private String num;
private String name;
private int age;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String num, String name, int age) {
super();
this.num = num;
this.name = name;
this.age = age;
}
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class ObjectInputStreamDeal {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Student str=new Student("001","liu",20);
FileOutputStream out;
try {
//字节流
out = new FileOutputStream("s.txt");
ObjectOutputStream ob=new ObjectOutputStream(out);
ob.writeObject(str);
FileInputStream in=new FileInputStream("s.txt");
ObjectInputStream obin=new ObjectInputStream(in);
Student ll=(Student) obin.readObject();
ll.setNum("002");
ll.setName("li");
ll.setAge(23);
System.out.println("编号:"+str.getNum()+"姓名:"+str.getName()+"年龄:"+str.getAge());
System.out.println("编号:"+ll.getNum()+"姓名:"+ll.getName()+"年龄:"+ll.getAge());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Java.lang.Thread
Java中的线程是为了解决同步问题而存在的
Java虚理机允许并发执行多个线程,日常生活中做一件事的同时也在做另一件事(如:看视频时想听音乐)
创建线程包括两种方法
1. 通过子线程创建
2. 通过Runnable实现
1.子线程问题
对于主线程和子线程,先运行主线程
public class ThreadTest1 {
/**
* @param args
*/
public static void main(String[] args) {
Thread1 t = new Thread1();
//new Thread(t).start();
t.start();
while(true){
System.out.println(Thread.currentThread().getName() + " : 干其他事儿......");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Thread1 extends Thread{
@Override
public void run() {
while(true){
System.out.println(this.getName() +" : hello world......");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
---------------------------------------------------
public class ThreadSubClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
People teacher,student;
ComputerSum sum=new ComputerSum();
teacher=new People("老师",200,sum);
student=new People("学生",200,sum);
teacher.start();
student.start();
}
}
class ComputerSum{
int sum;
public void setSum(int sum){
this.sum=sum;
}
public int getSum(){
return sum;
}
}
class People extends Thread{
int timelength;
ComputerSum sum;
People(String s,int timeLength,ComputerSum sum){
setName(s);
this.timelength=timeLength;
this.sum=sum;
}
//两个线程共享一个对象,一个中断,
public void run(){
for(int i=1;i<=3;i++){
int m=sum.getSum();
sum.setSum(m+1);
System.out.println("我是"+getName()+",现在的和:"+sum.getSum());
try{
sleep(timelength);
}
catch(InterruptedException e){}
}
}
}
-------------------------------------------------------------
2.下面是一个赛跑问题,Runnable创建线程
public class RubbitAndWuGuiMatch {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WindowThreadMatch win=new WindowThreadMatch("这是一个龟兔赛跑的游戏");
}
}
class WindowThreadMatch extends JFrame implements ActionListener,Runnable{
RubbitCanvas rubbit;
WuGuiCanvas wugui;
JButton start;
Thread trubbit,twugui;
//这里的x,y在容器里都是相对位移
int x1=150,y1=0,x2=150,y2=0;
int rsu=0,wsu=0;
JPanel pane,pane1;
class RubbitCanvas extends Canvas{
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
g.setColor(Color.CYAN);
g.fillRect(x1, y1, 30, 30);
}
}
class WuGuiCanvas extends Canvas{
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
g.setColor(Color.red);
g.fillOval(x2, y2, 30, 30);
}
}
public WindowThreadMatch(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
rubbit=new RubbitCanvas();
rubbit.setBackground(Color.DARK_GRAY);
wugui=new WuGuiCanvas();
wugui.setBackground(Color.LIGHT_GRAY);
start=new JButton("比赛开始");
start.addActionListener(this);
pane=new JPanel();
pane.add(start);
pane1=new JPanel();
pane1.setLayout(new GridLayout(1,2));
pane1.add(rubbit);pane1.add(wugui);
Container con=getContentPane();
con.setLayout(new BorderLayout());
con.add(pane,BorderLayout.NORTH);
con.add(pane1,BorderLayout.CENTER);
setSize(600,600);
setVisible(true);
validate();
}
@Override
public void run() {
// TODO Auto-generated method stub
int length=500;
rsu=(int)(Math.random()*100)+5;
wsu=(int)(Math.random()*100)+1;
double t=0;
while(true){
t=t+0.2;
if(Thread.currentThread()==trubbit){
y1=(int) (rsu*t);
if(y1>=length) y1=length;
rubbit.repaint();
}
else if(Thread.currentThread()==twugui){
y2=(int)(wsu*t);
if(y2>=length) y2=length;
wugui.repaint();
}
try{
Thread.sleep(500);
}
catch(InterruptedException e){
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==start){
trubbit=new Thread(this);
trubbit.start();
twugui=new Thread(this);
twugui.start();
}
}
}
--------------------------------------------------------
3.Runnable两个小球,一个平抛,另一个自由落体
class MyCanvas extends Canvas{
Color c;
public MyCanvas(Color c){
this.c=c;
}
public void paint(Graphics g){
g.setColor(c);
g.fillOval(0, 0, 20, 20);
}
}
public class ThreadBallDownOrFlow extends JFrame implements Runnable{
/**
*
*/
private static final long serialVersionUID = 1L;
MyCanvas red,blue;
Thread redBall,blueBall;
double t=0;
public void init() {
// TODO Auto-generated method stub
this.setTitle("小球自由落体和平抛运动");
setBounds(10,10,500,600);
Container con=getContentPane();
con.setLayout(null);
red=new MyCanvas(Color.RED);
red.setBounds(200,200,300,500);
//red.setBackground(Color.cyan);
blue=new MyCanvas(Color.BLUE);
blue.setBounds(200,200,300,500);
//blue.setBackground(Color.orange);
con.add(blue);con.add(red);
con.setBounds(20,20,400,500);
redBall=new Thread(this);
blueBall=new Thread(this);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
redBall.start();
blueBall.start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
t=t+0.2;
if(t>=10) t=0;
if(Thread.currentThread()==redBall){
int x=200,y=200;
y=(int) (60+1.0/2*5*t*t);
if(y>=500){
y=200;
}
red.setLocation(x,y);
try{
Thread.sleep(200);
}
catch(InterruptedException e){}
}
else if(Thread.currentThread()==blueBall){
int x=200,y=200;
x=(int) (200+16*t);
y=(int) (60+1.0/2*5*t*t);
if(y>=500){
y=200;
x=200;
}
if(x>=400){
x=200;
}
blue.setLocation(x, y);
try{
Thread.sleep(200);
}
catch(InterruptedException e){}
}
}
}
/**
* method main
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ThreadBallDownOrFlow th=new ThreadBallDownOrFlow();
th.init();
}
}
-------------------------------------------------------------------------------------
4.子线程与主线程的综合使用(实现计数功能)
public class ThreadTest2 extends JFrame {
/**
* @param args
*/
private JLabel top,bottom;
public ThreadTest2(){
this.top = new JLabel("counter0: ",JLabel.CENTER);
this.bottom = new JLabel("counter1: ",JLabel.CENTER);
this.getContentPane().setLayout(new GridLayout(2,1));
this.getContentPane().add(top);
this.getContentPane().add(bottom);
this.setBounds(300, 300, 300, 150);
this.setVisible(true);
new Counter0Thread().start();
new Thread(new Counter1Thread()).start();
}
public static void main(String[] args) {
new ThreadTest2();
}
class Counter0Thread extends Thread{
int counter = 0;
@Override
public void run() {
while(true){
top.setText("counter0: " +this.counter++);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Counter1Thread implements Runnable{
int counter = 0;
@Override
public void run() {
while(true){
bottom.setText("counter1: " +this.counter++);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
5.Runnable 的使用
public class ThreadUseRunnable {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Bank bank=new Bank();
bank.setMoney(300);
bank.account.start();
bank.cash.start();
}
}
//Runnable用Thread直接创建线程
class Bank implements Runnable{
Thread account,cash;
private int money;
Bank(){
account=new Thread(this);
account.setName("会计");
cash=new Thread(this);
cash.setName("出纳");
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
money=money-50;
if(Thread.currentThread()==account){
System.out.println("我是"+account.getName()+",现在有:"+money+"元");
if(money<=150){
System.out.println(account.getName()+"进入死亡状态");
return; //退出account的run方法,如果有另一个线程,他开始执行自己的方法run
}
}
else if(Thread.currentThread()==cash){
System.out.println("我是"+cash.getName()+",现在有"+money+"元");
if(money<=0){
System.out.println(cash.getName()+"进入死亡状态!");
return;
}
}
try{
Thread.sleep(800); //当前线程释放自己的资源,另一个线程开始执行
}
catch(InterruptedException e){}
}
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
-------------------------------------
6.时间进度表
public class ThreadTime {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自动生成方法存根
new WindowThread("时间进度表");
}
}
class WindowThread extends JFrame implements ActionListener{
private JButton start,stop,continu;
private JTextField text;
private JPanel pane1,pane2;
//设置计时器的过程包括创建一个 Timer 对象,
//在该对象上注册一个或多个动作侦听器,以及使用 start 方法启动该计时器
Timer time;
public WindowThread(String string) {
// TODO 自动生成构造函数存根
setTitle(string);
//创建一个 Timer 并将初始延迟和事件间延迟初始化为 delay 毫秒。
time=new Timer(1000,this);//time对象做计时器
Container con=getContentPane();
con.setLayout(new BorderLayout());
pane1=new JPanel(new FlowLayout(FlowLayout.LEFT));
start=new JButton("开始");
start.addActionListener(this);
stop=new JButton("暂停");
stop.addActionListener(this);
continu=new JButton("继续");
continu.addActionListener(this);
pane1.add(start);pane1.add(stop); pane1.add(continu);
pane2=new JPanel(new FlowLayout(FlowLayout.RIGHT));
text=new JTextField(20);
pane2.add(text);
con.add(pane1,BorderLayout.NORTH);
con.add(pane2,BorderLayout.SOUTH);
setVisible(true);
setSize(300,200);
validate();
}
public void actionPerformed(ActionEvent e) {
// TODO 自动生成方法存根
if(e.getSource()==time){
Date date=new Date();
System.out.println(date.toString());
String sr=date.toString().substring(11,19);
text.setText("时间:"+sr);
}
else if(e.getSource()==start){
time.start();
}
else if(e.getSource()==stop){
time.stop();
}
else if(e.getSource()==continu){
time.restart();
}
}
}
----------------------------
7.时间进度表的另一种做法
public class MonitorTimeMachine {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
WindowMonitorListener win=new WindowMonitorListener("这是一个小计时器");
}
}
class WindowMonitorListener extends JFrame implements Runnable ,ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JButton start,stop,continu;
private JTextField text;
private JPanel pane1,pane2;
MyCanvas my;
Thread th,can;
int x=0,y=0;
int hour=0,minute=0,second=0;
String timestr;
int state=0;
class MyCanvas extends Canvas{
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
if(state==0){
g.setColor(Color.CYAN);
g.fillOval(x, y, 30, 30);
}
else if(state==1){
g.setColor(Color.CYAN);
g.fillOval(x, y, 30, 30);
}
}
}
public WindowMonitorListener(String string) {
// TODO Auto-generated constructor stub
setTitle(string);
th=new Thread(this);
can=new Thread(this);
my=new MyCanvas();
my.setBackground(Color.lightGray);
Container con=getContentPane();
con.setLayout(new BorderLayout());
pane1=new JPanel(new FlowLayout(FlowLayout.LEFT));
start=new JButton("开始");
start.addActionListener(this);
stop=new JButton("暂停");
stop.addActionListener(this);
continu=new JButton("继续");
continu.addActionListener(this);
pane1.add(start);pane1.add(stop); pane1.add(continu);
pane2=new JPanel(new FlowLayout(FlowLayout.RIGHT));
text=new JTextField(20);
pane2.add(text);
text.setText("00:00:00");
con.add(pane1,BorderLayout.NORTH);
con.add(my,BorderLayout.CENTER);
con.add(pane2,BorderLayout.SOUTH);
setVisible(true);
setResizable(false);
setSize(600,600);
validate();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==start){
x=0;y=0;
hour=0;
minute=0;
second=0;
text.setText("00:00:00");
if(!can.isAlive() && !th.isAlive()){
can=new Thread(this);
can.start();
th=new Thread(this);
th.start();
}
else {}
}
else if(e.getSource()==stop){
th.stop();
can.stop();
hour=0;
minute=0;
second=0;
text.setText("00:00:00");
}
else if(e.getSource()==continu){
if(!th.isAlive()){
th=new Thread(this);
th.start();
}
else if(!can.isAlive()){
can=new Thread(this);
can.start();
}
}
}
public String format(int time){
if(time<10){
return "0"+time;
}
else{
return time+"";
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
if(Thread.currentThread()==th){
second++;
if(second>=60){
second=0;
minute++;
if(minute>=60){
hour++;
minute=0;
second=0;
if(hour>=24){
hour=0;
minute=0;
second=0;
}
}
}
timestr=format(hour)+":"+format(minute)+":"+format(second);
text.setText(timestr);
}
else if(Thread.currentThread()==can){
System.out.println("小球运动");
while(true){
// if(state==-1 ){
// y=y-5;
// x=y;
// }
// else if(state==1){
// y=y+5;
// x=y;
// }
// else if(state==2){
// x=x+2;
// y=x;
// }
// else if(state==-2){
// x=x-2;
// y=x;
// }
if(y>=WindowMonitorListener.this.getHeight()-120){
y=0;x=y;
//state=-1;
}
else if(x>=WindowMonitorListener.this.getWidth()){
x=0;y=x;
//state=-2;
}
else if(x>=WindowMonitorListener.this.getLocation().getX()){
x=x+5;
y=x;
//state=2;
}
else if(y>=WindowMonitorListener.this.getLocation().getY()){
y=y+5;
x=y;
//state=1;
}
my.repaint();
try{
Thread.sleep(10);
}
catch(InterruptedException e){
}
}
}
}
}
}
-------------------------------------
8.Synchnorized的使用,一个线程调用了它,这个线程运行结束后,其它线程才会开始
public class ThreadTest5 {
public static void main(String[] args) {
/*
* 子线程的使用
new Thread5().start();
new Thread5().start();
new Thread5().start();
new Thread5().start(); */
Thread5 t = new Thread5();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
new Thread(t).start();
}
}
/*子线程的使用
class Thread5 extends Thread{
private static int tickets = 30;
private static Object o = new Object();
public void run(){
while(true){
synchronized(o){
if(this.tickets < 1){
break;
}
else{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName() +" 买了第 "+ this.tickets-- +" 张票");
}
}
}
}
}
*/
class Thread5 implements Runnable{
private int tickets = 30;
private Object o = new Object();
public synchronized void f(){
while(true){
if(this.tickets < 1){
break;
}
else{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +" 买了第 "+ this.tickets-- +" 张票");
}
}
}
public void run(){
this.f();
/*synchronized的不同使用·
* while(true){
synchronized(o){
if(this.tickets < 1){
break;
}
else{
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() +" 买了第 "+ this.tickets-- +" 张票");
}
}
}*/
}
}
-----------------------------------------------------------------
9.Wait 与 synchronized的用法
package com.lzl.thread;
public class QueueTest {
protected Object[] data;
protected int writeIndex,readIndex;
protected int count;
public QueueTest(int size){
data=new Object[size];
}
public static void main(String[] args) {
// TODO Auto-generated method stub
QueueTest queue=new QueueTest(5);
new Writer(queue);
new Reader(queue);
}
public synchronized void write(Integer integer) {
// TODO Auto-generated method stub
while(count>=data.length){
try{
wait();
}
catch(InterruptedException e){} }
data[writeIndex++]=integer;
System.out.println("写出的数是:"+integer);
writeIndex%=data.length;
count++;
//唤醒在此对象监视器上等待的单个线程。
//线程通过调用其中一个 wait 方法,在对象的监视器上等待。
notify();
}
public synchronized void read() {
// TODO Auto-generated method stub
//if(count<=0) return;
while(count<=0){
try{
wait();
}
catch(InterruptedException e){}
}
int value=((Integer) data[readIndex++]).intValue();
System.out.println("读出的数是:"+value);
readIndex%=data.length;
count--;
notify();
}
}
class Writer implements Runnable{
QueueTest queue;
public Writer(QueueTest queue) {
this.queue=queue;
new Thread(this).start();
}
@Override
public void run() {
int i=0;
while(true){
queue.write(new Integer(i));
i++;
try{
Thread.sleep(500);
}
catch(InterruptedException e){}
}
}
}
class Reader implements Runnable{
QueueTest queue;
public Reader(QueueTest queue) {
this.queue=queue;
new Thread(this).start();
}
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
queue.read();
try{
Thread.sleep(500);
}
catch(InterruptedException e){}
}
}
}
Java网络编程Socket
1.多客户端与服务器端通信(一个客户端可以和用户多次交互)
服务器端代码
public class Server2 {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("服务器在10000端口处等待............");
int client_id = 1;
try {
ServerSocket ss = new ServerSocket(2300);
while(true){
Socket socket = ss.accept();
new ServerThread(client_id,socket).start();
client_id++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread extends Thread{
private int client_id;
private Socket socket;
public ServerThread(int client_id, Socket socket) {
this.client_id = client_id;
this.socket = socket;
}
@Override
public void run() {
BufferedReader br=null;
PrintWriter pw=null;
try {
while(true){
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(System.out));
String line = null;
while((line = br.readLine()) != null){
pw.println("第 " +this.client_id+ " 个客户端说: " +line);
pw.flush();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端代码
public class Client2 {
/**
* @param args
*/
public static void main(String[] args) {
/* if(args.length < 2){
System.out.println("usage: java Client1 hostname port");
return;
}
String hostname = args[0];
int port = Integer.parseInt(args[1]);*/
BufferedReader br=null;
PrintWriter pw=null;
try {
Socket s = new Socket(InetAddress.getByName("localhost"),2300);
br = new BufferedReader(new InputStreamReader(System.in));
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
String line = null;
while((line = br.readLine()) != null){
pw.println(line);
pw.flush();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
br.close();
pw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
--------------------------------------------------------------------------------------------
2.服务器端与客户端在交互时,用的方法要一致,否则会出现异常
服务器端
public class MulWriteAndMulReadServer {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server=null;
Socket socket=null;
int client_id=1;
System.out.println("客户端等待服务器端请求..");
try {
server=new ServerSocket(5500);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while(true){
socket=server.accept();
new ServerThread001(client_id,socket).start();
client_id++;
}
}
catch(Exception e){}
}
}
class ServerThread001 extends Thread{
BufferedReader br=null;
PrintWriter pw=null,pw1=null;
Socket socket=null;
int client_id;
public ServerThread001(int client_id,Socket socket2) {
// TODO Auto-generated constructor stub
this.client_id=client_id;
this.socket=socket2;
}
@Override
public void run() {
try {
br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
pw1=new PrintWriter(new OutputStreamWriter(System.out));
String ss=null;
while(true){
ss=br.readLine();
pw.println("第"+client_id+"客户"+"我是服务器");
pw.println("第"+client_id+"客户"+"你说的信息变化后是:"+ss);
pw.flush();
pw1.println("第"+client_id+"客户"+"服务器收到的信息是"+ss);
pw1.flush();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
br.close();
pw.close();
pw1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
客户端
public class MulWriteAndMulReadClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader br=null;
PrintWriter pw=null;
BufferedReader br1=null;
Socket socket=null;
String line=null;
try {
socket=new Socket("localhost",5500);
System.out.println("客户端发送请求..,,");
pw=new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
br1=new BufferedReader(new InputStreamReader(socket.getInputStream()));
br=new BufferedReader(new InputStreamReader(System.in));
String tt=null;
boolean flag=true;
while((line=br.readLine())!=null){
System.out.println("客户端发送:"+line);
pw.println(line);
pw.flush();
//和服务器端相符合
System.out.println("从服务器收到的信息是:"+br1.readLine());
System.out.println("从服务器收到的信息是:"+br1.readLine());
}
}
catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
finally{
try {
br.close();
pw.close();
br1.close();
socket.close();
} catch (IOException e3) {
// TODO Auto-generated catch block
e3.printStackTrace();
}
}
}
}
-------------------------------------------------
3.带有图形界面的客户端与服务器端交互(计算三角形面积)
服务器端:
public class TriangleofEdegeAreaServer {
public static void main(String[] args) {
// TODO Auto-generated method stub
ServerSocket server=null;
Server_thread1 thread;
Socket socket=null;
while(true){
try {
server=new ServerSocket(4322);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("正在监听");
}
System.out.println("等待客户呼叫");
try {
socket=server.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("正在等待客户呼叫");
}
System.out.println("客户的地址是:"+socket.getInetAddress());
if(socket!=null){
new Server_thread1(socket).start(); //为每一个客户启动一个专门的线程
}
}
}
}
class Server_thread1 extends Thread{
Socket socket;
DataInputStream in=null;
DataOutputStream out=null;
String s=null;
boolean question=false;
public Server_thread1(Socket socket) {
this.socket=socket;
try {
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
while(true){
double a[]=new double[3];
int i=0;
try {
s=in.readUTF();
StringTokenizer token=new StringTokenizer(s," ,");
while(token.hasMoreTokens()){
String fen=token.nextToken();
a[i]=Double.parseDouble(fen);
i++;
}
question=true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
question=false;
}//堵塞状态,除非读到信息
if(question==true){
double p=(a[0]+a[1]+a[2])/2;
try {
out.writeUTF(""+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("客户离开....");
}
}
}
}
}
--------------------------------------------------------------------
客户端
public class TriangleofEdegeAreaClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
new TriangleArea();
}
}
class TriangleArea extends JFrame implements ActionListener,Runnable{
JButton connection,send;
JTextField inputText,showText;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
public TriangleArea(){
socket=new Socket();
Container con=getContentPane();
con.setLayout(new FlowLayout());
//使用 BoxLayout 对象作为其布局管理器的一个轻量级容器。
//Box 提供几个对使用 BoxLayout 的容器(甚至非 Box 容器)有用的类方法。
//javax.swing.Box Box.createVerticalBox()创建一个从上到下显示其组件的 Box。
Box box=Box.createVerticalBox();
connection=new JButton("连接服务器");
send=new JButton("发送");
send.setEnabled(false);
inputText=new JTextField(12);
showText=new JTextField(12);
box.add(connection);
box.add(new JLabel("输入三角形三边的长度,用逗号或空格分开"));
box.add(inputText);
box.add(send);
box.add(new JLabel("收到的结果是:"));
box.add(showText);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
con.add(box);
setBounds(100,200,400,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
@Override
public void run() {
// TODO Auto-generated method stub
String ss=null;
while(true){
try {
ss=in.readUTF();
showText.setText(ss);
} catch (IOException e) {
// TODO Auto-generated catch block
showText.setText("与服务器断开");
break;
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==connection){
if(socket.isConnected()){}
else{
try {
//InetAddress含有一个internet主机地址的域名和ip地址
//InetAddress.getByName(s)将一个域名或Ip地址传给该方法的参数s,获得一个
//InetAddress对象,该对象含有主机地址的域名和ip地址 如 :域名/IP
InetAddress address=InetAddress.getByName("localhost");
InetSocketAddress socketAddress=new InetSocketAddress(address,4322);
socket.connect(socketAddress);
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
else if(e.getSource()==send){
String s=inputText.getText();
if(s!=null){
try {
out.writeUTF(s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
--------------------------------------------------------------
4.客户端服务器端与服务器交互(可以多客户端多次交互)
服务器端代码
public class ServerJDBCTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new ServerDeal();
}
}
class ServerDeal{
ServerSocket server;
Socket socket;
public ServerDeal(){
try {
server=new ServerSocket(8809);
boolean flag=true;
while(flag){
try {
socket=server.accept();
System.out.println("客户端连上服务");
new ServerThread(socket).start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread extends Thread{
Socket socket;
Connection con;
Statement st;
ResultSet rs;
BufferedReader in;
BufferedWriter out;
public ServerThread(Socket socket) {
this.socket=socket;
try {
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("1111111111");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
String s=null;
char[] tr=new char[20];
boolean flag=true;
try {
while(flag){
in.read(tr);
s=new String(tr).trim();
System.out.println(s);
int num=Integer.parseInt(s);
String sql="select * from student where id="+num;
try {
con=new DBConnection1().getConn();
con.setAutoCommit(false);
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()){
String ss="学号:"+rs.getInt(1)+" 姓名:"+rs.getString(2)+" 课程:"+rs.getString(3)+" 得分:"+rs.getInt(4);
System.out.println("1:"+rs.getInt(1)+" 2:"+rs.getString(2)+" 3:"+rs.getString(3)+" 4:"+rs.getInt(4));
out.write(ss);
out.flush();
}
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
con.rollback();
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs.close();
st.close();
con.close();
out.close();
in.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class DBConnection1 {
Connection con=null;
public Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con=DriverManager.getConnection("jdbc:mysql://localhost/stu","root","1234");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
客户端代码
public class TriangleofEdegeAreaClient {
public static void main(String[] args) {
// TODO Auto-generated method stub
new TriangleArea();
}
}
class TriangleArea extends JFrame implements ActionListener,Runnable{
JButton connection,send;
JTextField inputText,showText;
Socket socket=null;
DataInputStream in=null;
DataOutputStream out=null;
Thread thread;
public TriangleArea(){
socket=new Socket();
Container con=getContentPane();
con.setLayout(new FlowLayout());
//使用 BoxLayout 对象作为其布局管理器的一个轻量级容器。
//Box 提供几个对使用 BoxLayout 的容器(甚至非 Box 容器)有用的类方法。
//javax.swing.Box Box.createVerticalBox()创建一个从上到下显示其组件的 Box。
Box box=Box.createVerticalBox();
connection=new JButton("连接服务器");
send=new JButton("发送");
send.setEnabled(false);
inputText=new JTextField(12);
showText=new JTextField(12);
box.add(connection);
box.add(new JLabel("输入三角形三边的长度,用逗号或空格分开"));
box.add(inputText);
box.add(send);
box.add(new JLabel("收到的结果是:"));
box.add(showText);
connection.addActionListener(this);
send.addActionListener(this);
thread=new Thread(this);
con.add(box);
setBounds(100,200,400,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
@Override
public void run() {
// TODO Auto-generated method stub
String ss=null;
while(true){
try {
ss=in.readUTF();
showText.setText(ss);
} catch (IOException e) {
// TODO Auto-generated catch block
showText.setText("与服务器断开");
break;
}
}
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==connection){
if(socket.isConnected()){}
else{
try {
//InetAddress含有一个internet主机地址的域名和ip地址
//InetAddress.getByName(s)将一个域名或Ip地址传给该方法的参数s,获得一个
//InetAddress对象,该对象含有主机地址的域名和ip地址 如 :域名/IP
InetAddress address=InetAddress.getByName("localhost");
InetSocketAddress socketAddress=new InetSocketAddress(address,4322);
socket.connect(socketAddress);
in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
send.setEnabled(true);
thread.start();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException ee) {
// TODO Auto-generated catch block
ee.printStackTrace();
}
}
}
else if(e.getSource()==send){
String s=inputText.getText();
if(s!=null){
try {
out.writeUTF(s);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
5.服务器与客户端交互包括数据库
public class ServerJDBCTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
new ServerDeal();
}
}
class ServerDeal{
ServerSocket server;
Socket socket;
public ServerDeal(){
try {
server=new ServerSocket(8809);
boolean flag=true;
while(flag){
try {
socket=server.accept();
System.out.println("客户端连上服务");
new ServerThread(socket).start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class ServerThread extends Thread{
Socket socket;
Connection con;
Statement st;
ResultSet rs;
BufferedReader in;
BufferedWriter out;
public ServerThread(Socket socket) {
this.socket=socket;
try {
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
System.out.println("1111111111");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
String s=null;
char[] tr=new char[20];
boolean flag=true;
try {
while(flag){
in.read(tr);
s=new String(tr).trim();
System.out.println(s);
int num=Integer.parseInt(s);
String sql="select * from student where id="+num;
try {
con=new DBConnection1().getConn();
con.setAutoCommit(false);
st=con.createStatement();
rs=st.executeQuery(sql);
if(rs.next()){
String ss="学号:"+rs.getInt(1)+" 姓名:"+rs.getString(2)+" 课程:"+rs.getString(3)+" 得分:"+rs.getInt(4);
System.out.println("1:"+rs.getInt(1)+" 2:"+rs.getString(2)+" 3:"+rs.getString(3)+" 4:"+rs.getInt(4));
out.write(ss);
out.flush();
}
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
con.rollback();
}
}
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
rs.close();
st.close();
con.close();
out.close();
in.close();
socket.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
class DBConnection1 {
Connection con=null;
public Connection getConn() {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
con=DriverManager.getConnection("jdbc:mysql://localhost/stu","root","1234");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
客户端:
public class ClientJDBCTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new WindowClientJDBC("数据库与网络连接的方法");
}
}
class WindowClientJDBC extends JFrame implements ActionListener{
private JButton connection,send;
private JLabel label;
private JTextField text;
private JTextArea area;
Socket socket;
BufferedReader in=null;
BufferedWriter out=null;
public WindowClientJDBC(String string) {
setTitle(string);
Container con=getContentPane();
connection=new JButton("连接服务器");
label=new JLabel("输入学号");
send=new JButton("发送");
JPanel north=new JPanel();
north.add(connection);
north.add(label);
text=new JTextField(20);
text.addActionListener(this);
north.add(text);
north.add(send);
connection.addActionListener(this);
send.addActionListener(this);
area=new JTextArea(20,10);
con.add(north,BorderLayout.NORTH);
con.add(area,BorderLayout.CENTER);
setSize(500,400);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
validate();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource()==connection){
try {
socket=new Socket("localhost",8809);
new ClientThread(socket).start();
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
else if(e.getSource()==send ||e.getSource()==text){
String strtext=text.getText();
System.out.println("文本信息:"+strtext);
try {
out.write(strtext);
out.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
class ClientThread extends Thread{
Socket socket;
public ClientThread(Socket socket) {
this.socket=socket;
try{
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
out=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
}
catch(Exception e){
e.printStackTrace();
}
}
@Override
public void run() {
char c[]=new char[100];
boolean flag=true;
try {
while(flag){
in.read(c);
String sss=new String(c).trim();
area.append(sss+"\n");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in.close();
out.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
---------------------------------------------------------------------------------
Java数据库端(java.sql)
1.数据库信息
public class DatabaseMetaDataAccessTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:student", "lzl", "1234");
// 取得DatabaseMetaData 获取数据库信息
DatabaseMetaData dmd = con.getMetaData();
System.out.println("数据库名:\t" + dmd.getDatabaseProductName());
System.out.println("数据库版本:\t" + dmd.getDatabaseProductVersion());
System.out.println("驱动名:\t" + dmd.getDriverName());
System.out.println("驱动版本:\t" + dmd.getDriverVersion());
System.out.println("==============================================");
// 查询Access数据库的user表
//st = con.createStatement();
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from student");
//rs=st.executeQuery("update user set name='阿里巴巴' where name=‘‘刘德华");
// 取得ResultSetMetaData获取表结构
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
System.out.println("==========before============");
// 取得结果集
while (rs.next()) {
System.out.print(rs.getInt(1) + "\t");
System.out.print(rs.getString(2) + "\t");
System.out.print(rs.getString(3));
System.out.println();
}
/*
rs.absolute(1);
rs.updateString("name", "阿里巴巴");
rs.updateString("password", "2008");
rs.updateRow();
*/
rs.afterLast();
System.out.println("========after=============");
while (rs.previous()) {
System.out.print(rs.getInt(1) + "\t");
System.out.print(rs.getString(2) + "\t");
System.out.print(rs.getString(3));
System.out.println();
}
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
-------------------------
2.mysql数据源连接
java与数据库的两种连接(Drimanager 与 数据源连接)
public class MySQLDataSourceTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MysqlDataSource source=new MysqlDataSource();
source.setServerName("localhost");
source.setDatabaseName("stu");
source.setPort(3306);
source.setUser("root");
source.setPassword("1234");
try {
Connection con=source.getConnection();
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student");
while(rs.next()){
System.out.println(rs.getInt(1)+"...."+rs.getString(2)+"...."+rs.getString(3)+"..."+rs.getInt(4));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
------------------------------------------------------------------------------------------------
3.数据库中的JNDI用法
public class MysqlJNDI {
public static final String DSNAME="jdbc/jndi";
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建jndi属性
Context ctx=null;
Properties jndienv=new Properties();
jndienv.setProperty(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.fscontext.RefFSContextFactory");
//d盘必须有temp这个文件,之后会生成一个绑定文件
jndienv.setProperty(Context.PROVIDER_URL, "file:\\d:\\temp");
try {
//把属性类绑定到Context里
ctx=new InitialContext(jndienv);
bindDS(ctx);
System.out.println("绑定成功");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void bindDS(Context ctx) {
// TODO Auto-generated method stub
MysqlDataSource sou=new MysqlDataSource();
sou.setUrl("jdbc:mysql://localhost:3306/stu");
sou.setUser("root");
sou.setPassword("1234");
try {
//把数据源绑定到一个名称下
ctx.rebind(DSNAME, sou);
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
-----------------------------
//当前类与前一个设置的类MysqlJNDI有关联,有MysqlJNDI才能有当前类
public class MysqlLookUpTest {
public static String DSNAME="jdbc/jndi";
public static void main(String[] args) {
Context ctx=null;
Properties pt=new Properties();
pt.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
pt.setProperty(Context.PROVIDER_URL, "file:\\D:\\temp");
try {
ctx=new InitialContext(pt);
LookUpDS(ctx);
System.out.println("连接成功");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void LookUpDS(Context ctx) {
// TODO Auto-generated method stub
Connection con=null;
Statement st=null;
ResultSet rs=null;
//通过名称获得数据源
try {
DataSource source=(DataSource) ctx.lookup(DSNAME);
con=source.getConnection();
st=con.createStatement();
rs=st.executeQuery("select * from student");
while(rs.next()){
System.out.println("---"+rs.getInt(1)+"---"+rs.getString(2)+"---"+rs.getString(3)+"---"+rs.getInt(4));
}
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null)
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
------------------------------
4.Java数据库大数据
public class BlobandClobData {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BlobandClobData bb=new BlobandClobData();
bb.insertCBlob();
bb.findBClob();
}
private void findBClob() {
Connection con=(Connection) new DBConnection().getCon();
BufferedOutputStream out=null;
BufferedWriter bw=null;
PreparedStatement ps=null;
ResultSet rs=null;
try{
con.setAutoCommit(false);
out=new BufferedOutputStream(new FileOutputStream(new File("1.jpg")));
bw=new BufferedWriter(new FileWriter(new File("2.txt")));
ps=con.prepareStatement("select * from photostu");
rs=ps.executeQuery();
while(rs.next()){
int num=rs.getInt(1);
String name=rs.getString(2);
Blob ima=rs.getBlob(3);
InputStream ins=ima.getBinaryStream();
byte[] b=new byte[ins.available()];
int len=ins.read(b);
out.write(b, 0, len);
Clob tex=rs.getClob(4);
Reader rr=tex.getCharacterStream();
char []aa=new char[(int)tex.length()];
rr.read(aa);
bw.write(aa, 0,(int) aa.length);
}
con.commit();
}
catch(Exception e){
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
out.close();
bw.close();
ps.close();
rs.close();
con.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void insertCBlob() {
// TODO Auto-generated method stub
BufferedInputStream in=null;
BufferedReader br=null;
File image=new File("adu.jpg");
File text=new File("s1.txt");
Connection con=(Connection) new DBConnection().getCon();
PreparedStatement ps=null;
try {
con.setAutoCommit(false);
in=new BufferedInputStream(new FileInputStream(image));
br=new BufferedReader(new FileReader(text));
ps=con.prepareStatement("insert into photostu(id,name,photo,descr) values(null,?,?,?)");
ps.setString(1,"liu");
ps.setBinaryStream(2, in, (int)image.length());
ps.setCharacterStream(3, br, (int)text.length());
ps.executeUpdate();
con.commit();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
try {
ps.close();
con.close();
in.close();
br.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
--------------------------------------------------
5.Java的批量处理
public class JDBCBatchTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
JDBCBatchTest batch=new JDBCBatchTest();
//statement的批量处理
batch.batchStatement();
//prepareStatement的批量处理
batch.batchPrepareStatement();
}
private void batchPrepareStatement() {
Connection con=new DBConnection().getCon();
PreparedStatement ps=null;
try {
con.setAutoCommit(false);
ps=con.prepareStatement("insert into student(id,name,course,score) values(null,?,?,?)");
ps.setString(1, "111");ps.setString(2, "111");ps.setInt(3, 65);ps.addBatch();
ps.setString(1, "222");ps.setString(2, "222");ps.setInt(3, 65);ps.addBatch();
ps.setString(1, "333");ps.setString(2, "333");ps.setInt(3, 65);ps.addBatch();
ps.setString(1, "444");ps.setString(2, "444");ps.setInt(3, 65);ps.addBatch();
ps.setString(1, "555");ps.setString(2, "555");ps.setInt(3, 65);ps.addBatch();
ps.executeBatch();
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
private void batchStatement() {
Connection con=new DBConnection().getCon();
Statement st=null;
try {
con.setAutoCommit(false);
st=con.createStatement();
//批量添加
st.addBatch("insert into student(id,name,course,score) values(null,'刘星','语文',86)");
st.addBatch("insert into student(id,name,course,score) values(null,'张玲','数学',90)");
int[] rs=st.executeBatch();
for(int j=0;j<rs.length;j++){
System.out.println("第"+j+"个声明影响"+rs[j]+"列");
}
con.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
finally{
try {
st.close();
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
-----------------------------------------------------------------------------
6.Java的滚动处理
public class JDBCRollTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection con=new DBConnection().getCon();
//ResultSet.TYPE_FORWARD_ONLY该常量指示光标只能向前移动(向下一个)的 ResultSet 对象的类型
//ResultSet.TYPE_SCROLL_INSENSITIVE该常量指示可滚动但通常不受 ResultSet 底层数据更改影响的 ResultSet 对象的类型。
//即当数据库变化时,当前结果积不变
//ResultSet.TYPE_SCROLL_SENSITIVE该常量指示可滚动并且通常受 ResultSet 底层数据更改影响的 ResultSet 对象的类型。
//即当数据库变化时,当前结果同步改变
/**
* ResultSet.CONCUR_READ_ONLY该常量指示不可以更新的 ResultSet 对象的并发模式.即不能用结果集更新数据库中的表
* ResultSet.CONCUR_UPDATABLE该常量指示可以更新的 ResultSet 对象的并发模式。能用结果集更新数据库中的表
*/
try {
//一般用第一条就足够了
//1.Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs=st.executeQuery("select * from student");
//输出所有列
System.out.println("学号"+"\t"+"姓名"+"\t"+"课程"+"\t"+"学分");
while(rs.next()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
}
//定位到最后一列
rs.last();
System.out.println("最后一列:");
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
//定位到第二列
rs.absolute(2);
System.out.println("第二列:");
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
//定位到最后
rs.afterLast();
System.out.println("倒序输出:");
while(rs.previous()){
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
}
/**
* 对于用updaterow,Statememt里的同步应该是ResultSet.CONCUR_UPDATABLE,
* 如果是ResultSet.CONCUR_READ_ONLY则会出现错误
*/
//修改第四列
rs.absolute(4);
rs.updateString(2, "aaaa");
rs.updateString(3, "bbbb");
rs.updateRow();
System.out.println("修改后第四列:");
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
//插入行 将光标移动到插入行。
rs.moveToInsertRow();
rs.updateInt(1,1013);
rs.updateString(2, "ccc");
rs.updateString(3,"dddd");
rs.updateInt(4, 80);
//将插入行的内容插入到此 ResultSet 对象和数据库中。
rs.insertRow();
//将光标移动到记住的光标位置,通常为当前行。
rs.moveToCurrentRow();
rs.last();
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
//删除当前行
rs.absolute(9);
rs.deleteRow();
//定位到第一个的上一个
rs.beforeFirst();
rs.next();
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3)+"\t"+rs.getInt(4));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
---------------------------------
7.Java以excel为数据库的处理
/**
* 注意:
必须使用[](方括号),否将报:
FROM 子句语法错误
必须跟$(美元符号),否则报:
Microsoft Jet 数据库引擎找不到对象'Sheet2'。请确定对象是否存在,并正确地写出它的名称和路径。
如果工作表名称不对,或者不存在,将报:
'Sheet2$' 不是一个有效名称。请确认它不包含无效的字符或标点,且名称不太长。
在 如何在 Visual Basic 或 VBA 中使用 ADO 来处理 Excel 数据 中提到可以使用
~ 和 '(波浪线和单引号)代替[],使用ADO。NET测试没有成功,报:
FROM 子句语法错误
当引用工作表明名([Sheet1$])时,数据提供程序认为数据表从指定工作表上最左上方的非空单元格开始。比如,工作表从第 3 行,C 列开始,第3行,C列之前以及第1、2行全为空,则只会显示从第3行,C列开始的数据;以最后表最大范围内的非空单元结束;
* @author Ascent01
*
*/
public class ResultSetMetaDataExcelTest {
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:teststu","","");
//取得DatabaseMetaData 获取数据库信息
DatabaseMetaData dmd = con.getMetaData();
System.out.println("数据库名:\t"+dmd.getDatabaseProductName());
System.out.println("数据库版本:\t"+dmd.getDatabaseProductVersion());
System.out.println("驱动名:\t"+dmd.getDriverName());
System.out.println("驱动版本:\t"+dmd.getDriverVersion());
System.out.println("==============================================");
//查询某个excel工作空间-->表
st = con.createStatement();
rs = st.executeQuery("select * from [sss$]"); //user是操作的工作空间,格式:[sheetx$]
//取得ResultSetMetaData获取表结构-->连接的工作空间
//工作空间中默认第一行是列名,后面的行是数据
ResultSetMetaData rsmd = rs.getMetaData();
for(int i=1;i<=rsmd.getColumnCount();i++){
System.out.print(rsmd.getColumnName(i)+"\t");
}
System.out.println();
System.out.println("=======================");
//取得结果集
while(rs.next()){
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getString(3)+"\t");
System.out.print(rs.getString(4));
System.out.println();
}
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}