求一个java 表格 输出数据库表的方法

啊飞凤飞飞 2009-05-06 11:43:21
因为用netbeans,那个设计UI的,自己先画了一个表格,想让表格输出数据库一个表的内容,求大家帮我写个.假设 数据库的class表,内容有 classid ,gradeid ,classname,现在要在表中输出这三列内容,表的长度未定,根据数据库内容调整. 因为要用到数组集合什么的,,我脑袋特晕.. 求大家给个能用的.
...全文
1030 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
houzhanli222 2010-03-15
  • 打赏
  • 举报
回复
怎么给行赋值啊?
Emerson_Li 2009-05-07
  • 打赏
  • 举报
回复
不好意思,我上面的equals写错了~~汗一个,写太快了。。。。。。
Emerson_Li 2009-05-07
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 cfanschina 的回复:]
楼上的,我的成功了,但是怎么更改jtable的列名啊?我之前在数据库表的列名都是字母,想换成汉字的
[/Quote]

public String getColumnName(int column) {
return rsmd.getColumnName(column+1);

}
这个就是返回名字的方法啊~~那你在这里加入转换就好了
比如:

public String getColumnName(int column) {
if(column==0){
return " VIP号 ";
}
else if(column==1){
return " 名字 ";
}
else if(column==2){
return " 电话 ";
}
else if(column==3){
return " 地址 ";
}
else if(column==4){
return " 出生月份 ";
}
else if(column==5){
return " 出生日期 ";
}
else if(column==6){
return " 会员等级 ";
}
else return " 会员描述 ";
}


但是这样就失去了复用性,这个model就只能用于这一个表了,不过也有折中的办法那就是:

public String getColumnName(int column) {
if(rsmd.getColumnName(column+1).euqals("VID")){
return " VIP号 ";
}
......
else if(rsmd.getColumnName(column+1).euqals("level")){
return " 会员等级 ";
}
else return " 会员描述 ";
}



这样的话,你可以把所有的表的column都加入,使这个model类适用于整个数据库,这是没办法的办法了。

其实我最先给你的model是最具有复用性的,能显示任何查询表结构,你可以保存起来以后用哦~~
qusic 2009-05-07
  • 打赏
  • 举报
回复
String getColumnName(int columnIndex)
这是TableModel的一个方法
只要实现这个方法即可,DefaultTableModel有默认的实现
楼主自己研究研究去吧~
啊飞凤飞飞 2009-05-07
  • 打赏
  • 举报
回复
楼上的,我的成功了,但是怎么更改jtable的列名啊?我之前在数据库表的列名都是字母,想换成汉字的
  • 打赏
  • 举报
回复
显示效果:

希望对楼主有帮助,楼主参考一下
  • 打赏
  • 举报
回复
import java.awt.Rectangle;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;


public class TestTable extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;

DefaultTableModel model = new DefaultTableModel();

JTable table = new JTable(model);

public TestTable() {
model.addColumn("Id");
model.addColumn("Firstname");
model.addColumn("lastname");
model.addColumn("123");
this.getContentPane().setLayout(null);
//table.setBounds(new Rectangle(100,10,300,200));
this.getContentPane().add(table);
this.setSize(500,400);
this.setVisible(true);
this.setTitle("ͨѶ¼");


}


public static void main(String args []){

new TestTable();

}


}

这是测试代码,可以运行
  • 打赏
  • 举报
回复
package com.jercy.java;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
//import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;

public class MyFrame extends JFrame{


/**
*
*/
private static final long serialVersionUID = 1L;


private JMenuItem saveItem, closeItem, addItem, deleteItem;
JButton saveButton,refreshButton,exitButton;
private JMenuBar menuBar= new JMenuBar();
private JComboBox jComBox;
JPanel bottomPanel,topPanel;
DefaultTableModel myData = new DefaultTableModel();
private JTable jTable = new JTable(myData);
private JScrollPane scrollPane = new JScrollPane(jTable);

public MyFrame(){
//获取总的容器,并设置布局管理器
Container content=this.getContentPane();
content.setLayout(new BorderLayout());

//设置窗口的基本位置
Toolkit theKit=getToolkit();
Dimension wndSize=theKit.getScreenSize();//Get screen size

setBounds(wndSize.width/4,wndSize.height/4,wndSize.width/2,wndSize.height/2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//创建菜单组件
JMenu fileMenu=new JMenu("File");
JMenu contactsMenu=new JMenu("Contacts");

saveItem=new JMenuItem("Save");
closeItem=new JMenuItem("Close");
addItem=new JMenuItem("Add");
deleteItem=new JMenuItem("Delete");

//为每个菜单项添加相应的监听器
saveItem.addActionListener(new MenuListener());
closeItem.addActionListener(new MenuListener());
addItem.addActionListener(new MenuListener());
deleteItem.addActionListener(new MenuListener());

//菜单项加入到具体菜单中
fileMenu.add(saveItem);
fileMenu.add(closeItem);
contactsMenu.add(addItem);
contactsMenu.add(deleteItem);

//把菜单加入到菜单栏中
menuBar.add(fileMenu);
menuBar.add(contactsMenu);


//创建按钮
saveButton=new JButton("save");
refreshButton=new JButton("refresh");
exitButton=new JButton("exit");

//为每个按钮添加相应的监听器
saveButton.addActionListener(new ButtonListener());
refreshButton.addActionListener(new ButtonListener());
exitButton.addActionListener(new ButtonListener());

//把按钮加入到它所在的容器中
bottomPanel=new JPanel();
bottomPanel.add(saveButton);
bottomPanel.add(refreshButton);
bottomPanel.add(exitButton);

//创建下拉菜单并加入到它所在的容器中
String[] str={"Freinds","Public","Work","Family"};
jComBox=new JComboBox(str);
jComBox.addActionListener(new ComBoxListener());
topPanel=new JPanel();
topPanel.add(jComBox);


//创建表格并加入到它所在的容器中
myData.addColumn("ID");
myData.addColumn("lastName");
myData.addColumn("firstName");
myData.addColumn("telephone");

//scrollPane.add(jTable);

//把各个容器加入到框架中。
content.add(topPanel,BorderLayout.NORTH);
content.add(scrollPane,BorderLayout.CENTER);
content.add(bottomPanel,BorderLayout.SOUTH);
this.setJMenuBar(menuBar);
//设置窗口
//aWindow.pack();
setTitle("通讯录");
setSize(500,400);
setVisible(true);

}



public static void main(String[] args){

new MyFrame();


}


//对菜单进行监听
class MenuListener implements ActionListener{

String idString,lastNameString,firstNameString,telephoneString;

public void actionPerformed(ActionEvent e) {


// TODO Auto-generated method stub
if(e.getSource() == saveItem){

//对save按钮进行处理,对当前做的修改进行保存
int indexRow;
indexRow = jTable.getSelectedRow();

//获取所选行的数据,为以后在数据库中保存,更新
idString = (String) jTable.getValueAt(indexRow, 0);
lastNameString = (String) jTable.getValueAt(indexRow, 1);
firstNameString = (String) jTable.getValueAt(indexRow, 2);
telephoneString = (String) jTable.getValueAt(indexRow, 3);


Database database=new Database();
String sqlString = "update user set ID = " + idString + "set lastName = " + lastNameString + "set firstName = " + firstNameString +"set telephone = " + telephoneString;
database.executeUpdate(sqlString);

}else if(e.getSource() == closeItem){
System.exit(0);

}else if(e.getSource() == addItem){
new Contacts();

}else if(e.getSource() == deleteItem){

int indexRow;
indexRow = jTable.getSelectedRow();

//把所选行的数据行进行删除
idString = (String) jTable.getValueAt(indexRow, 0);
lastNameString = (String) jTable.getValueAt(indexRow, 1);
firstNameString = (String) jTable.getValueAt(indexRow, 2);
telephoneString = (String) jTable.getValueAt(indexRow, 3);


Database database=new Database();
String sqlString = "delete user where ID = "+idString + ";";
database.executeUpdate(sqlString);


}
}

}



class ButtonListener implements ActionListener{

String idString,lastNameString,firstNameString,telephoneString;

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == saveButton){
int indexRow;
indexRow = jTable.getSelectedRow();

//获取所选行的数据,为以后在数据库中保存,更新,这个按钮的功能和file 菜单下的save按钮作用一样
idString = (String) jTable.getValueAt(indexRow, 0);
lastNameString = (String) jTable.getValueAt(indexRow, 1);
firstNameString = (String) jTable.getValueAt(indexRow, 2);
telephoneString = (String) jTable.getValueAt(indexRow, 3);


Database database=new Database();
String sqlString = "update user set ID = " + idString + "set lastName = " + lastNameString + "set firstName = " + firstNameString +"set telephone = " + telephoneString + ";";
database.executeUpdate(sqlString);


}else if(e.getSource() == refreshButton){

//直接把数据库中现有的数据来显示以覆盖以前的数据
Database database=new Database();
String sqlString = "select * from user" +";";
database.executeUpdate(sqlString);

}else if(e.getSource() == exitButton){
System.exit(0);
}
}

}


class ComBoxListener implements ActionListener{

private String selectedItem;

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub

selectedItem = (String) jComBox.getSelectedItem();

/*if("Freinds" == selectedItem){

}else if("Public" == selectedItem){

}else if("Work" == selectedItem){

}else if("Family" == selectedItem){

}
*/
Database database=new Database();
System.out.println(selectedItem);
String sqlString = "select ID,lastName,firstName,telephone from user where(groupid = "+"'"+selectedItem+"'"+")";

database.resultSet = database.executeQuery(sqlString);



try {
while(database.resultSet.next()){
String[] temparray = {
database.resultSet.getString("ID"),
database.resultSet.getString("lastName"),
database.resultSet.getString("firstName"),
database.resultSet.getString("telephone")};
myData.addRow(temparray);
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}




}

}



}

这是个完整的例子
  • 打赏
  • 举报
回复
数据库操作类

package com.jercy.java;

import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;

import com.mysql.jdbc.Connection;

public class Database {

String dbDriver;
String connectionString;
String userName;
String password;


Connection connection = null;
Statement statement = null;
PreparedStatement prepareStatement = null;
ResultSet resultSet = null;


public Database(){
dbDriver = "com.mysql.jdbc.Driver";
connectionString = "jdbc:mysql://localhost/user";
userName = "root";
password = "123456";

}


public Connection getConnection() {
try {
Class.forName(dbDriver);
System.out.println("Success loading MySQL driver.");

connection = (Connection) DriverManager.getConnection(connectionString,
userName, password);
System.out.println("Success connecting MySQL DataBase.");
} catch (SQLException e) {
System.out.println("database.executeQuery:" + e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println("database():" + e.getMessage());
}
return connection;
}


public void executeInsert(String sqlString) {
connection = this.getConnection();
try {
statement = connection.createStatement();
statement.executeUpdate(sqlString);
} catch (SQLException e) {
//System.out.println("database.executeUpdate:" + e.getMessage());
e.printStackTrace();
}
}

public void executeUpdate(String sqlString) {
connection = this.getConnection();
try {
statement = connection.createStatement();
statement.executeUpdate(sqlString);
} catch (SQLException e) {
System.out.println("database.executeUpdate:" + e.getMessage());
}
}

public ResultSet executeQuery(String sqlString) {
connection = this.getConnection();
try {
statement = connection.createStatement();
resultSet = statement.executeQuery(sqlString);
} catch (SQLException e) {
System.out.println("database.executeQuery:" + e.getMessage());
} catch (NullPointerException e) {
e.printStackTrace();
}
return resultSet;
}

public void executeDelete(String sqlString) {
connection = this.getConnection();
try {
statement = connection.createStatement();
statement.executeUpdate(sqlString);
} catch (SQLException e) {
System.out.println("database.executeDelete:" + e.getMessage());
}
}

public PreparedStatement getPrepareStatement(String sqlString) {
connection = this.getConnection();
try {
prepareStatement = connection.prepareStatement(sqlString);
} catch (SQLException e) {
System.out.println("database connection error.");
}

return prepareStatement;
}

public void close() {
try {
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}

public String getConnectionString() {
return connectionString;
}

public void setConnectionString(String connectionString) {
this.connectionString = connectionString;
}

public String getDbDriver() {
return this.dbDriver;
}

public void setDbDriver(String dbDriver) {
this.dbDriver = dbDriver;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getUserName() {
return userName;
}

public void setUserName(String UserName) {
this.userName = UserName;
}
}




/*public void save(TableModel myData) throws SQLException{

int rowCount=myData.getRowCount();

Vector<String[]> data = new Vector<String[]>();

for(int i = 0;i < rowCount; i++){
String[] temparray = {
(String)myData.getValueAt(i, 0),
(String)myData.getValueAt(i, 1),
(String)myData.getValueAt(i, 2),
(String)myData.getValueAt(i, 3)};
data.add(temparray);
}
database.save(data);
isChange = false;

}


public void delete()throws SQLException{
int selIndex = table.getSelectRow();

if(selIndex < 0 || selIndex >=table.getRowCount()){
return;
}

Vector mv = model.getDataVector();
Vector v = (Vector)mv.elementAt(selIndex);
int ID=Integer.parseInt(v.get(0).toString());
dataBase.delete(ID);
}*/

  • 打赏
  • 举报
回复
[Quote=引用楼主 cfanschina 的帖子:]
因为用netbeans,那个设计UI的,自己先画了一个表格,想让表格输出数据库一个表的内容,求大家帮我写个.假设 数据库的class表,内容有 classid ,gradeid ,classname,现在要在表中输出这三列内容,表的长度未定,根据数据库内容调整. 因为要用到数组集合什么的,,我脑袋特晕.. 求大家给个能用的.
[/Quote]
楼主参考一下,我以前学校做的一个同学里的代码

package com.jercy.java;

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Dimension;
//import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

public class Contacts extends JFrame{


/**
*
*/
private static final long serialVersionUID = 1L;
private JTextField lastNameText,firstNameText,telephoneText;
private JLabel lastNameLabel,firstNameLabel,telephoneLabel;
private ButtonGroup buttonGroup;
private JRadioButton friendsButton,publicButton,workButton,familyButton;
private JButton saveButton,cancelButton;
private Box topbox,centerbox1,centerbox2,bottombox,highbox;

public Contacts(){

//获取总的容器,并设置布局管理器
Container content=this.getContentPane();
content.setLayout(new BorderLayout());


//设置窗口的基本位置
Toolkit theKit=getToolkit();
Dimension wndSize=theKit.getScreenSize();//Get screen size

setBounds(wndSize.width/4,wndSize.height/4,wndSize.width/2,wndSize.height/2);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//创建按钮
friendsButton = new JRadioButton("Friends",true);
publicButton = new JRadioButton("Public",false);
workButton = new JRadioButton("Work",false);
familyButton = new JRadioButton("Family",false);

saveButton = new JButton("Save");
cancelButton = new JButton("cancel");


//创建标签和文本欲
firstNameLabel = new JLabel("firstName");
lastNameLabel = new JLabel("LastName");
telephoneLabel = new JLabel("TelephoneNumber");

lastNameText = new JTextField();
firstNameText = new JTextField();
telephoneText = new JTextField();

//把按钮加入到按钮组中
buttonGroup = new ButtonGroup();
buttonGroup.add(friendsButton);
buttonGroup.add(publicButton);
buttonGroup.add(workButton);
buttonGroup.add(familyButton);


//创建水平BOX容器,并把响应的组件加进去
topbox = Box.createHorizontalBox();
topbox.add(Box.createVerticalStrut(60));
topbox.add(friendsButton);
topbox.add(Box.createHorizontalStrut(40));
topbox.add(publicButton);
topbox.add(Box.createHorizontalStrut(40));
topbox.add(workButton);
topbox.add(Box.createHorizontalStrut(40));
topbox.add(familyButton);



centerbox1 = Box.createHorizontalBox();
centerbox1.add(Box.createVerticalStrut(80));
centerbox1.add(firstNameLabel);
centerbox1.add(Box.createHorizontalStrut(40));
centerbox1.add(lastNameLabel);
centerbox1.add(Box.createHorizontalStrut(40));
centerbox1.add(telephoneLabel);
centerbox1.add(Box.createHorizontalStrut(40));

centerbox2 = Box.createHorizontalBox();
centerbox2.add(Box.createVerticalStrut(10));
centerbox2.add(firstNameText);
centerbox2.add(Box.createHorizontalStrut(40));
centerbox2.add(lastNameText);
centerbox2.add(Box.createHorizontalStrut(40));
centerbox2.add(telephoneText);
centerbox2.add(Box.createHorizontalStrut(40));

bottombox = Box.createHorizontalBox();
bottombox.add(Box.createVerticalStrut(150));
bottombox.add(saveButton);
bottombox.add(Box.createHorizontalStrut(40));
bottombox.add(cancelButton);

//添加Listener
saveButton.addActionListener(new ButtonListener());
cancelButton.addActionListener(new ButtonListener());

highbox = Box.createVerticalBox();//建立一个垂直BOX组件。
highbox.add(topbox);
highbox.add(centerbox1);
highbox.add(centerbox2);
highbox.add(bottombox);


//把相关的BOX加入到容器中
JPanel pCenter = new JPanel();
pCenter.add(highbox);
content.add(pCenter,BorderLayout.CENTER);

//设置窗口
this.setTitle("通讯录");
this.setSize(500,400);
this.setVisible(true);

}

//对按钮进行监听
class ButtonListener implements ActionListener{

public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if(e.getSource() == saveButton){

String groupItem = null;
String firstName,lastName,telephoneNumber;

//获取按钮的数据
if(friendsButton.isSelected()){
groupItem = friendsButton.getText();
}else if(publicButton.isSelected()){
groupItem = publicButton.getText();
}else if(workButton.isSelected()){
groupItem = workButton.getText();
}else if(familyButton.isSelected()){
groupItem = familyButton.getText();
}

//获取文本区域的数据
firstName = firstNameText.getText();
lastName = lastNameText.getText();
telephoneNumber = telephoneText.getText();


//判断文本区域的值不能为空
if(firstName.equals(" ") && lastName.equals(" ") && telephoneNumber.equals(" ")){
String warnning = "输入的数据不能为空!";
JOptionPane.showConfirmDialog(new JPanel(), warnning,"警告",JOptionPane.WARNING_MESSAGE);
}

//把数据插入到数据库中
Database database=new Database();
String sqlString = "insert into user(lastName,firstName,telephone,groupid) values('"+lastName+"','"+firstName+"','"+telephoneNumber+"','"+groupItem+"')";
//String sqlString = "insert into user(lastName,firstName,telephone) values ('"+lastName+"','"+firstName+"','"+telephoneNumber+"')";
database.executeInsert(sqlString);


JOptionPane.showConfirmDialog(new JPanel(), "恭喜,添加成功!","消息",JOptionPane.INFORMATION_MESSAGE);


}else if(e.getSource() == cancelButton){
System.exit(0);
}
}

}
}
goodmrning 2009-05-07
  • 打赏
  • 举报
回复
主要的几个点:
1、确定表有多少行。
2、按表的行数画表格。
JPanel panel=new JPanel(new BorderLayout());
JTable talbe=new JTable(n+1,3);
panel.add(table,BorderLayout.CENTER);
..........

Emerson_Li 2009-05-07
  • 打赏
  • 举报
回复
首先你必须继承Jtable的model类,然后用你自己的model去设置Jtabel,不知道什么是model,请查MVC设计思想。



package Frame;

import java.sql.*;

import javax.swing.JButton;
import javax.swing.table.AbstractTableModel;

public class ResultSetTableModel extends AbstractTableModel {

ResultSet rs=null;
ResultSetMetaData rsmd =null;

public ResultSetTableModel(ResultSet rs) {
this.rs=rs;
try {
rsmd=rs.getMetaData();
} catch (SQLException e) {
e.printStackTrace();
return;
}
}

@Override
public int getColumnCount() {
try {
return rsmd.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
return 0;
}
}

@Override
public int getRowCount() {
try {
rs.last();
return rs.getRow();
} catch (SQLException e) {
e.printStackTrace();
return 0;
}
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
try {
rs.absolute(rowIndex+1);
return rs.getObject(columnIndex+1);
} catch (SQLException e) {
e.printStackTrace();
return "null";
}

}

@Override
public String getColumnName(int column) {
return rsmd.getColumnName(column+1);

}

}



最后你只要
ResultSetTableModel rstm=new ResultSetTableModel(rs);
table.setModel(rstm);
即可
啊飞凤飞飞 2009-05-07
  • 打赏
  • 举报
回复
其实我要的就是 一个 如何将 ResultSet rs的值传递给数组, 然后如何用这个数组创建一个表格jtable,其他的都明白.

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧