前两天刚写了,慢慢回忆下:
首先看Api Jtable的构造 JTable table=new Jtable(Object[][] data,Object []ColumnNames) ,还有许多其他构造根据需求选择。data二维数组表示表中的jable中的数据项,ColumnNames数组是表头。接着就是从数据库中读取数据。获取数据库中属性即表头有相应的API,可以查看。获取数据放到二维数组没有相应的方法但并不难。table最后还要放到JScrollPane中,不然不显示表头 即
jscrollPane.setViewportView(table),最后再把jscrollPane放到JFrame中。自己去试着实现,可能觉得很难,当懂了后很简单的。有什么问题或需要源码可以追问。下面连java 连oracle代码给你:
String driver="oracle.jdbc.driver.OracleDriver"
String conUrl="jdbc:oracle:thin:@localhost:1521:XE"
String user="system"
String psw="123"
Connection con
try{
Class.forName(driver)
System.out.println("加载成功!")
}catch(ClassNotFoundException e){
e.printStackTrace()
System.out.println("驱动加载失败")
}
try{
con= DriverManager.getConnection(conUrl,user,psw)
System.out.println("数据库连接成功!")
}catch(SQLException e){
e.printStackTrace()
System.out.println("数据库连接失败!")
}finally{
try{
if(con!=null)con.close()
System.out.println("数据库关闭成功!")
}catch(SQLException e){
e.printStackTrace()
System.out.println("数据库关闭异常!")
}
}
准备工作是你要配置连接oracle驱动ojdbc14.jar。
对数据库 *** 作看statement 三个主要方法。
写得很混乱,自己将就着看下。
public class T extends JFrame {private static final long serialVersionUID = 1L
private JPanel jPanel = null
private JTextField jTextField = null
private JTextField jTextField1 = null
private JButton jButton = null
private JButton jButton1 = null
private JButton jButton2 = null
private JTable jTable = null
private DefaultTableModel tableModel = null
private JPanel getJPanel() {
if (jPanel == null) {
JLabel jLabel1 = new JLabel()
jLabel1.setBounds(new Rectangle(30, 50, 80, 25))
jLabel1.setText("请输入ISBN:")
JLabel jLabel = new JLabel()
jLabel.setBounds(new Rectangle(30, 20, 80, 25))
jLabel.setText("请输入书名:")
jPanel = new JPanel()
jPanel.setLayout(null)
jPanel.setPreferredSize(new Dimension(1, 120))
jPanel.add(jLabel)
jPanel.add(jLabel1)
jPanel.add(getJTextField())
jPanel.add(getJTextField1())
jPanel.add(getJButton())
jPanel.add(getJButton1())
jPanel.add(getJButton2())
}
return jPanel
}
private JTextField getJTextField() {
if (jTextField == null) {
jTextField = new JTextField()
jTextField.setBounds(new Rectangle(120, 20, 140, 25))
}
return jTextField
}
private JTextField getJTextField1() {
if (jTextField1 == null) {
jTextField1 = new JTextField()
jTextField1.setBounds(new Rectangle(120, 50, 140, 25))
}
return jTextField1
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton()
jButton.setBounds(new Rectangle(270, 20, 60, 25))
jButton.setText("显示")
jButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* 修改处 */
}
})
}
return jButton
}
private JButton getJButton1() {
if (jButton1 == null) {
jButton1 = new JButton()
jButton1.setBounds(new Rectangle(270, 50, 60, 25))
jButton1.setText("显示")
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/* 修改处 */
}
})
}
return jButton1
}
private JButton getJButton2() {
if (jButton2 == null) {
jButton2 = new JButton()
jButton2.setBounds(new Rectangle(240, 80, 90, 30))
jButton2.setText("显示全部")
jButton2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
/*
* 修改处此处只要改下面一行,换成从数据库读就行
* 应该在DAO层加一个查询全部的方法
* public List<Titles>getAll()具体实现自己写。
* 把114行的代码改成:List<Titles>lists = new TitleDaoImpl().getAll()
* */
List<Titles>lists = Titles.list()
// 将表行数设为0行,防止异常
tableModel.setRowCount(0)
for (int i = 0i <lists.size()i++) { // 当每有一个Titles对象就添加一行
tableModel.addRow(new Object[] {})
}
Titles instance = null
Object obj = null
Object name = null
for (int i = 0i <tableModel.getRowCount()i++) { // 行循环
instance = lists.get(i) // 为当前Titles对象赋值
for (int j = 0j <tableModel.getColumnCount()j++) {
name = tableModel.getColumnName(j)
if (name.equals("ISBN")) {
obj = instance.getISBN()
} else if (name.equals("title")) {
obj = instance.getTitle()
} else if (name.equals("publisher")) {
obj = instance.getPublisher()
} else if (name.equals("date")) {
obj = instance.getDate()
} else if (name.equals("price")) {
obj = instance.getPrice()
} else {
obj = ""
}
tableModel.setValueAt(obj, i, j)
}
}
}
})
}
return jButton2
}
private JPanel getJPanel1() {
JScrollPane jScrollPane = new JScrollPane()
jScrollPane.setViewportView(getJTable())
JPanel panel = new JPanel(new BorderLayout())
panel.add(jScrollPane, BorderLayout.CENTER)
return panel
}
private JTable getJTable() {
if (jTable == null) {
// 获得Titles类里的字段,一个字段在JTable中应该表现为一列
Field[] fields = Titles.class.getDeclaredFields()
// 将字段名保存为列名数组为DefaultTableModel所用
Object[] columnNames = new Object[fields.length]
for (int i = 0i <fields.lengthi++) {
columnNames[i] = fields[i].getName()
}
tableModel = new DefaultTableModel(columnNames, 0)
jTable = new JTable(tableModel)
}
return jTable
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
T thisClass = new T()
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
thisClass.setVisible(true)
}
})
}
public T() {
super()
setSize(580, 475)
getContentPane().add(getJPanel(), BorderLayout.SOUTH)
getContentPane().add(getJPanel1(), BorderLayout.CENTER)
}
}
不是很明白你的要求。具体的 *** 作是怎样的的呢?
假设数据库中有个学生表:
001 张三 20
002 李四 21
假设按姓名搜索,输入搜索条件“张”:
情况1、根据搜索条件直接搜索数据库记录(通常都是这样搜索),那从数据库搜索出的记录就只有姓名包含“张”的记录,然后JTable中也就只展示这些记录,就无所谓置顶不置顶啦。
情况2、只是根据搜索条件在当前JTable展示的数据中搜索,代码如下:
import java.awt.BorderLayoutimport java.awt.GridLayout
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.JButton
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JTable
import javax.swing.JTextField
import javax.swing.border.EmptyBorder
import javax.swing.event.TableModelEvent
import javax.swing.event.TableModelListener
public class JTableTest extends JFrame {
private JPanel searchPanel
private JTextField numField
private JButton searchByNumButton
private JTextField nameField
private JButton searchByNameButton
private JTable table
private TestTableModel tableModel
public JTableTest() {
super("Simple JTable Test")
setSize(400, 300)
setDefaultCloseOperation(DISPOSE_ON_CLOSE)
searchPanel = new JPanel()
searchPanel.setBorder(new EmptyBorder(3, 3, 3, 3))
searchPanel.setLayout(new GridLayout(2, 3, 2, 3))
searchPanel.add(new JLabel("学号"))
numField = new JTextField(20)
searchPanel.add(numField)
searchByNumButton = new JButton("按学号搜索")
searchByNumButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
table.getSelectionModel().clearSelection()
tableModel.doSearchByNum(numField.getText())
}
})
searchPanel.add(searchByNumButton)
searchPanel.add(new JLabel("姓名"))
nameField = new JTextField(20)
searchPanel.add(nameField)
searchByNameButton = new JButton("按姓名搜索")
searchByNameButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
table.getSelectionModel().clearSelection()
tableModel.doSearchByName(nameField.getText())
}
})
searchPanel.add(searchByNameButton)
getContentPane().add(searchPanel, BorderLayout.NORTH)
tableModel = new TestTableModel()
tableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if (tableModel.getHitRowCount() > 0) {
table.setRowSelectionInterval(0, tableModel.getHitRowCount() - 1)
}
}
})
table = new JTable(tableModel)
JScrollPane jsp = new JScrollPane(table)
getContentPane().add(jsp, BorderLayout.CENTER)
}
public static void main(String[] args) {
JTableTest self = new JTableTest()
self.setVisible(true)
}
} import java.util.ArrayList
import java.util.Arrays
import java.util.List
import javax.swing.table.AbstractTableModel
public class TestTableModel extends AbstractTableModel {
private List<Student> data = Arrays.asList(new Student("001", "王二", 20), new Student("002",
"王二小", 19), new Student("003", "张三", 20), new Student("004", "张三丰", 21), new Student("005",
"李四", 21), new Student("006", "李四光", 19))
private List<Integer> searchHitRows = new ArrayList<Integer>()
@Override
public int getRowCount() {
return data.size()
}
@Override
public int getColumnCount() {
return 3
}
@Override
public String getColumnName(int column) {
if (column == 0)
return "学号"
else if (column == 1)
return "姓名"
return "年龄"
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
Student student = data.get(rowIndex)
if (columnIndex == 0)
return student.getNum()
else if (columnIndex == 1)
return student.getName()
return student.getAge()
}
/** 按姓名搜索 */
public void doSearchByName(String key) {
searchHitRows.clear()
if (key == null || "".equals(key))
return
for (int i = 0 i < data.size() i++) {
Student studentI = data.get(i)
String value = studentI.getName()
if (value.indexOf(key) < 0)
continue
int j = 0
for (j = i - 1 j >= 0 j--) {
Student studentJ = data.get(j)
String valueJ = studentJ.getName()
if (valueJ.indexOf(key) >= 0)
break
}
Student temp = data.get(j + 1)
data.set(j + 1, studentI)
data.set(i, temp)
searchHitRows.add(Integer.valueOf(j + 1))
}
fireTableDataChanged()
}
/** 按学号搜索 */
public void doSearchByNum(String key) {
searchHitRows.clear()
if (key == null || "".equals(key))
return
for (int i = 0 i < data.size() i++) {
Student studentI = data.get(i)
String value = studentI.getNum()
if (value.indexOf(key) < 0)
continue
int j = 0
for (j = i - 1 j >= 0 j--) {
Student studentJ = data.get(j)
String valueJ = studentJ.getNum()
if (valueJ.indexOf(key) >= 0)
break
}
Student temp = data.get(j + 1)
data.set(j + 1, studentI)
data.set(i, temp)
searchHitRows.add(Integer.valueOf(j + 1))
}
fireTableDataChanged()
}
public void setData(List<Student> data) {
if (data == null)
throw new IllegalArgumentException("参数data不能为null。")
this.data = data
fireTableDataChanged()
}
public int getHitRowCount() {
return searchHitRows.size()
}
}
从数据库查询出记录后,转成Student对象列表调用TestTableModel的setData设置表格的数据。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)