TestDefaultListModel-java數據庫調用示例

//author:Young Yuan

//email:[email protected]; [email protected]

//function:calling database in java list model


package javaSwing;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import java.util.Vector;


public class TestDefaultListModel
{
public static void main(String[] args) 
{
JFrame f=new JFrame("Name"); //Create the below frame
Container contentPane=f.getContentPane(); //Create the content pane by getContentPane
contentPane.setLayout(new FlowLayout()); //Set the layout of the content pane is flow layout
String str="select name from stu_info"; //query statement
TestDB db=new TestDB(); //create the case of the TestDB to connect database
ResultSet rs=db.query(str); //Call the function function to search
/*
*The below codes put the result set to the array name
*/
try
{
rs.last(); //move to the last line of the result set
int i=rs.getRow(); //get the number of lines to write into variable i
rs.beforeFirst(); //move to the first line of the result set
String name[]=new String[i]; //Create the array name whose length is i
int m=0;
while(rs.next()){ //Loop to get the data and put into the array name


name[m]=rs.getString(1);
m++;
}


DefaultListModel mode=new DefaultListModel(); //Create the model of list
for(int k=0;k<name.length;k++){
mode.addElement(name[k]); //Add the iterms of list
}
JList list=new JList(mode); //Create the list
list.setVisibleRowCount(3); //Set the initial visible length of list is 3
contentPane.add(new JScrollPane(list)); //Add to the list to the scrollpane


}
catch (SQLException e)
{
//TODO Auto-generated catch block
e.printStackTrace();
}
f.pack(); //pack is used to adjust the size of frame to adapt the initial size of the component
f.setVisible(true); //Set the pane is visible
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){ //Set the listener,close the window and finish the program
System.exit(0);

}
});
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章