add column to jtable dynamically on netbeans - java

my code is this :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel)pl.getModel();
String urlBaseDonnes="jdbc:mysql://localhost:3306/test";
Connection con;
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException ex){
System.out.println(ex);
}
try{
con =DriverManager.getConnection(urlBaseDonnes,"root","");
try (Statement stmt = con.createStatement()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM news");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
System.out.println("resultSet MetaData column Count=" + numberOfColumns);
int j=0;
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
// get the name of the column, and changing it
for (int i = 1 ; i <= numberOfColumns; i++) {
ChangeName(pl,j,rsMetaData.getColumnName(i));
System.out.println(rsMetaData.getColumnName(i));
System.out.println(j);
j= j+1;
}
String query="SELECT * FROM news";
rs=stmt.executeQuery(query);
//Show the database
while(rs.next()){
String id=rs.getString("id");
String titre=rs.getString("titre");
String contenu=rs.getString("contenu");
model.addRow(new Object[]{id,titre,contenu});
}
rs.close();
}
con.close();
System.out.println("close the database");
}catch(SQLException ex){
System.out.println(ex);
}
}
My goal is to change the name of the columns dynamically when i change the name of my table, this code can change the name of the column but when it's come to showing the content of the database it doesn't work, also i can't add column, for exemple if i choose a table that have 4 column, i'll have an error. I tried to add column using a DefaultTableModel but it didn't work.
could you please help me with the part of adding column dynamically ? and tell me why this code doesn't show what's on the database ?
Thanks

that the data that are in my database are not shown. this code only changes the name of the column.
First you access the TableModel of the table:
DefaultTableModel model=(DefaultTableModel)pl.getModel();
Then you change the TableModel of the table:
pl.setModel(new javax.swing.table.DefaultTableModel(new Object [][] {},new String [] {"ddd","fgg","nl"}));
Then you add the data from the database to the "old" model:
model.addRow(new Object[]{id,titre,contenu});
So the data is NOT added to the current model.
If you want to create a new model then your code should be something like:
DefaultTableModel model = DefaultTableModel(Object[] columnNames, int rowCount);
pl.setModel( model );
Then your code will add the database data to the real model.
The question is why are you trying to hardcode the column name? When you do a select * from the database you don't know how many columns of data will be returned. You should be using more generic code. See the TableFromDatabaseExample.java code from Table From Database.

Related

Getting Multiple Data using Text field + Jbutton from SQL Server to Jtable

Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.

How to set values to jtable?

I have two tables in my database(using mysql workbench), but I can't set the data in that tables at the same time to jtable. How can I fix this issue ?
(Get the values from two tables or related fields and set those into jtable)
I mean two resultsets?
Why do you have two ReultSets? You have two options:
Change your SQL query to get the data into a single ResultSet
Don't use DBUtils to create the TableModel
In this case you need to load the data from the ResultSet manually one row at a time.
For the first ResultSet you need to create the columns for the table and then add rows of data. The basic logic would be:
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
// Read data from a table
String sql = "Select * from ???";
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql );
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++)
{
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
connection.close();
}
catch(Exception e)
{
System.out.println( e );
}
For the second ResultSet you just add the data to the Vector.
Then you create the DefaultTableModel using the two Vectors and you create the JTable using the TableModel.

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

SQL data and 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);
}
}

Categories

Resources