JAVA用SWT写的界面,怎样把数据库里面的表显示在SWT的table中?并且实现修...
发布网友
发布时间:2024-01-05 01:21
我来回答
共1个回答
热心网友
时间:2024-09-30 11:20
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
public class TabViewTest {
public void open() throws Exception{
Display display=new Display();
Shell shell=new Shell(display);
shell.setLayout(new FillLayout());
shell.setSize(new Point(400,300));
Table table=new Table(shell,SWT.MULTI | SWT.FULL_SELECTION |SWT.BORDER);
table.setHeaderVisible(true);
table.setLinesVisible(true);
TableColumn idColumn =new TableColumn(table,SWT.LEFT);
idColumn.setText("id");
idColumn.setWidth(100);
TableColumn usernameColumn=new TableColumn(table,SWT.LEFT);
usernameColumn.setText("username");
usernameColumn.setWidth(100);
TableColumn passwordColumn=new TableColumn(table,SWT.LEFT);
passwordColumn.setText("password");
passwordColumn.setWidth(100);
Connection conn=getAcessConnection();
String sqlString="select * from user";
Statement statement=conn.createStatement();
ResultSet rSet=statement.executeQuery(sqlString);
while(rSet.next()){
TableItem item=new TableItem(table,SWT.LEFT);
String[] valueStrings={rSet.getInt("id")+"0",rSet.getString("username"),rSet.getString("password")};
item.setText(valueStrings);
}
rSet.close();
statement.close();
conn.close();
shell.open();
while(!shell.isDisposed()){
if( !display.readAndDispatch()){
display.sleep();
}
}
display.dispose();
}
public static void main(String[] args) throws Exception {
new TabViewTest().open();
}
public Connection getAcessConnection(){
Connection conn=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
URL url1=TabViewTest.class.getClassLoader().getResource("db/test.mdb");
String path=url1.getPath();
path=path.substring(1, path.length());
String url="jdbc:odbc:driver={Microsoft Access Driver (*.mdb)};DBQ="+path;
conn=DriverManager.getConnection(url);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
}
数据库用的是access,楼主可以自己随便修改下的。