1. 测试java.swing包提供的轻量级组件的例子(以java Application方式运行)

TestSwing.java文件

源代码如下:

package SampleGUI;
 import java.awt.*;
 import java.util.*;
 import javax.swing.*;
 import javax.swing.tree.*;
 import javax.swing.table.*;
 import javax.swing.ButtonGroup;public class TestSwing extends JFrame{
  JLabel lblName = new JLabel("姓名: ");
  JLabel lblNumber = new JLabel("身份证号");
  JLabel lblSex = new JLabel("性别 ");
  JLabel lblJob = new JLabel("职业");
  JLabel lblText = new JLabel("个性化宣言"); JTextField tfName = new JTextField(23);
  JTextField tfNumber = new JTextField(20);
  
  JTextArea taText = new JTextArea(5, 20);
  JRadioButton jMale = new JRadioButton("男");
  JRadioButton jFemale = new JRadioButton("女");
  
  ButtonGroup group = new ButtonGroup();
  JComboBox combJob = new JComboBox();
  JButton btnOK = new JButton("确定");
  JButton btnDisplay = new JButton("取消");
  JTable tblInf = new JTable();
  
  DefaultTableModel dtm = new DefaultTableModel();
  
  JTree tree = new JTree();
  JPanel p1 = new JPanel();
  JPanel p2 = new JPanel();
  JPanel p3 = new JPanel();
  JPanel p4 = new JPanel();
  JPanel p5 = new JPanel();
  JPanel p6 = new JPanel();
  JPanel p7 = new JPanel(new BorderLayout());
  JPanel p8 = new JPanel();
  JPanel p9 = new JPanel(new BorderLayout());
  
  public TestSwing(){
   group.add(jMale);
   group.add(jFemale);
   
   combJob.addItem("计算机");
   combJob.addItem("医生");
   combJob.addItem("教师");
   combJob.addItem("军队");
   
      p1.add(lblName);
      p1.add(tfName);
      
      p2.add(lblNumber);
      p2.add(tfNumber);
      
      p3.add(lblSex);
      p3.add(jMale);
      p3.add(jFemale);
      
      p4.add(lblJob);
      p4.add(combJob);
      
      p5.add(p3);
      p5.add(p4);
      
   p6.setLayout(new BorderLayout());
   p6.add(p1, BorderLayout.NORTH);
   p6.add(p2, BorderLayout.CENTER);
   p6.add(p5, BorderLayout.SOUTH);
   
   p7.add(lblText, BorderLayout.NORTH);
   p7.add(taText, BorderLayout.CENTER);
   
   p8.setLayout(new FlowLayout(FlowLayout.CENTER,30, 10));
   p8.add(btnOK);
   p8.add(btnDisplay);
   
   p9.add(p6, BorderLayout.NORTH);
   p9.add(p7, BorderLayout.CENTER);
   p9.add(p8, BorderLayout.SOUTH);
   
   add(p9);
   
   setTable();
   
   setTree();
   
   getContentPane().add(p9, BorderLayout.NORTH);
   JScrollPane s = new JScrollPane(tblInf);
   getContentPane().add(s, BorderLayout.CENTER);
   getContentPane().add(tree, BorderLayout.SOUTH);
  
  }
  
  public void setTable(){
   Vector vCdata = new Vector();
   vCdata.add("姓名");
   vCdata.add("身份证号");
   vCdata.add("性别");
   
   tblInf.setModel(dtm);
   for (int i = 0; i < vCdata.size(); i++) {
    dtm.addColumn((String)vCdata.elementAt(i));
    Vector vRdata = new Vector();
    vRdata.add("王飞");
    vRdata.add("430423199810249658");
    vRdata.add("男");
    
    dtm.addRow(vRdata);
    
   }
   
  }
  
  public void setTree(){
   DefaultMutableTreeNode root;
   DefaultMutableTreeNode NodeName, NodeNumber, NodeSex;
   DefaultMutableTreeNode leafName, leafNumber, leafSex;
   
   root = new DefaultMutableTreeNode("个人信息");
   NodeName = new DefaultMutableTreeNode("姓名");
   leafName = new DefaultMutableTreeNode("王飞");
   NodeNumber = new DefaultMutableTreeNode("身份证号");
   leafNumber = new DefaultMutableTreeNode("430423199810249658");
   NodeSex = new DefaultMutableTreeNode("性别");
   leafSex = new DefaultMutableTreeNode("男");
   
   root.add(NodeName);
   root.add(NodeNumber);
   root.add(NodeSex);
   
   NodeName.add(leafName);
   NodeNumber.add(leafNumber);
   NodeSex.add(leafSex);
   
   tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
   tree.setShowsRootHandles(true);
   tree.setEditable(false);
   tree.setModel(new DefaultTreeModel(root));
    
  }
  
  public static void main(String []args){
   TestSwing st = new TestSwing();
   st.setSize(400, 450);
   st.show();
  }
   
 }

2. 界面布局的简单例子 (以java Applet方式运行)

UserPanel.java文件

源代码如下:

package SampleGUI;
 import java.applet.*;
 import java.awt.*;
 import java.applet.Applet;public class UserPanel extends Applet{
  Label lblName, lblNumber, lblSex, lblJob, lblText;
  TextField tfName, tfNumber;
  Checkbox chMale, chFemale;
  CheckboxGroup c;
  TextArea taText;
  Choice chJob;
  Button btnOK, btnCancel;
  Panel p1, p2, p3, p4, p5, p6, p7, p8, p9;
  
  public void init(){
   lblName = new Label("姓名:");
   lblNumber = new Label("身份证号: ");
   lblSex = new Label("性别: ");
   lblJob = new Label("职业: ");
   lblText = new Label("修改化宣言: ");
   
   tfName = new TextField(23);
   tfNumber = new TextField(20);
   
   taText = new TextArea(10, 20);
   c = new CheckboxGroup();
   chMale = new Checkbox("男", c, true);
   chFemale = new Checkbox("女", c, false);
   chJob = new Choice();
   chJob.add("计算机");
   chJob.add("医生");
   chJob.add("教师");
   chJob.add("军队");  btnOK = new Button("确定 ");
   btnCancel = new Button("取消");
   
   p1 = new Panel();
   p2 = new Panel();
   p3 = new Panel();
   p4 = new Panel();
   p5 = new Panel();
   p6 = new Panel();
   p7 = new Panel(new BorderLayout());
   p8 = new Panel();
   p9 = new Panel(new BorderLayout());
   
   p1.add(lblName);
   p1.add(tfName);
   p2.add(lblNumber);
   p2.add(tfNumber);
   
   p3.add(lblSex);
   p3.add(chMale);
   p3.add(chFemale);
   
   p4.add(lblJob);
   p4.add(chJob);
   
   p5.add(p3);
   p5.add(p4);
   
   p6.setLayout(new BorderLayout());
   p6.add(p1, BorderLayout.NORTH);
   p6.add(p2, BorderLayout.CENTER);
   p6.add(p5, BorderLayout.SOUTH);
   
   p7.add(lblText, BorderLayout.NORTH);
   p7.add(taText, BorderLayout.CENTER);
   
   p8.setLayout(new FlowLayout(FlowLayout.CENTER,30, 10));
   p8.add(btnOK);
   p8.add(btnCancel); 
   
   p9.add(p6, BorderLayout.NORTH);
   p9.add(p7, BorderLayout.CENTER);
   p9.add(p8, BorderLayout.SOUTH);
   
   add(p9);
  }
  
  public void start(){
   repaint();
  }
  
 }

 

3.用户图形界面例子

SampleGUI.java文件

package SampleGUI;
 import java.awt.*;
 import java.applet.*;public class SampleGUI extends Applet{
  Image samImage;
  public void init(){
   samImage = getImage(getDocumentBase(), "Hydrangeas.jpg");
  }
  
  public void paint(Graphics g){
   //g.clipRect(50, 50, 180, 180);
   g.drawLine(0, 0, 20, 30);
   g.drawString("图形显示", 100, 30);
   Color c = new Color(255,200,0);
   g.setColor(c);
   Font f = new Font("TimesRoman",Font.BOLD+Font.ITALIC, 24);
   g.setFont(f);
   g.drawString("图形显示", 180 , 30);
   g.drawLine(20, 20, 100, 50);
   g.drawLine(20, 20, 50, 100);
   
   g.drawRect(40, 40, 40, 40);
   g.fillRect(60, 60, 40, 40);
   g.setColor(Color.red);
   
   
      g.draw3DRect(80, 80, 40, 40, true);
      g.draw3DRect(100, 100, 40, 40, false);
      g.fill3DRect(120, 120, 40, 40, true);
      
      g.drawOval(150, 150, 30, 40);
      g.fillOval(170, 170, 20, 20);
      g.setColor(Color.blue);
      
      
      g.drawRoundRect(180, 180, 40, 40, 20, 20);
      g.fillRoundRect(200, 200, 40, 40, 20, 20);
      
      
      int xC[] = {242,260,254,297,242};
      int yC[] = {240,243,290,300,270};
      g.drawPolygon(xC, yC, 5);
      
      
      g.drawImage(samImage, 250,50,this);
      
  }
 }

 

5.测试选择事件例子

UserItemEvent.java
package SampleGUI;
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;public class UserItemEvent extends Applet implements ItemListener{
  Checkbox cDisp;
  Button btnDisp;
  Choice cFont;
  
  public void init(){
   cDisp = new Checkbox("红色");
   btnDisp = new Button("颜色显示");
   cFont = new Choice();
   
   cFont.add("10");
   cFont.add("12");
   cFont.add("14");
   
   cDisp.addItemListener(this);
   cFont.addItemListener(this);
   
   add(cDisp);
   add(cFont);
   add(btnDisp);
   
  }
  
  public void itemStateChanged(ItemEvent e){
   Checkbox temp;
   Choice temp2;
   Font oldF;
   
   if (e.getItemSelectable()instanceof Checkbox) {
    temp = (Checkbox)(e.getItemSelectable());
    if (temp.getState()) {
     btnDisp.setBackground(Color.red);
    }else{
     btnDisp.setBackground(Color.blue);
    }
   }
   
   if (e.getItemSelectable()instanceof Choice) {
    oldF = btnDisp.getFont();
    temp2 = (Choice)(e.getItemSelectable());
    String s = temp2.getSelectedItem();
    btnDisp.setFont(new Font(oldF.getName(), oldF.getStyle(), Integer.parseInt(s)));
    
   }
  }
 }

 

6.测试文本事件例子

UserTextEvent.java

package SampleGUI;
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;public class UserTextEvent extends Applet implements 
 ActionListener, TextListener{
  TextField tOld;
  TextArea tNew;
  Panel p;
  public void init(){
   tOld = new TextField(25);
   tNew = new TextArea(8, 25);
   
   tOld.addActionListener(this);
   tOld.addTextListener(this);
   
   p = new Panel(new BorderLayout());
   p.add(tOld, BorderLayout.NORTH);
   p.add(tNew, BorderLayout.SOUTH);
   
   add(p);
   
   
  }
  
  public void textValueChanged(TextEvent e){
   if (e.getSource() == tOld) {
    tNew.setText(tOld.getText()); 
   }
  }
  
  public void actionPerformed(ActionEvent e){
   if (e.getSource() == tOld) {
    tNew.setText("");
   }
  }
 }

7.测试动作事件例子

UserButton.java

package SampleGUI;
import java.applet.*;
 import java.awt.*;
 import java.applet.Applet;
 import java.awt.event.*;public class UserButton extends Applet implements ActionListener{
  String str1 = new String();
  String strContent = new String();
  
  
  Button b1;
  Button b2;
  
  boolean Is1 = false;
  boolean Is2 = false;
  Color c;
  
  
  public void init(){
   
   b1 = new Button();
   b2 = new Button("按钮对象2"); 
   this.add(b1);
   this.add(b2);
   
   b1.addActionListener(this);
   b2.addActionListener(this);
  }
  
  public void start(){
   b1.setLabel("按钮对象1");
   
   str1 = b2.getLabel();
   
   repaint();
   
  }
  
  public void paint(Graphics g){
   g.drawString(str1, 120, 130);
   g.drawString(strContent, 120, 200);
  }
  
  public void actionPerformed(ActionEvent e){
   String arg = e.getActionCommand();
   
   if ("按钮对象1" == arg) {
    c = Color.red;
    strContent = "按钮对象1";
    
   }else if ("按钮对象2" == arg) {
    c = Color.blue;
    strContent = "按钮对象2";
   }
   repaint();
  }
                     
 }

8.测试调整事件例子

UserAdjustmentEvent.java

package SampleGUI;
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;public class UserAdjustmentEvent extends Applet implements AdjustmentListener{
  
  Scrollbar s;
  TextArea txtValue;
     Panel p;
     public void init(){
      s = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 10, 36);
      s.addAdjustmentListener(this);
      
      txtValue = new TextArea(5,25);
         p = new Panel(new BorderLayout());
         p.add(s, BorderLayout.NORTH);
         p.add((txtValue), BorderLayout.SOUTH);
         add(p);
     }
     
     public void start(){
      
     }
     
     public void adjustmentValueChanged(AdjustmentEvent e){
      int value;
      Font oldF;
      if (e.getAdjustable() == s) {
    value = e.getValue();
    txtValue.setText(new Integer(value).toString());
    oldF = txtValue.getFont();
    txtValue.setFont(new Font(oldF.getName(), oldF.getStyle(), value));  
      }
     }
 }

9.测试按钮和画布的鼠标事件例子

UserMouseEvent.java

 

package SampleGUI;
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;public class UserMouseEvent extends Applet implements MouseListener, MouseMotionListener{
  Button btn;
  public void init(){
   btn = new Button("演示鼠标事件");
   add(btn);
   // 给按钮添加鼠标事件和鼠标移动事件
   btn.addMouseListener(this);
   btn.addMouseMotionListener(this);
   //给画布添加鼠标事件和鼠标移动事件
   this.addMouseListener(this);
   this.addMouseMotionListener(this);
  }
  
  public void mouseClicked(MouseEvent e){
   Point p = new Point();
   if (e.getSource() == btn) {
    if (e.getClickCount() == 1) {
     btn.setLabel("单击鼠标");
    }else if (e.getClickCount() == 2) {
     btn.setLabel("双击鼠标");
    }
   }else{
    if (e.getClickCount() == 1) {
     p = e.getPoint();
     showStatus(p.x+","+p.y+"单击鼠标");
     
    }else if (e.getClickCount() == 2) {
     p = e.getPoint();
     showStatus(p.x+","+p.y+"双击鼠标");
    }
   }
  }
  
  public void mouseEntered(MouseEvent e){
   if (e.getSource() == btn) {
    btn.setLabel("进入Button");
   }else{
    showStatus("进入Applet");
   }
  }
  
  public void mouseExited(MouseEvent e){
   if (e.getSource() == btn) {
    btn.setLabel("退出Button");
   }else{
    showStatus("退出Applet");
   }
  }
  
  public void mousePressed(MouseEvent e){
   if (e.getSource() == btn) {
    btn.setLabel("按下鼠标");
   }else{
    showStatus("按下鼠标");
   }
  }
  
  public void mouseReleased(MouseEvent e){
   if (e.getSource() == btn) {
    btn.setLabel("松开鼠标");
   }else{
    showStatus("松开鼠标");
   }
  }
  
     public void mouseMoved(MouseEvent e){
   if (e.getSource() == btn) {
    btn.setLabel("移动鼠标");
   }else{
    showStatus("移动鼠标,新位置"+e.getX()+","+e.getY());
   }
     }
     
     public void mouseDragged(MouseEvent e){
   if (e.getSource() == btn) {
    btn.setLabel("拖动鼠标");
   }else{
    showStatus("拖动鼠标");
   }
     } 
 }

 

10.测试键盘事件的例子

UserKeyEvent.java

package SampleGUI;
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;public class UserKeyEvent extends Applet implements KeyListener{
 Button btn;
  public void init(){
   btn = new Button("test");
   btn.addKeyListener(this);
   this.addKeyListener(this);
   add(btn);
  }
  
  @Override
  public void keyPressed(KeyEvent e) {
   // TODO Auto-generated method stub
   char ch = e.getKeyChar();
   if (ch == 'Y' || ch == 'y') {
    btn.setLabel("同意");
   }else if (ch == 'N' || ch == 'n') {
    btn.setLabel("反对");
   }else{
    btn.setLabel("无效");
   }
  } @Override
  public void keyTyped(KeyEvent e) {
   // TODO Auto-generated method stub
   
  } @Override
  public void keyReleased(KeyEvent e) {
   // TODO Auto-generated method stub
   
  }
  
 }

 

11. 测试输入输出流例子

 

SystemIO.java文件

package MThread;
 import java.io.*;public class SystemIO{
  public static void main(String []args){
   int bytes = 0;
   byte buf[] = new byte[255];
   System.out.println("\n请输入任意文本: ");
   try
    {
    bytes = System.in.read(buf, 0, 255);
    System.out.println("这是你输入的文本行: ");
    String inSr = new String(buf, 0, bytes);
    System.out.println(inSr);
    
    
          } catch (Exception e) {
    // TODO: handle exception
    System.out.println(e.getMessage());
   }
  }
 }

 

例子一 UserFileInputStream.java文件

package MThread;
 import java.io.*;public class UserFileInputStream{
  public static void main(String []args){
   byte buf[] = new byte[2056];
   try {
    FileInputStream fileIn = new FileInputStream("./src/Mthread/UserFileInputStream.java");
    int bytes = fileIn.read(buf, 0, 2056);
    String inSr = new String(buf, 0, bytes);
    System.out.println(inSr);
   } catch (Exception e) {
    // TODO: handle exception
    System.out.println(e.getMessage());
   }
  }
 }

例子二 UserFileOutputStream.java文件 

package MThread;
 import java.io.*;public class UserFileOutputStream{
  public static void main(String []args){
   byte buf[]  = new byte[255];
   byte bufIn[] = new byte[255];
   
   try {
    String str = "你好,这是已有的文本";
    buf = str.getBytes();
    
    FileOutputStream fileOut = new FileOutputStream("Hello.txt");
    
    fileOut.write(buf, 0, buf.length);
    fileOut.flush();
    fileOut.close();
    
    System.out.println("\n请输入一行文本: ");
    
    int bytes = System.in.read(bufIn, 0, 255);
    
    fileOut = new FileOutputStream("Hello.txt", true);
    fileOut.write(bufIn, 0, bytes);
   } catch (Exception e) {
    // TODO: handle exception
    System.out.println(e.getMessage());
   }
  }
 }

例子三 线程

MThread.java文件

package MThread;
 //package MThread;
 import java.applet.*;
 import java.awt.*;
 import java.awt.event.*;
 import java.applet.Applet;public class MThread{
  public static void main(String []args){
   System.out.println("HelloWorld");
   thread2 t1= new thread2("线程实例1");
   t1.start();
   
   thread2 t2 = new thread2("线程实例2");
   t2.start();
   
   thread2 t3 = new thread2("线程实例3");
   t3.start();
  }
 }class thread2 extends Thread{
  Thread thread;
  String str;
  public thread2(String str){
   this.str = str;
  }
  
  public void start(){
   thread = new Thread(this);
   thread.start();
  }
  
  public void run(){
   int i = 0;
   while (thread != null) {
    try {
     if (5 == i) {
      sleep(10000);
     }
    } catch (Exception e) {
     // TODO: handle exception
     System.out.println(e.getMessage());
    }
    
    System.out.println(str);
    i++;
   }
  }
 }

 

例子四 线程

UserRunnable.java

package MThread;
 import java.awt.*;
 import java.applet.*;
 import java.applet.Applet;public class UserRunnable extends Applet implements Runnable{
  Thread t;
  Image imgs[];
  int high, h1, h2, h3;
  public void init(){
   high = getHeight()/3;
   h1 = high;
   h2 = high * 2;
   h3 = high * 3;
   imgs = new Image[3];
   for (int i = 0; i < 3; i++) {
    imgs[i] = getImage(getDocumentBase(), "image"+(i+1)+".png");
   }
   
  }
  
  public void start(){
   t = new Thread(this);
   t.start();
  }
  
  public void stop(){
   t = null;
  }
  public void run(){
   while (t != null) {
    try {
     Thread.sleep(10000);
     repaint();
     h1--;
     
     if (0 == h1) {
      Thread.sleep(30000);
      h2 = high;
     }
     h2--;
     if (0 == h2) {
      Thread.sleep(30000);
      h3 = high;
     }
     h3--;
     if (0 == h3) {
      Thread.sleep(30000);
      h1 = high;
     }
     
    } catch (Exception e) {
     // TODO: handle exception
     System.out.println(e.getMessage());
    }  }
  }
  
  public void paint(Graphics g){
   g.drawImage(imgs[0], 0, h1, this);
   g.drawImage(imgs[1], 0, h2, this);
   g.drawImage(imgs[2], 0, h3, this);
  }
  
  public void update(Graphics g){
   paint(g);  
  }
 }

 

UserFile.java文件

package MThread;
 import java.io.*;public class UserFile{
  public static void main(String []args){
   try {
    File f = new File("temp.txt");
    System.out.println("创建临时文件");
    FileOutputStream  fout = new FileOutputStream(f);
    PrintStream p = new PrintStream(fout);
    p.println("将这句话写入临时文件");
    System.out.println("写临时文件");
    p.close();
    f.deleteOnExit();
    System.out.println("删除临时文件");
   } catch (Exception e) {
    // TODO: handle exception
    System.out.println(e.getMessage());
   }
  }
 }

 

数据库编程例子

UserJDBC.java

1. 先用Microsoft Visual FoxPro 6.0建立FoxPro数据库,数据库名为Student.mdb, 其中一个表为Xuesheng.dbf, 表中有学号、姓名、班级、出生日期、性别字段, 并添加几条记录进去。

2.配置ODBC数据源: 依次找到程序---管理工具---数据源(ODBC)(在控制面板中可以找到ODBC),调出“ODBC数据源管理器”,点击“添加”按钮,出现“创建新数据源”窗口,选择Microsoft Visual FoxPro Driver,点击完成。进入“ODBC Visual FoxPro Setup”窗口。

Data Source Name: ODBC提供给应用程序的数据库的名字。( 给数据库取个名字)

Description: 用来说明数据库的文字信息,根据自己的需要填写。

Path: ODBC映射数据库的具体路径,可以直接填写完整路径,也可以点击“Browse(浏览)”按钮选择数据库,这里选择之前建立的Student.mdb数据库,点击OK按钮,可以看见“ODBC数据源管理器”窗口多了一个STU数据源。

package MThread;
 import java.sql.*;public class UserJDBC{
  public static void main(String []args){
   try {
    Statement stmt;
    PreparedStatement pstmt;
    ResultSet rs;
    
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    String urlName = "jdbc:odbc:STU";
    
    Connection conn = DriverManager.getConnection(urlName, "", "");
    stmt = conn.createStatement();
    rs = stmt.executeQuery("select 学号, 姓名, 班级 from Xuesheng WHERE 班级='025'");
    System.out.println("显示所有返回结果: ");
    
     while(rs.next()) {
     String strNumber = rs.getString("学号");
     String strName = rs.getString("姓名");
     String strClass = rs.getString(3);
     System.out.println("学号: "+strNumber+" 姓名: "+strName+" 班级:"+strClass);
    }
     
     pstmt = conn.prepareStatement("UPDATE Xuesheng SET 班级= ? WHERE 班级=?");
     pstmt.setString(1, "计算机");
     pstmt.setString(2, "025");
     pstmt.executeUpdate();
     conn.close();
   } catch (Exception e) {
    // TODO: handle exception
    e.printStackTrace();
   }
  }
 }