Can anyone please tell me how to add row on defaulttablemodel?i use resultset to retrieve data from database and rs.getString() to get them..and also i want this table update automatically as soon i pressed the button..
public void table(){
try{
rs = stat.executeQuery("SELECT * FROM payments;");
Vector<String> header = new Vector<String>();
header.add("PAYMENT");
header.add("AMOUNT");
header.add("MODIFIER");
header.add("DATE MODIFIED");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
dtm.addRow(row);
} // loop
dtm.setDataVector(data , header);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(0,0,490,250);
panel.add(scrollPane);
validate();
}catch(Exception e){
System.out.println("Error in table: "+e);
}//try and catch
}
You can use your data Vector to store all your results/rows and then dtm.setDataVector(data , header); after the loop.
Change your code
dtm.addRow(row);
to
data.add(row);
Basically, your code have to be
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row); // add each result/row to data Vector
} // loop
dtm.setDataVector(data , header); // load all the table rows to DefaultTableModel
Related
i have a jtable as shown in the pictures with 2 JDateChooser when i search and populate the table it loses the cell render is there a way to fix it ?
i have tried alot of things suggested but none worked
this is the action for the button for searching and seting the mode
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.sql.Date lowerdate = new java.sql.Date(dateChooser.getDate().getTime());
java.sql.Date upperdate = new java.sql.Date(dateChooser_1.getDate().getTime());
Connection con = DerbyConnection.dbConnector();
PreparedStatement pstmt = con.prepareStatement("select * from COMPANYCHEKS WHERE CHEKSDATEIN >= ? AND CHEKSDATEIN <= ?");
pstmt.setDate(1, lowerdate);
pstmt.setDate(2,upperdate);
ResultSet rs = pstmt.executeQuery();
table.setModel(Menu32.resultSetToTableModel(rs));
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
here is my model set to be called for populating the table with the result
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
columnNames.add("الرمز");
columnNames.add("العميل");
columnNames.add("البنك");
columnNames.add("تاريخ الشك");
columnNames.add("رقم الشك");
columnNames.add("القيمة");
columnNames.add("العملة");
columnNames.add("سعر الصرف");
columnNames.add("القيمة بالدولار");
columnNames.add("تاريخ الإيداع");
columnNames.add("بنك الإيداع");
columnNames.add("الحالة");
columnNames.add("ملاحظات");
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
here you can see what happens
Table before search:
table after populate:
when i search and populate the table it loses the cell render is there a way to fix it ?
By default, when you create set a new model to the table, a new TableColumnModel is created based on the new data in the TableModel and you lose the custom renderers.
Assuming the columns of the model are the same and only the rows of data changed you can prevent the TableColumnModel from be creating by invoking:
table.setAutoCreateColumnsFromModel( false );
after you have created the JTable with the original TableModel.
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();.
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
guys? help me with my problem. I want to have a one jtable that populates data using two table from database. i have two methods inside my class Apple..
Class Apple;
public void table(){
try{
String id = num.getText();
rs = stat.executeQuery("SELECT * FROM payments;");
Vector<String> header = new Vector<String>();
header.add("PAYMENT");
header.add("AMOUNT");
header.add("MODIFIER");
header.add("DATE MODIFIED");
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while(rs.next()) {
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // loop
dtm.setDataVector(data , header);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(0,0,490,250);
panel.add(scrollPane);
validate();
}catch(Exception e){
System.out.println("Error in table: "+e);
}//try and catch
}//tble
that's the first method inside class Apple, and rs = stat.executeQuery("SELECT * FROM payments;"); is the first database table i want to retrieve the data and insert inside my jtable.. after it insert inside my jtable i have another method that will retrieve data from another database table..
public void table(){
try{
String id = num.getText();
rs = stat.executeQuery("SELECT * FROM record where idNum ='"+id+"';");
while(rs.next()){
Vector<Object> row = new Vector<Object>();
row.add(rs.getString("description"));
row.add(rs.getString("amount"));
row.add(rs.getString("remarks"));
row.add(rs.getString("date"));
data.add(row);
} // while
dtm.setDataVector(data , header);
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(0,0,490,250);
panel.add(scrollPane);
validate();
}catch(Exception e){
System.out.println("Error in table: "+e);
}//try and catch
}//tble
this is the second methd inside the class apple.. i want its data to be added into my jtable and not deleting the previous data inserted inside the jtable..sorry for my poor english grammar..hope you understand what i mean..
Do join operation in single query between payments and record table and retrieve result on JTable.
I'm trying one sample program for practice and i want to display results of database in JTable. The problem is i have no idea how to do that. I know how to get data from database and display it on text field or console but never tried with JTable. How to do that ?
Consider that i've table which is holding information like person name, age, city and date. i want it to be displayed via JTable. Also is it possible to update the JTable display if i add the option of adding more details in program(i mean adding entries to db then that will show immediately in JTable )?
Any suggestions, pointers on how to proceed is appreciated. Thanks in advance.
JDBC + JTable # google:
Hacking Swing: A JDBC Table Model
Mastering the JTable
Making SQL Queries with JDBC and Displaying Results with Swing
here is the code
public static TableModel resultSetToTableModel(ResultSet rs) {
try {
ResultSetMetaData metaData = rs.getMetaData();
int numberOfColumns = metaData.getColumnCount();
Vector<String> columnNames = new Vector<String>();
// Get the column names
for (int column = 0; column < numberOfColumns; column++) {
columnNames.addElement(metaData.getColumnLabel(column + 1).toUpperCase());
}
// Get all rows.
Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> newRow = new Vector<Object>();
for (int i = 1; i <= numberOfColumns; i++) {
newRow.addElement(rs.getObject(i));
}
rows.addElement(newRow);
}
return new DefaultTableModel(rows, columnNames);
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
you can call this method such that way
void update_Table() throws ParseException
{
// we used this try catch so that values in table automatically show(without clicking on any button) when the dialog box open
try
{
Connection con=MSUTIL.getMSConnection();
PreparedStatement pst=con.prepareStatement("select payment_mode from PaymentMode");
ResultSet rs=pst.executeQuery();
//here i call that method
table.setModel(resultSetToTableModel(rs));
table.getTableHeader().setFont(new Font("SansSerif", Font.BOLD, 14));
while(rs.next())
{
mp.paymentmode_ComboBox.addItem(rs.getString("payment_mode"));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
finally
{
//this method is for closing the connection
MSUTIL.cleanUp(con, pst, rs);
}
}