SQL data and JTable - java

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);
}
}

Related

Is there away to fix the JTable same is before search?

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.

How can I populate my JTable with my embedded database?

I am having trouble showing my database filled JTable within my GUI application.
My code below runs through and creates a GUI with a panel, I then create my JTable and add it onto my application. I then run through a method that supposedly populates the table. After the populating has finished, nothing shows.
Dissecting my code, I'm led to believe somewhere is causing the data not to parse into my table, for some unknown reason, which is why I have come here.
At the click of a button, this code entails:
JTable tigerTable = new JTable();
JPanel centerPanel = new JPanel();
centerPanel.add(tigerTable, new GridBagConstraints());
FillTable(tigerTable, "SELECT * FROM TIGER_INFO");
The FillTable method as follows:
//Add buildTableModel method
public void FillTable(JTable table, String Query)
{
try
{
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:derby:STOCK_CONTROL");
Statement stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stat.executeQuery(Query);
System.out.println("Connected");
//Remove previously added rows
while (table.getRowCount() > 0)
{
((DefaultTableModel) table.getModel()).removeRow(0);
}
int columns = rs.getMetaData().getColumnCount();
while (rs.next())
{
Object[] row = new Object[columns];
for (int i = 1; i <= columns; i++)
{
row[i - 1] = rs.getObject(i);
}
((DefaultTableModel) table.getModel()).insertRow(rs.getRow() - 1, row);
}
rs.close();
stat.close();
conn.close();
}
catch (InstantiationException |
IllegalAccessException |
ClassNotFoundException |
SQLException e)
{
System.out.println(e);
e.printStackTrace();
}
}
Doing so creates the application, but does not show any table with data. My database contains 3 columns and 3 rows, but I do not see my data displayed inside a JTable.
My question is, how can I populate my JTable with my database and display it correctly on my GUI application?
If you need anything else, please let me know and I will provide as much as I can.
Thank you in advance.
I think you mix the operation, i suggest to use this instruction :
Create a Bean, or Entity to store the information of your Object
Get the List of your data,
Display your data in your JTable,
So you can use this to display your data in your JTable :
....
List<TIGER_INFO> list = new ArrayList<>();//create a List of data
while (rs.next()){
//fill data in your List
list.add(new TIGER_INFO(rs.getTYPExxx("att1"), rs.getTYPExxx("att2"), rs.getTYPExxx("att3"));
}
//when you finish call your function which display your data :
fillData(list);
....
Fill date method can look like this :
private void fillData(List<TIGER_INFO> list) {
DefaultTableModel model = (DefaultTableModel) jTableName.getModel();
while (model.getRowCount() > 0) {
for (int i = 0; i < model.getRowCount(); i++) {
model.removeRow(i);
}
}
for (TIGER_INFO obj : list) {
model.addRow(new Object[]{
obj.getAttribute1(),
obj.getAttribute2,
obj.getAttribute3
});
}
}
I recommend to write a class extending AbstractTableModel. Add a function to this class filling the content based on a SQL-Statement. Then it will look something like:
TigerTableModel tigerModel = new TigerTableModel(dbConnection);
tigerModel.executeQuery("select * FROM TIGER_INFO");
JTable tigerTable = new JTable(tigerModel);
or you create a generic TableModel that is able to run every SQL-statement, so you are very flexible in your project.
I have found the solution - I've been trying to wrap my head around the problem for way too long, and I finally fixed it.
Try setting the table model manually first.
JTable tigerTable = new JTable();
tigerTable.setModel(new DefaultTableModel(0, numberOfColumns));
When you don't specify a model, the JTable creates an anonymous inner class and generally doesn't behave how you want it to.

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

Cant display rows in a JTable (Values from Database)

Hello dear programmers,
it's my first post and i hope i'm able to describe which kind of problem i have.
I'm German, thats why my classnames are in german. I tried to put in some helpfull comments.
I'm trying to put the values of a database (called "buchungen") into a JTable inside a JPanel.
My JTable shows up but only the headers and no rows..
Here is my class with the JTable inside:
public class Verlauf extends SQL{
JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
Verlauf(){
removeAll();
try {
rs = stmt.executeQuery("SELECT * FROM buchungen WHERE Ausführer = '" + kontoNr + "'"); // kontoNr equals to Ausführer in the database
} catch (Exception e) {
e.printStackTrace();
}
displayData(rs);
repaint();
}
public void displayData(ResultSet rs)
{
int i;
int count;
String a[];
String header[] = {"BuchungsNr","Ausführer","Betrag","Aktion","Empfänger"}; //Table Header Values, change, as your wish
count = header.length;
//First set the Table header
for(i = 0; i < count; i++)
{
model.addColumn(header[i]);
}
table.setModel(model); //Represents table Model
add(table.getTableHeader(),BorderLayout.NORTH);
a = new String[count];
// Adding Database table Data in the JTable
try
{
while (rs.next())
{
for(i = 0; i < count; i++)
{
a[i] = rs.getString(i+1);
}
model.addRow(a); //Adding the row in table model
table.setModel(model); // set the model in jtable
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, "Exception : "+e, "Error", JOptionPane.ERROR_MESSAGE);
}
}
I got the method for the jtable from a other post which i cant find anymore...
I hope someone can help me :)
Edit: The connection to my database is made in another class (called SQL) which works fine because i can use it from other classes perfectly in the same way i did here.
Greetings Lukas Warsitz
While the JTable header has been added to the container, the table itself has not
add(table);

JTable doesn't show the newly inserted row/data

I have a JTable and I populte the table as follows:
jTable_Std_info.setModel(DBControler.getALLStudents());
And the following is a static method in a class named DBControler which retrieves all the data from the database(Oracle).
public static DefaultTableModel getALLStudents() throws SQLException, Exception {
DefaultTableModel tableModel = new DefaultTableModel();
Vector rows = new Vector();
Vector columns = new Vector();
try {
conn = geConnection();
cst = conn.prepareCall("{? = call std_getInfoFunc}");
cst.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
cst.execute();
res = (ResultSet) cst.getObject(1);
System.out.print(res);
ResultSetMetaData rsm = res.getMetaData();
for (int i = 1; i <= rsm.getColumnCount(); i++) {
columns.addElement(rsm.getColumnName(i));
}
int row = 0;
while (res.next()) {
Vector vRow = new Vector(); //to store the current row
//System.out.println("Row " +row+"\n");
for (int i = 1; i <= rsm.getColumnCount(); i++) {
String columnValue = res.getString(i);
vRow.addElement(columnValue);
}
row += 1;
rows.addElement(vRow);
}
tableModel.setDataVector(rows, columns);
} catch (SQLException e) {
e.printStackTrace();
} finally {
res.close();
conn.close();
}
return tableModel;
}
So far everything works fine, but the problem is that if I insert a new record in the database, the JTable doesn't get the newly inserted row/data. Why is that and how can I fix this problem?
UPDATE:
It's retrieving the data when I commit my new insertion. So do I have to commit each time I update? Or is there any other ways to do this?
I think that you looking for Oracle Built-In Database Change Notification, not sure if is accesible for Oracle's in free-versions, if not then never mind, for MySQL is there two or three similair API for Java JDBC
But the problem is that if I insert a new record in the database, the JTable doesn't get the newly inserted row/data. Why is that?
The TableModel doesn't know when the database is updated.
and how can I fix this problem?
If your application is adding the row to the database then it also needs to add a row to the TableModel at the same time.

Categories

Resources