Cant display rows in a JTable (Values from Database) - java

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

Related

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

JAVA update database on JTable cell change

He I am noob to Java (Thats not new) and I can't find a good tutorial for this. I use jTable to display a table filled with data from a MySQL database.
So far so good, I get the table:
Standard you can click a table cell and it changes to a text-field with can be filled with something new. You all know that, but how can I use this to also update the value in my database?
My code:
import [...];
public class table extends JPanel {
public String table;
private Database db;
public table(String tablename, Database db){
try {
table = tablename;
this.db = db;
//Get table with and height
ResultSet res = db.query("SELECT COUNT( * ) FROM `"+table+"`");
ResultSet res2 = db.query("SELECT COUNT( * ) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = '"+table+"'");
int rows = 0;
int collums = 0;
res.next();
res2.next();
rows = res.getInt(1);
collums = res2.getInt(1);
//Get table column names and set then in array
ResultSet clom = db.query("DESCRIBE `"+table+"`");
String[] columnNames = new String[collums];
int s = 0;
while(clom.next()){
columnNames[s] = clom.getString(1);
s++;
}
//get table data and put in array
Object[][] data = new Object[rows][collums];
ResultSet result = db.query("SELECT * FROM `"+table+"`");
int q = 0;
while(result.next()){
for(int a=0; a<= (collums - 1); a++){
data[q][a] = result.getString(a + 1);
//System.out.println(q + " - " + a);
}
q++;
}
//Make Jtable of the db result form the two array's
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
// do some event listening for cell change
JScrollPane scrollPane = new JScrollPane(table);
JFrame frame = new JFrame("table editor");
scrollPane.setOpaque(true);
frame.setContentPane(scrollPane);
frame.pack();
frame.setSize(600, 800);
frame.setVisible(true);
} catch (SQLException e1) {
e1.printStackTrace();
}
}
}
I guess I need to bind some kind of table listener and when something changes I take all the values of the table and update them with a query.
How can I do this?
This is my pseudo code:
table.bindCellEventListner(callback(t){
Array row = t.getAllValuesAsArrayOfRow();
String data = "";
int f = 0
while(row.next()){
data .= "`"+clom[f]+"` = '"+row[f]+"',"
f++;
}
data.delLastChar();
db.query("UPDATE `"+table+"` SET "+data+" WHERE `id` ="+row[0]+";");
});
A deleted answer plagiarised Rachel Swailes' answer from 14 years ago, found here. For completeness and because the answer is correct and useful, I have quoted the relevant text here:
Step 1: It's going to be way easier for the whole thing if you make your table extend a TableModel from now (if you haven't already). So if you need help with that just ask.
Step 2: In the table model you need to enable the cells to be editable. In the TableModel class that you make, you need to add these methods
public boolean isCellEditable(int row, int col) {
return true;
}
public void setValueAt(Object value, int row, int col) {
rowData[row][col] = value;
fireTableCellUpdated(row, col);
}
Step 3: You will see in the second method that we fire a method called fireTableCellUpdated. So here we can catch what the use it changing. You need to add a TableModelListener to your table to catch this.
mytable.getModel().addTableModelListener(yourClass);
And in the class that you decide will implement the TableModelListener you need this
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int column = e.getColumn();
TableModel model = (TableModel)e.getSource();
Object data = model.getValueAt(row, column);
...
}
now you have the data in the cell and the place in the grid where the
cell is so you can use the data as you want

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.

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