How to add multiple rows to JTable? - java

I'm trying to populate a JTable from a database, but the output is still empty. Here is my code :
private void buttonsearchActionPerformed(java.awt.event.ActionEvent evt)
{
conn = DatabaseConnection.dbConnection();
try {
String Sql="select idp,nomp,prix,stock from produit where codep='"
+ textsearch.getText() + "'";
pst = conn.prepareStatement(Sql);
ResultSet rs = pst.executeQuery();
DefaultTableModel model = new DefaultTableModel();
Object[] columns = {"Id Produit", "Nom Produit", "Quantité", "Prix", "Stock"};
model.setColumnIdentifiers(columns);
table.setModel(model);
Object[] row = new Object[5];
if (rs.next())
{
row[0] = rs.getInt("idp");
row[1] = rs.getString("nomp");
//row[2] = rs.getString("");
row[3] = rs.getString("prix");
row[4] = rs.getString("stock");
model.addRow(row);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
table "poduit" is :
| idp | codep | nomp | prix | stock |
"Quantité" in
Object[] columns = {"Id Produit", "Nom Produit", "Quantité", "Prix", "Stock"};
It meant to modify numbers of items to create a billing.
my issue is the 2nd row is pasted right on the 1st one
Thanks for help

According How to add row in JTable? and the Internet itself, all examples uses following line:
DefaultTableModel deFaultTableModel = (DefaultTableModel) myJTable.getModel();
so you have to replace the code line 'DefaultTableModel model = new DefaultTableModel();' by DefaultTableModel model = (DefaultTableModel) table.getModel();.

Related

Record is not loaded from the database on the JTable java netbeans

I am trying to display the records on JTable when the frame is loaded, but the records didn't display. This is what I've tried so far:
public void load()
{
try {
Connection con1;
PreparedStatement insert;
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost/javapos","root","");
insert = con1.prepareStatement("SELECT name,status FROM category");
ResultSet Rs = insert.executeQuery();
while(Rs.next()){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
String name = Rs.getString("name");
String status = Rs.getString("status");
model.addRow(new Object[]{name,status });
}
jTable1.setModel(model);
} catch (Exception e) {
System.out.println("Failed " + e);
}
}
My guess since your code should not compile but seems to (you are seing an empty JTable after all).
You have declare a DefaultTableModel model before the snippet.
How do I know that? With the code you proposed jTable1.setModel(model); can't compile because model doesn't exist in the scope (outside of the loop).
while(Rs.next()){
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
String name = Rs.getString("name");
String status = Rs.getString("status");
model.addRow(new Object[]{name,status });
}
jTable1.setModel(model);
Compile error :
"model" cannot be resolved to a variable.
I would guess you have declare it somewhere before. In the loop you declare a new one in a different scope, hiding the original one. In this last model instance, you insert your rows.
But after the loop, you set the first model that have no row in the jtable.
A basic example of what is happening, here I will rename both instance but in your code, model1 and model2 are named model.
model1 = new Model();
while(rs.next()){
model2 = new Model();
model2.addRow(...);
}
table.setModel(model1);
Quick correction, remove the declaration in the loop.
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
while(Rs.next()){
//DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
String name = Rs.getString("name");
String status = Rs.getString("status");
model.addRow(new Object[]{name,status });
}
jtable1.setModel(model);
Declare one TableModel
I would suggest you to make a separate two dimensional array and after retrieving data from Database save that data into that two dimensional array and after that you can assign that two dimensional array to the Jtable Model.
I can't reproduce exactly what you're trying to do, but I've tryed this:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.addRow(new Object[]{"name1","status1" });
model.addRow(new Object[]{"name2","status2" });
model.addRow(new Object[]{"name3","status3" });
and the three rows are indeed added at the end of the table. Are you sure you have any data in your database table? could an exception being thrown?
UPDATE
I suspect that you have not defined the columns in the model:
UPDATE 2: Reset model before adding rows
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int r = model.getRowCount();
while (r > 0) {
model.removeRow(--r);
}
ResultSet Rs = insert.executeQuery();
while(Rs.next()){
String name = Rs.getString("name");
String status = Rs.getString("status");
model.addRow(new Object[]{name,status });
}

JTable - Filter data

I'm trying to filter a JTable but the results are not as expected.
Below is the JTable with the added elements (I'm using MySQL to store the Data)
JTable with contents - Picture
When I try to filter the list for someone specific, I do not get the data from the table. For example, I search for "Ana" and nothing appears.
Search results for "Ana" - Picture
If I try to search using some "numbers", like the salary, I get the right result but the ID is not right. Pictures to clarify the issue below.
Wrong ID
Right ID
The Code to generate the ArrayList with the employees :
public static ArrayList<Angajat> listaAngajati() {
ArrayList<Angajat> listaAngajati = new ArrayList<>();
try (java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/angajati", "root", "***");) {
Statement st = conn.createStatement();
st.executeQuery("select * from angajati");
ResultSet rs = st.getResultSet();
Angajat angajat;
while (rs.next()) {
angajat = new Angajat(rs.getInt("id"), rs.getString("nume"), rs.getString("prenume"), rs.getInt("varsta"), rs.getString("adresa"), rs.getDouble("salariu"));
listaAngajati.add(angajat);
}
} catch (SQLException ex) {
System.out.println("Error in database connection: \n" + ex.getMessage());
}
return listaAngajati;
}
public static void arataAngajati() {
ArrayList<Angajat> arataAngajati = listaAngajati();
DefaultTableModel model = (DefaultTableModel) tabelangajati.getModel();
Object[] rand = new Object[6];
for (int i = 0; i < arataAngajati.size(); i++) {
rand[0] = arataAngajati.get(i).getID();
rand[1] = arataAngajati.get(i).getNume();
rand[2] = arataAngajati.get(i).getPrenume();
rand[3] = arataAngajati.get(i).getVarsta();
rand[4] = arataAngajati.get(i).getAdresa();
rand[5] = arataAngajati.get(i).getSalariu();
model.addRow(rand);
}
}
Code to filter the JTable
private void cautaInTabelKeyReleased(java.awt.event.KeyEvent evt) {
DefaultTableModel tabel = (DefaultTableModel) tabelangajati.getModel();
String query = cautaInTabel.getText().toLowerCase();
TableRowSorter<DefaultTableModel> sort = new TableRowSorter<DefaultTableModel>(tabel);
tabelangajati.setRowSorter(sort);
sort.setRowFilter(RowFilter.regexFilter(query));
}
Question : How can I modify the code so when I try to search for a an employee using his name to get the right result (not like now - no results) and when trying to modify the employee data, to get the right ID as shown in the JTable (example in the pictures above) ?
EDIT
In order to filter the data from the table accordingly I had to use
sort.setRowFilter(RowFilter.regexFilter("(?i)" + query));
When I was filtering the table, only the view modified and not the values from the row (Even if I saw the values from the row 3 and values on the backend where from the row 1). I managed to modify the following row and the table works perfectly.
From :
int row = tabelangajati.getSelectedRow();
To :
int row = tabelangajati.convertRowIndexToModel(tabelangajati.getSelectedRow());

How display in JTable the data from MySQL

I want to display the data from MySQL in JTable but showed the last row from the table and more nothing. Help me, please. I understand that I have a problem because jt = new JTable(data, columns) each time create a new table for each row (deleting previous) but I can't find the right option.
public class Test2 extends JPanel {
static final String USERNAME = "root";
static final String PASSWORD = "root";
static final String CONN_STRING = "jdbc:mysql://localhost:3306/mydbtest?useSSL=false";
JTable jt;
public Test2 () {
try {
Connection conn;
conn = DriverManager.getConnection(CONN_STRING, USERNAME, PASSWORD);
Statement stmt = (Statement) conn.createStatement();
String query = "Select title, season, episode from movie";
ResultSet rs = stmt.executeQuery(query);
rs.beforeFirst();
while (rs.next()) {
String title = rs.getString("Title");
String season = rs.getString("Season");
String episode = rs.getString("Episode");
String[] columns = {"Title", "S", "E"};
String[][] data = {{title, season, episode}};
jt = new JTable(data, columns);
};
jt.setPreferredScrollableViewportSize(new Dimension(450, 63));
jt.setFillsViewportHeight(true);
JScrollPane jps = new JScrollPane(jt);
add(jps);
}
catch (Exception er) {System.err.println(er);}
}
public static void main(String[] args) {
JFrame jf = new JFrame();
Test2 t = new Test2();
jf.setTitle("Test");
jf.setSize(500,500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}
Your problem is here:
while (rs.next()) {
String title = rs.getString("Title");
String season = rs.getString("Season");
String episode = rs.getString("Episode");
String[] columns = { "Title", "S", "E" };
String[][] data = { { title, season, episode } };
jt = new JTable(data, columns); // *** you're making many JTables here!! ***
}
Each time the while loop loops, you create and discard a new JTable object. The exception is on the last time through the loop, the data from the last row of the result set is not discarded and is then displayed in final JTable created. To solve this, to display all of the data within the JTable, you need to collate all of your result set data within the while loop, and then add it to the JTable, and the easiest way to do this is to create a table model, here a simple DefaultTableModel, before the while loop, and populate it within each row of result set data within the while loop:
// create a table model with the appropriate column headers
// and with 0 rows (to start with)
String[] columnNames = {"Title", "Season", "Episode"};
DefaultTableModel tableModel = new DefaultTableModel(columnNames, 0);
while (rs.next()) {
String title = rs.getString("Title");
String season = rs.getString("Season");
String episode = rs.getString("Episode");
// create a single array of one row's worth of data
String[] data = { title, season, episode } ;
// and add this row of data into the table model
tableModel.addRow(data);
}
jt.setModel(tableModel); // place model into JTable
Or perhaps better, change the last line to:
jt = new JTable(tableModel); // to create a new JTable
Try This... You Can Do it easily....
public final void EmployeeGridView(){
try{
Connection conn = DBConn.connect();
PreparedStatement ps = conn.prepareStatement("Select * from empdetails");
ResultSet rs=ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)jTable1.getModel();
tm.setRowCount(0);
while(rs.next()){
Object o[] = {rs.getInt("EMPID"),rs.getString("FirstName"),rs.getString("LastName"),rs.getString("Designation"),rs.getString("NIC"),rs.getString("PhoneNO"),rs.getString("DOB"),rs.getString("Address"),rs.getString("Gender")};
tm.addRow(o);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,"Error in Employee Grid View..... "+e);
}
}

Java UI - doesn't create and populate table

I am trying to pull data from a table in a mysql database and populate the results in a JTable. There are currently 3 tabs in the UI, the first two being input screens, which work fine. The 3rd tab, I am trying to run a query (after button is pushed) and display the results in a JTable. I am getting no error messages, but the screen does not display the table. Below is my code. Any assistance would be greatly appreciated. Note, user name and password have been replaced with generic. The query has also been simplified until I can get it to work. The system.out.print was just to check and see if it was pulling any data.
private void salePropertyActionPerformed(java.awt.event.ActionEvent evt) {
String sSelectQuery = "";
Statement statement=null;
Connection conn = null;
//PreparedStatement pStatement =null;
JPanel panel= spPanel;
TableColumn column;
JTable spTable = jTable1;
Vector columnNames = new Vector();
Vector data = new Vector();
spTable = new JTable(data,columnNames);
JScrollPane scrollPane = new JScrollPane(spTable);
panel.add(scrollPane);
try {
String myDriver = "com.mysql.jdbc.Driver";
String myURL = "jdbc:mysql://localhost:3306/realestate?autoReconnect=true&useSSL=false";
Class.forName(myDriver);
conn=DriverManager.getConnection(myURL,"root","jul1664bd");
/*Storing SQL statement*/
sSelectQuery ="SELECT propertyID, propertyPrice FROM property";
statement = conn.createStatement();
try (ResultSet rs = statement.executeQuery(sSelectQuery) //executes the query
) {
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
for(int i = 1; i<=columns; i++){
columnNames.addElement(metaData.getColumnName(i));
}
while (rs.next()){
Vector row = new Vector(columns);
for (int i=1; i<=columns; i++){
row.addElement(rs.getObject(i));
}
data.addElement(row);
System.out.println(data);
}
rs.close();
for (int i=0; i<spTable.getColumnCount(); i++){
column=spTable.getColumnModel().getColumn(i);
//column.setMaxWidth(250);
}
}
statement.close();
} catch (SQLException e) {
System.err.println("An exception ocurred");
System.err.println(e.getMessage());
} catch (ClassNotFoundException ex) {
Logger.getLogger(realEstateUI.class.getName()).log(Level.SEVERE, null, ex);
}
JOptionPane.showMessageDialog(this,"Query Complete");
}
/**
You are attempting to add the JTable after the UI is visible. For the addition to take affect you must call revalidate followed by repaint. As an alternative, add your JTable upon UI construction (before it is visible) and populate the model of the JTable in salePropertyActionPerformed

extra column automatically appended in jtable (how to remove it )

I am working on a java project
I am using jdk 1.6
I am want to add data from database in jtable
I have achieved this by using DefaulTableModel
and I got the column names by using ResultSetMetadata
but the problem is
**I am getting a extra column name A at the 0th index of jtable
I want to remove this column
it looks like this
A | deptno
I only need deptno
**
the code used for creating this model is
private void updateTable() throws Exception {
String sqlrow = "Select count(*) from emp";
rs= db.sta.executeQuery(sqlrow);
rs.next();
int rows=rs.getInt(1);
System.out.println(""+rows);
String sqldata = "SELECT deptno FROM emp";
rs =db.sta.executeQuery(sqldata);
rsMD = rs.getMetaData();
numberOfColumns = rsMD.getColumnCount();
ColumnNames = new String[numberOfColumns+1];
System.out.println(""+numberOfColumns);
for(int i=1;i<=numberOfColumns;i++)
{
String colName=rsMD.getColumnName(i);
ColumnNames[i] = colName;
System.out.println(""+ColumnNames[i]);
}
//Cj is a method which takes sqlQuery , rows, column
Object[][] rowData=CJ(sqldata,rows,numberOfColumns);
//jt is table name
jt.setModel(new DefaultTableModel(rowData,ColumnNames));
}
// code for cj()
public Object[][] CJ(String sql,int rows,int cols)
{
Object[][] obj=new Object[rows][cols+1];
ResultSet rs=null;
try{
rs= db.sta.executeQuery(sql);
int c=0;
while(rs.next())
{
for(int i=1;i<=cols;i++)
{
obj[c][i]=rs.getString(i);
}
c++;
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
return obj;
}
I am using this code on
button click
updateTable();
jsp = new JScrollPane(jt); // jt is Jtable
jp.add(jsp); //jp is jpanel
please help me out
Not following the naming convention makes it hard to read, but I would suggest to take a closer look at the following piece of code
numberOfColumns = rsMD.getColumnCount();
ColumnNames = new String[numberOfColumns+1];
System.out.println(""+numberOfColumns);
for(int i=1;i<=numberOfColumns;i++)
{
String colName=rsMD.getColumnName(i);
ColumnNames[i] = colName;
System.out.println(""+ColumnNames[i]);
}
Here you explicitly use more column names then numberOfColumns. Idem for your CJ method, where you start at index 1.
Just start all those for loops at index 0, make the arrays one shorter and everything should work

Categories

Resources