我在表格上工作。在这种形式中,我使用Name从DataBase获取记录。我从文本字段收集数据,该文本字段在其他类(即框架)中定义。我将此字符串传递给searchData函数以从数据库中获取它。但是当我运行程序时,它为columnNames []提供了一个为JTable定义的字符串数组的NullPoingerException。 类panelShowData:
的代码如下 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)
{
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 counter = 0;
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 };
tableModel.setColumnIdentifiers( columnName );
tableModel.addRow( data );
tableModel.fireTableDataChanged();
counter++;
}
table = new JTable( tableModel );
table.setEnabled(false);
scrollPane = new JScrollPane( table );
scrollPane.setBounds( 10, 10, 350, 100 );
scrollPane.revalidate();
add( scrollPane );
connection.close( );
}
catch (Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog( null, "Record Not Found",
"Sorry", JOptionPane.ERROR_MESSAGE );
}
}
}
callin方法是:
if ( ae.getSource( ) == buttonSearch )
{
addform.setEnabled( false );
addform.setVisible( false );
remove( addform );
showData.revalidate( );
showData.repaint( );
add( showData );
String stringNameSearch="";
stringNameSearch = nameSearch.getText( );
System.out.println( "Name is"+stringNameSearch );
showData.searchData( stringNameSearch );
}
答案 0 :(得分:0)
您没有初始化字段tableModel
。这样一行
tableModel.setColumnIdentifiers( columnName );
触发NullPointerException
。