> 健康
javagui表格(java中jtable的用法)
导语:如何解决java_GUI中Jtable表格重叠问题
直接使用JScrollPane套Jtable最容易出现的问题就是重叠问题,上图:
像这样,先是显示会员界面,然后点击切换图书界面后所出现的画面重叠,这种问题最好的解决方式就是套DefaultTableModel,让Jtable与DefaultTableModel处于全局状态,到时候直接更改横项与纵向数据就行。
这是有重叠问题的代码:
try {String[][] columnDate = new String[99][9];String[] lib = {, , , , , ,};Statement stmt = mysql.conn.createStatement();ResultSet rs = stmt.executeQuery();int col=0;while (rs.next()) {//rs一列一列循环输出 String bookid = rs.getString();String bookname = rs.getString();String bookleixing = rs.getString();String bookjianjie = rs.getString();String bookroot = rs.getString();String booka = rs.getString();String bookxy = rs.getString();columnDate[col][0] = bookid;columnDate[col][1] = bookname;columnDate[col][2] = bookleixing;columnDate[col][3] = bookjianjie;columnDate[col][4] = bookroot;columnDate[col][5] = booka;columnDate[col][6] = bookxy;col++;}JTable table= new JTable(columnDate, lib);table.getColumnModel().getColumn(0).setPreferredWidth(40);// 设置第二列宽度为120table.getColumnModel().getColumn(1).setPreferredWidth(120);JScrollPane scrollPane = new JScrollPane(table);panel.add(scrollPane);scrollPane.setBounds(10,70,765,500);DefaultTableCellRenderer r = new DefaultTableCellRenderer();r.setHorizontalAlignment(JLabel.CENTER);table.setDefaultRenderer(Object.class, r);}catch (SQLException e2){}
这里的解决方案如下:
在全局放置public JTable table = null;private DefaultTableModel tmModel = null;
tmModel = new DefaultTableModel();tmModel.setDataVector(columnDate, lib);//让表格数据写入DefaultTableModeltable= new JTable(tmModel);//JTable再调用DefaultTableModeltable.getColumnModel().getColumn(0).setPreferredWidth(40);// 设置第二列宽度为120table.getColumnModel().getColumn(1).setPreferredWidth(120);JScrollPane scrollPane = new JScrollPane(table);panel.add(scrollPane);scrollPane.setBounds(10,70,765,500);DefaultTableCellRenderer r = new DefaultTableCellRenderer();r.setHorizontalAlignment(JLabel.CENTER);table.setDefaultRenderer(Object.class, r);
这样之后再点击切换后执行如下代码就行了;
tmModel.setDataVector(columnDate, lib);使用这一段就直接可以更换表格中的数据。
点击切换后执行的代码:
try {String[][] columnDate = new String[99][9];String[] lib = {, , , , , };Statement stmt = mysql.conn.createStatement();ResultSet rs = stmt.executeQuery();int col=0;while (rs.next()) {//rs一列一列循环输出 String bookid = rs.getString();String bookname = rs.getString();String bookleixing = rs.getString();String bookjianjie = rs.getString();String bookroot = rs.getString();String booka = rs.getString();columnDate[col][0] = bookid;columnDate[col][1] = bookname;columnDate[col][2] = bookleixing;columnDate[col][3] = bookjianjie;columnDate[col][4] = bookroot;columnDate[col][5] = booka;col++;}tmModel.setDataVector(columnDate, lib);}catch (SQLException e1){}
教程结束
本文内容由小竹整理编辑!