将组件添加到 JTable
Posted
技术标签:
【中文标题】将组件添加到 JTable【英文标题】:Adding component to JTable 【发布时间】:2013-04-23 08:06:35 【问题描述】:我想在表格中添加 JButton。我正在使用表格来显示数据库记录。实际上我想为表格中的每条记录添加按钮,但是该按钮未显示在表格上。它没有显示任何错误。请帮忙。提前致谢。
package addPanel;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class panelShowData extends JPanel
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String url = "jdbc:mysql://localhost:3306/records";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
JScrollPane scrollPane;
JTable table;
DefaultTableModel tableModel;
String nameSearch="";
public panelShowData()
this.setLayout(null);
setVisible(true);
setBounds(0, 200, 500, 450);
public void searchData( String nameSearch)
tableModel = new DefaultTableModel();
try
Class.forName( driver ).newInstance( );
connection = DriverManager.getConnection( url, userName, password );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE );
resultSet = statement.executeQuery( "select * from registration where firstname='"
+ nameSearch
+ "'or lastname ='"
+ nameSearch + "'" );
System.out.println( "Query executed" );
System.out.println( "nameSearch="+nameSearch );
String firstName;
String lastName;
int id;
JButton add=new JButton("ADD");
while ( resultSet.next( ) )
System.out.print( resultSet.getString( 2 ) + "\t" );
System.out.print( resultSet.getString( 4 ) + "\n" );
firstName = resultSet.getString( 2 );
lastName = resultSet.getString( 4 );
id = resultSet.getInt(1);
String[ ] columnName = "Id","First Name", "Last Name","click" ;
Object[ ] data = id, ""+firstName, "" + lastName, add ;
System.out.println("Names is:"+firstName);
tableModel.setColumnIdentifiers( columnName );
tableModel.addRow( data );
tableModel.fireTableDataChanged();
table = new JTable( tableModel );
table.setEnabled(false);
scrollPane = new JScrollPane( table );
scrollPane.setBounds( 10, 10, 350, 100 );
scrollPane.revalidate();
scrollPane.repaint();
add( scrollPane );
connection.close( );
catch (Exception e)
e.printStackTrace();
JOptionPane.showMessageDialog( null, "Record Not Found",
"Sorry", JOptionPane.ERROR_MESSAGE );
【问题讨论】:
【参考方案1】:-
您帖子中的所有代码行都是重要原因,为什么 ResultSetTableModel、TableFromDatabase(和/或从 SwingWorker、Runnable#Thread 调用的 JDBC)存在
永远不要调用 tableModel.fireTableDataChanged();,
在 XxxTableModel 定义之外
DefaultTableModel 已正确实现此通知程序
您的代码需要覆盖此通知程序,因为谈到 Swing 中的并发性 (Oracle tutorial),再次谈到我的第 1 点。
所有重要的东西都在那里,请到read this answer about ListModel and JList,所有点,同样的问题,
JPanel 在 API 中实现了 FlowLayout,没有理由使用 NullLayout,将其改为 BorderLayout
覆盖 getPreferredSize 以获得 JPanel 的合理尺寸,包含包装在 JScrollPane 中的 JTable
JButton added in JTable is here solved a few times
【讨论】:
以上是关于将组件添加到 JTable的主要内容,如果未能解决你的问题,请参考以下文章