I am trying to populate data in a JTable with a DefaultTableModel from a MySQL database using the addRow function but somehow it's not working. The data is not getting populated in the table model. I am sharing my code please help me with that,
inventoryTable = new JTable();
String showquery="select * from sample.inventory where parts='BSP'";
PreparedStatement showPst;
DefaultTableModel showTable=new DefaultTableModel();
inventoryTable.setModel(showTable);
try{
showPst=connect.prepareStatement(showquery);
//showPst.setString(2, "BSP");
ResultSet showrs=showPst.executeQuery();
ResultSetMetaData meta=(ResultSetMetaData) showrs.getMetaData();
String[] rowdata=new String[2];
while(showrs.next()){
rowdata[0]=showrs.getObject(2)+" "+showrs.getObject(3)+" "+showrs.getObject(5)+" "+showrs.getObject(8)+" "+showrs.getObject(7);
rowdata[1]=(String) showrs.getObject(15);
showTable.addRow(rowdata);
}
}catch(Exception e){
e.printStackTrace();
}
inventoryTable.setModel(showTable);
showTable.fireTableDataChanged();
inventoryTable.setBounds(62, 0, 489, 306);
panel.add(inventoryTable);
}
A table has rows and columns. A bit of simple debugging could have shown you that your table model lacks columns:
public static void main(String[] args) {
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addRow(new Object[]{"Test", "Test"});
System.out.println(tableModel.getRowCount());//returns 1
System.out.println(tableModel.getColumnCount());//returns 0
}
As long as the table has zero columns, no data will be displayed.
You can for example use the
public DefaultTableModel(Vector columnNames, int rowCount)
constructor to specify the column names.
Related
I have a JTable with 6 columns, the rows for the first 3 columns comes from table1(subject_records_bsit_first_year) and the last 3 will come from table2(evaluation_permission). The two database table have two joined columns(subject_code and subject_title). I'm trying to fill the last 3 columns of my JTable with data from table2—using the db table connection to display the right data.
My code:
public static void loadFirstYearSubjectList() {
ConnectionManager connectionManager = new ConnectionManager();
//String sqlChooseStudent = "SELECT * FROM student_bsit_"+studentID.toLowerCase() +" WHERE year_level = '"+yearLevel+"'";
try {
Connection con = connectionManager.createConnection();
Statement stmt = con.createStatement();
String sql = "SELECT * FROM `subject_records_bsit_first_year` ORDER BY `subject_records_bsit_first_year`.`trimester_period` ASC";
ResultSet rs = stmt.executeQuery(sql);
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("Subject Code");
tableModel.addColumn("Subject Title");
tableModel.addColumn("Trimester");
tableModel.addColumn("Section");
tableModel.addColumn("Professor");
tableModel.addColumn("Evaluation");
table.setModel(tableModel);
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(0).setPreferredWidth(95);
columnModel.getColumn(1).setPreferredWidth(266);
columnModel.getColumn(2).setPreferredWidth(90);
columnModel.getColumn(3).setPreferredWidth(77);
columnModel.getColumn(4).setPreferredWidth(179);
columnModel.getColumn(5).setPreferredWidth(78);
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setBackground(new Color(120, 120, 120, 10));
renderer.setOpaque(true);
columnModel.getColumn(0).setCellRenderer(renderer);
columnModel.getColumn(1).setCellRenderer(renderer);
columnModel.getColumn(2).setCellRenderer(renderer);
columnModel.getColumn(3).setCellRenderer(renderer);
columnModel.getColumn(4).setCellRenderer(renderer);
columnModel.getColumn(5).setCellRenderer(renderer);
while (rs.next()) {
String subjectCode = rs.getString("subject_code");
String subjectTitle = rs.getString("subject_title");
String trimesterPeriod = rs.getString("trimester_period");
tableModel.addRow(new Object[] {subjectCode, subjectTitle, trimesterPeriod});
}
} catch (Exception e) {
} finally {
try {
connectionManager.closeConnection();
} catch (Exception e2) {
}
}
}
table 2 data
I'm trying to display the section, subject_teacher and evaluation_permission from this table, this table is joined from another table that already displays the first 3 columns on my jtable. The two db table is joined with the same column names; subject_code and subject_title.
Create your own implementation of TableModel that is able to retrieve the data as you described above. Then use JTable's setModel() to make the JTable actually use your TableModel implementation.
An example how to use it is in the Java tutorials.
SELECT subject_records_bsit_first_year.subject_code,
subject_records_bsit_first_year.subject_title,
subject_records_bsit_first_year.trimester_period,
evaluation_permission.section, evaluation_permission.subject_teacher,
evaluation_permission.permission_status
FROM subject_records_bsit_first_year
INNER JOIN evaluation_permission
ON subject_records_bsit_first_year.subject_code = evaluation_permission.subject_code;
Got what I'm trying to do, thanks for the help! Sometimes people learn from example.
I am using JTable in swing to display a MySQL table, although the table values are present in the row object (as in the output in screenshot) but jtable in the application is empty.
The output in the screenshot shoes the Object[] array but when I pass this in the addRow method, it doesn't show anything on the JTable GUI.
private void tableSubmitButtonActionPerformed(java.awt.event.ActionEvent evt) {
//fetch the name of the database to be created
String dbName = tableDBName.getText();
//fetch the root password
String password = new String(tableDBPass.getPassword());
// fetch table name
String tableName = tableTableName.getText();
DefaultTableModel tableModel = (DefaultTableModel)tableViewTable.getModel();
int rowCount = tableModel.getRowCount();
for(int i = 0; i<rowCount; i++){
tableModel.removeRow(0);
}
try{
// create connection
CreateConnection newCon = new CreateConnection();
Statement newStat = newCon.initiate(dbName, password);
// result set contains the data fetched from the MySQL table
ResultSet rs = newStat.executeQuery("select * from "+tableName);
// get column names and column count
ResultSetMetaData metaData = rs.getMetaData();
int n_columns = metaData.getColumnCount();
ArrayList<String> columnNames = new ArrayList<>();
for(int i = 1; i<=n_columns; i++){
columnNames.add(metaData.getColumnName(i));
}
while(rs.next()){
ArrayList row = new ArrayList(n_columns);
for(int i = 1; i<=n_columns; i++){
row.add(rs.getObject(i));
}
Object[] obj = row.toArray();
tableModel.addRow(obj);
System.out.println("table updated..: "+Arrays.toString(obj));
}
}catch(SQLException e){
System.out.println(e.getMessage());
}
}
Besides this I deleted all the rows that are initially present when you insert the JTable in the form.
DefaultTableModel tableModel = (DefaultTableModel)tableViewTable.getModel();
So you start with an empty TableModel, which means the model has no columns or rows.
So even though you invoke the addRow() method, your model has no columns so there is nothing to display in the JTable
ArrayList<String> columnNames = new ArrayList<>();
for(int i = 1; i<=n_columns; i++){
columnNames.add(metaData.getColumnName(i));
}
The above code does nothing. All it does is add some data to an ArrayList, but that ArrayList is never used.
What you want to do is:
Use a Vector, not an ArrayList
Then you need to create an empty DefaultTableModel with just the columns names. Read the API for the appropriate constructor.
Then in your logic that iterates through the ResultSet you want to:
Again use a Vector for each row of data
add the data to the Vector
invoke the addRow(...) method of the model. The model will also accept a Vector so there is no need to convert it to an array
After all the data is added to the model you then need to:
Use tableModelView.setModel(...) to replace the model in your table.
Now your table model will have both columns and rows of data.
I am selecting records from the database and its showing some empty records in the JTable Along with the records I am not been able to filter records with table .
Here are some empty records which is in the image
public ArrayList<User> getUsers(){
ArrayList<User> usersList=new ArrayList<User>();
Connection connection=getConnection();
String query="SELECT * FROM info";
Statement myState;
ResultSet rs;
try{
myState=connection.createStatement();
rs=myState.executeQuery(query);
User user;
while(rs.next()){
user=new User(rs.getInt("id"),rs.getString("fname"),rs.getString("lname"),rs.getInt("age"));
usersList.add(user);
}
}
catch(Exception ep){
ep.printStackTrace();
}
return usersList;
}
I am populating these records in JTable with this function which is given below.
public void ShowUsersinJTable(){
ArrayList<User> uList=getUsers();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
Object[] row=new Object[4];
for(int i=0;i<uList.size();i++){
row[0]=uList.get(i).getId();
row[1]=uList.get(i).getFname();
row[2]=uList.get(i).getLname();
row[3]=uList.get(i).Age();
model.addRow(row);
}
}
as the code seems about right try changing your code to this:
ArrayList<User> uList=getUsers();
DefaultTableModel model=(DefaultTableModel)jTable1.getModel();
for(int i=0;i<uList.size();i++){
Object[] row=new Object[4];
row[0]=uList.get(i).getId();
row[1]=uList.get(i).getFname();
row[2]=uList.get(i).getLname();
row[3]=uList.get(i).Age();
model.addRow(row);
}
also you can delete all rows before filling the table (only needed if table was filled with data)
for (int i = table.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}
please tell me if it has worked, so i can help you further if needed
The default number of rows of the jTable in netbeans is four. So you can remove this by going to jTable properties -> model -> Rows.
Or, you can set rowCount to be zero before adding rows in the table like this:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
I try to put my ResultSet data into a JTable with help of DefaultTableModel class. As a solution I found a solution on Stackoverflow but modified it a bit (not really relevant here):
public static DefaultTableModel buildTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount;++column) {
columnNames.add(metaData.getColumnName(column));
}
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount;++columnIndex) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
} catch(SQLException e) {
e.printStackTrace();
return new DefaultTableModel(new Vector<>(), new Vector<>());
}
}
While I debugged this code I was able to see that:
ResultSet rs has data,
ColumnNames is populated,
RowCount is zero
and I think the issue is this line vector.add(rs.getObject(columnIndex));
It looks like my vector becomes empty because getObject() returns already no data.
Can someone help me with this or explains where the issue is? When I bind my generated DefaultTableModel to my JTable it is empty (no data is shown).
I recommend using the AbstractTableModel as a base. Some years ago, I found within the examples from Sun a class called JDBCAdapter.java. This class does, what you want. Search the web for this class and you will have something, that fulfills probably most of your needs. It might be a challenge, if your application should be able to write changes back to the DB, but just for displaying the table its fine.
I just found the issue short time ago: the problem was the fact that the cursor was set to last row because other methods iterated over the same ResultSet already and thus the cursor had to be set to first row again with first-method of ResultSet class.
I try to select certain row from jTable and perform a deletion then the jTable will be updated with the latest data in database. This is how I set up jTable :
private JTable getJTableManageReplies() {
jTableManageReplies.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jTableManageReplies.getSelectionModel().addListSelectionListener(
new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
if (!e.getValueIsAdjusting()) {
int viewRow = jTableManageReplies.getSelectedRow();
// Get the first column data of the selectedrow
int replyID = Integer.parseInt(jTableManageReplies.getValueAt(
viewRow, 0).toString());
eForumRepliesAdmin reply = new eForumRepliesAdmin(replyID);
replyID = JOptionPane.showConfirmDialog(null, "Are you sure that you want to delete the selected reply? " , "Delete replies", JOptionPane.YES_NO_OPTION);
if(replyID == JOptionPane.YES_OPTION){
reply.deleteReply();
SetUpJTableManageReplies();}
}
}
});
return jTableManageReplies;
}
public void SetUpJTableManageReplies() {
DefaultTableModel tableModel = (DefaultTableModel) jTableManageReplies
.getModel();
String[] data = new String[5];
db.setUp("IT Innovation Project");
String sql = "Select forumReplies.reply_ID,forumReplies.reply_topic,forumTopics.topic_title,forumReplies.reply_content,forumReplies.reply_by from forumReplies,forumTopics WHERE forumReplies.reply_topic = forumTopics.topic_id ";
ResultSet resultSet = null;
resultSet = db.readRequest(sql);
tableModel.getDataVector().removeAllElements();
try {
while (resultSet.next()) {
data[0] = resultSet.getString("reply_ID");
data[1] = resultSet.getString("reply_topic");
data[2] = resultSet.getString("topic_title");
data[3] = resultSet.getString("reply_content");
data[4] = resultSet.getString("reply_by");
// Add data to table model
tableModel.addRow(data);
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
}
And this is my codes to perform deletion from database :
public boolean deleteReply() {
boolean success = false;
DBController db = new DBController();
db.setUp("IT Innovation Project");
String sql = "DELETE FROM forumReplies where reply_ID = " + replyID
+ "";
if (db.updateRequest(sql) == 1)
success = true;
db.terminate();
return success;
}
However, there is an error message which is ArrayIndexOutOfBound right after I add the SetUpJTableManageReplies methos in the jDialog box. I try to do like when user select certain row, there will be a pop out to ask for confirmation of deletion. Then right after they click on yes, the jTable data will be refreshed. Can somebody give me some guides? Thanks in advance.
Your Problem is here:
tableModel.getDataVector().removeAllElements();
Better:
tableModel.setRowCount(0);
Much better: write your own table model and implement all methods which are defined in TableModel interface - so you can learn how to deal with the JTable component
Use TableModel to manage table data. DefaultTableModel will be useful, you should first create tableModel, then create JTable and set table's model to previously created table model.
You should perform insert/delete/update to table cells using model, which will update JTable automatically. Use DefaultTableModel to manage your data.