how to show data in jTable in JAVA it append old value - java

I am using jTable in netbeans. After selection of combobox if i select employee id 1 it show all data of emp 1 in jTable. But next time when i choose emmployee id 2 jTable shows single value of emp id 1's and all another values of empid 2.
My code is given below
Connect c = new Connect();//connection to database
con = (Connection) c.getConnection();
st = (Statement)con.createStatement();
String ddate = (String)text.getSelectedItem();
System.out.println("id " +ddate);
rs = st.executeQuery("select e.employee_id,e.`first_name`, i.outtime, i.outtime_date from tbl_employee e,tbl_outtime i where e.employee_id=i.outtime_emp_id and i.`outtime_date` LIKE '%/"+month2+"/"+year1+"'and outtime_emp_id="+ddate);
while(rs.next())
{
String dat1=rs.getString("outtime_date");
String e1=rs.getString("employee_id");
System.out.println(e1);
st33=(Statement) con.createStatement();
rs33=st33.executeQuery("select i.intime, i.intime_date from tbl_employee e,tbl_intime
i where e.employee_id=i.intime_emp_id and i.`intime_date`='"+dat1+"' and
i.intime_emp_id="+e1);
if(rs33.next())
{
int emp=rs.getInt("employee_id");
System.out.println(emp);
String name=rs.getString("first_name");
String dept=rs33.getString("intime");
String desig=rs.getString("outtime");
String join=rs33.getString("intime_date");
jTable1.setValueAt(emp, cnt, 0);
jTable1.setValueAt(name, cnt, 1);
jTable1.setValueAt(dept, cnt, 2);
jTable1.setValueAt(desig, cnt, 3);
jTable1.setValueAt(join, cnt, 4);
cnt=cnt+1;
}
}
Tell me solution if anyone knows.

read tutorial about JTable
all data for JTables view are stored into XxxTableModel
have to clear XxxTableModel, and add new row(s) from JDBC to the XxxTableModel

Use TableModel for adding row.
Read
http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
for samples.

Like all other Swing components, a table consists of two parts: a view part (the JTable) and a model part (the TableModel). The view is updated when the model indicates it has been changed by throwing events. See the table tutorial for more information.
So for your use-case, you can either adjust the existing TableModel or create a new one. I would personally opt to create a new one since you are working with a database.
Note that Swing components should only be accessed and modified on the Event Dispatch Thread, and that long running tasks (as querying a database) should not happen on this thread (see the Swing concurrency tutorial). That is why I would recommend to create a new TableModel. You can create this model on the worker thread you use for querying the database, and the replace the model in one go on the Event Dispatch Thread. The SwingWorker class is most suited for this.

Related

Multiple entries in a JTable from a Database

This is my first question here and I hope I am not repeating someone else's question. I will try and explain the problem as much as I can in the next few lines. Pardon my English if its really bad .
So I have here a JTable in which I would like to retrieve values from a database. So far I can add 1 value and I know why this is. The question is . How do I add multiple values to this table ?
This is the method I use in my operations to find a gun in a specific shop with its quantity
public ResultSet gunSearch(String id, int qty, int storeId) {
try {
String s = "SELECT gunID, gunName AS \"Gun Name\", gunPrice AS \"Price\", SellCost AS \"Cost\", availableQty AS \"Amount Available\", "+qty+" AS \"Quantity\" FROM Guns WHERE gunId = '" + id + "'AND storeId='"+storeId+"'";
pstmt = conn.prepareStatement(s);
rset = pstmt.executeQuery(s);
} catch (Exception ex) {
System.out.println("Error here at searchByProdId Operation "+ex);
}
return rset;
}
For my GUI I use the following code to display the information entered by the user
public void actionPerformed(ActionEvent e){
if(e.getSource().equals(enterBtn)){
String gunID = gunIdText.getText();
int qty = Integer.parseInt(quantityText.getText());
table.setModel(DbUtils.resultSetToTableModel(op.gunSearch(gunID, qty, storeId)));
Whenever I click the Enter button the column of data is retrieved from the database. However if I re-enter another gunId and quantity , the previous column disappears and the new column of data is retrieved from the database.
How could I possibly , enter couple of different gunId's and quantitie's into the JTable ?
Your gunSearch method only returns one result. You then completely recreate the TableModel from this one result, erasing whatever you had in the old model.
You'll need to concoct a new method that can take a Collection<String> (a collection of gun ids) and return a row for each id provided.
Alternatively, you can create a method that adds a gun to an existing TableModel rather than recreating the whole model from scratch every time. It depends on how you want the application to work, which option is better.

JTable is not appending data from database

I have a project set up with with an embedded derby jdbc and a jtable, however when I try to append data from my database to my jtable through resultset and adding the results from the resultset to a string[] and adding it to my tablemodel the result display is blank.
This is my database resultset:
ResultSet res = statement.executeQuery("SELECT * FROM VAULT");
while (res.next()) {
String [] row = {res.getString("Expenses"), res.getString("ExpensesType"), res.getString("PaymentType"), res.getString("Amount"), res.getString("Date")};
System.out.print(res.getString("Expenses"));
System.out.print(res.getString("ExpensesType"));
System.out.print(res.getString("PaymentType"));
System.out.print(res.getString("Amount"));
System.out.print(res.getString("Date"));
GUI.tableModel.addRow(row);
GUI.tableModel.fireTableDataChanged();
}
res.close();
This is my table code:
table = new JTable(tableModel);
table.setBackground(Color.GRAY);
table.setFillsViewportHeight(true);
JTableHeader header = table.getTableHeader();
header.setBackground(Color.DARK_GRAY);
header.setForeground(Color.LIGHT_GRAY);
scrollPane.setViewportView(table);
tableModel.addColumn("Expenses");
tableModel.addColumn("Expense Type");
tableModel.addColumn("Payment Type");
tableModel.addColumn("Amount");
tableModel.addColumn("Date");
Since the code, basically, works, I have to assume the problem is with some other part of the application which I cannot replicate, like the database management for example...
However...
Your resource management is non-existent...A database Statement has context and has a direct relationship to the query that made it, once you have completed working with it you should make sure you close it, for example...
public static Connection createDatabaseConnection() throws SQLException, ClassNotFoundException {
//...
System.out.println("Database Connected...");
try (Statement statement = c.createStatement()) {
count = statement.executeUpdate("CREATE TABLE VAULT (Expenses VARCHAR(5000), ExpensesType VARCHAR(5000), PaymentType VARCHAR(5000), Amount VARCHAR(10), Date VARCHAR(5000))");
System.out.println("Table Created...");
}
try (Statement statement = c.createStatement()) {
ResultSet res = statement.executeQuery("SELECT * FROM VAULT");
while (res.next()) {
String[] row = {res.getString("Expenses"), res.getString("ExpensesType"), res.getString("PaymentType"), res.getString("Amount"), res.getString("Date")};
System.out.print(res.getString("Expenses"));
System.out.print(res.getString("ExpensesType"));
System.out.print(res.getString("PaymentType"));
System.out.print(res.getString("Amount"));
System.out.print(res.getString("Date"));
GUI.tableModel.addRow(row);
}
}
and...
String updateStatement = "INSERT INTO VAULT"
+ " (Expenses, ExpensesType, PaymentType, Amount, Date)"
+ " VALUES (\'" + expenses + "\',\'" + expensesType + "\',\'" + paymentType + "\',\'" + amount + "\',\'" + date + "\')";
try (Statement statement = c.createStatement()) {
System.out.print(updateStatement);
int c = statement.executeUpdate(updateStatement);
count = count + c;
System.out.println("Data Inserted in to Database...");
} catch (Exception ex) {
ex.printStackTrace();
}
This will ensure that once you leave the try section, the resource will automatically be closed.
You should also consider making use of PreparedStatements, see Using Prepared Statements for more details.
In your actionPerformed method, this...
table.setModel(tableModel);
is worrying. The model has already been set when you setup the UI, you shouldn't need to set it again unless you've create a new model or table, which you've done neither of...
And...
tableModel.fireTableDataChanged();
table.updateUI();
Should never be done. You should never call any of the notification methods of a model externally, these should all be taken care of by the model it self (and in the case of the DefaultTableModel are).
updateUI has nothing to do with "updating the state of the UI" and has is probably the most efficient method you could use. The simple fact that you've fireTableDataChanged should have already triggered an update (although fireTableDataChanged is also one of the most efficient methods you could use as well).
Simply call tableModel.addRow and let the model and table do the rest.
Your work flow is a little off. You shouldn't add the row to the table until AFTER you've made sure it's been added to the database, what happens if the insert fails for some reason?
You really, really, REALLY should learn to make use of dialogs, see How to Make Dialogs for more details, instead of throwing, yet, another frame at the user...
static is not your friend, sure it might "seem" to make life easier and "it's just a quick {what ever}", but bad is bad any of the time...
You should never make UI components static it is way to easy to lose context and not know if you're updating what's actually on the screen or not.
"But how does class X reference component Y?" - in most cases, it shouldn't. I should either return a value/values that container class can deal with or should communicate through the use of some kind of model or observer pattern...
If you're going to strip away the window frame, you had better implement functionality that allows me to drag it and, because it's a personal grip of mine, resize it, otherwise your users will not like you
Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify
See Why is it frowned upon to use a null layout in Swing? and Laying Out Components Within a Container for more details...

Need to make a JTable with 1000 rows

I am working on a GUI application in Java for a client. One of the parts of that GUI needs to upload about a 1000 records each having 17 attributes simultaneously(i.e. it needs a 1000 X 17 table). Now Netbeans IDE 7.2.1 allows at most 100 rows at a time in a Jtable. Any suggestions how can i make one for displaying 1000 entries at a time. I considered having 10 tables one after other but that will leave a very messy coding to be done later at the back end!
Don't use an IDE to create your GUI. The IDE generates terrible code that creates a table with the null values for the number of rows that you want to create.
There is no restriction on the number of rows a table can hold. If you create the code manually you can do something simple like:
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
which will create an empty table with the column names that you specify
Then you can add rows individually using the DefaultTableModel.addRow(...) method.
Or you can add all the rows at one time by using the DefaultTableModel.setDataVector(...) method.
You can create your GUI with any IDE you like. There is no problem with Netbeans in this area. Netbeans, like any other editing tool, allows you perfectly well to create some class like i.e. MyModel that extends an AbstractTableModel, which has no GUI and you should use in order to separate your Model from the View and Controller that have a GUI.
Your JTable will then automatically call getValueAt(row, col) and getRowCount() in order to show the tiny subset of your 1.000 or maybe 1.000.000 lines that need to be displayed.
You must not necessarily load all 1000 records to any Vector or ArrayList. Just make getValueAt(row, col) read each row and return every column.
There is a high probability that your user will not scroll down every time and will not ask the TableModel to provide anything more than the 40-60 lines that should be visible after the first rendering.
This example shows the getValueAt, used on a scrollable ResultSet sr from a database:
#Override
public Object getValueAt(int row, int column) {
try {
sr.absolute(row + 1); // position your ResultSet.
switch (column) {
case 0:
return sr.getInt("...");
case 1:
return sr.getString("...");
case 2:
return sr.getString("...");
case 3:
return ......
default:
return ("-");
}
} catch (SQLException sex) {
........
}
}
This is what happens at the GUI side:
Is the JTable. Since you use a TableModel it will show you the JTable only at runtime.
Here is the place that allows you to bind your model to the auto-generated code of NetBeans.
This is the instance of your model. You could also write something like "new MyModel()" here.
The generated code is no monster either:
...
jTable1.setModel(etb);
jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
myMouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
...

adding check box in the jTable [duplicate]

This question already has an answer here:
How to add checkboxes to JTABLE swing [closed]
(1 answer)
Closed 8 years ago.
i am using swings for creating the desktop application . i have created the functionality which provided the data from the database and insert that into the Jtable .now i want to use provide the additional facility that include the additional column with the check box and the a button to delete that perticuler column (which is checked ) when the button is clicked .i have used the netbeans and it provide the maximum drag and drop option. i am not able to figure it out that the how and where to insert the instance of the checkbox in the current code for inserting the checkbox for the each and every row .
For providing the checkbox with the each row do have to generate the multiple instance of the check box
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
java.sql.Connection con = new DBConnection().getConnection();
PreparedStatement pst;
String Q;
Q = "select * from userregister ";
try {
pst = con.prepareStatement(Q);
ResultSet rs = null;
rs = pst.executeQuery();
String a, b, c, d;
int x = 0;
// DefaultTableModel dt = new DefaultTableModel(data, columnNames);
JCheckBox c1 = new JCheckBox();
for (int i = 0; rs.next(); i++) {
a = rs.getString(1);
b = rs.getString(2);
c = rs.getString(3);
d = rs.getString(4);
jTable2.setValueAt(a, i, 0);
jTable2.setValueAt(b, i, 1);
jTable2.setValueAt(c, i, 2);
jTable2.setValueAt(d, i, 3);
jTable2.setValueAt(, i,4);
}
//jTable1.setAutoscrolls(rootPaneCheckingEnabled);
// TODO add your handling code here:
} catch (SQLException ex) {
Logger.getLogger(NewJFrame1.class.getName()).log(Level.SEVERE, null, ex);
}
}
this is the methods that insert the data into the table . also i want to know that how do i be able to find out that which check box is checked and how to use the variable to respond the request of the multiple deletes . plz help
You have to take a look to Concepts: Editors and Renderers section of How to Use Tables tutorial.
This JCheckBox you're looking for is the default renderer/editor for Boolean class. Having said this JTable makes use of TableModel.getColumnClass() to decide the proper renderer/editor. If you use DefaultTableModel the implementation of the aforementioned method always return Object.class so you would have to override it to return Boolean.class. For instance let's say the first column will contain booleans:
DefaultTableModel model = new DefaultTableModel() {
#Override
Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? Boolean.class : super.getColumnClass(columnIndex);
}
};
It is all well explained in the linked tutorial.
Addendum
Another approach is shown in this Q&A: Checkbox in only one JTable Cell. This is useful when a given column may contain different types of values (booleans, numbers, strings...) so overriding getColumnClass() is not feasible. Don't think it's your case but it might be helpful.
also i want to know that how do i be able to find out that which check
box is checked and how to use the variable to respond the request of
the multiple deletes
Just iterate over the rows asking for the column value (true/false). If it's "selected" (true) then delete it:
TableModel model = table.getModel();
for(int i = 0; i < model.getRowCount(); i++) {
if((Boolean)model.getValueAt(i, 0)) {
// delete the row
}
}
Off-topic
Database calls are time consuming tasks and may block the Event Dispatch Thread (a.k.a. EDT) causing the GUI become unresponsive. The EDT is a single and special thread where Swing components creation and update take place. To avoid block this thread consider use a SwingWorker to perform database calls in a background thread and update Swing components in the EDT. See more in Concurrency in Swing trail.

Setting JTable Column width from another class

public TableModel getTableData() {
TableModel model=null;
try {
String sql = "SELECT eventID as 'Event ID', date as 'Date',eventName as 'Name', time as 'Start Time' FROM Event";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
model = (DbUtils.resultSetToTableModel(rs));
//CODE TO SET WIDTH OF JTABLE IN VIEWS
}
catch(SQLException e){
e.printStackTrace();
}
finally {
try {rs.close(); pst.close();}
catch(SQLException e){} }
return model;
}
Above is a method of the Model class, responsible for setting up the table model for the table I have in Views called tableEvent.
The Controller class uses the above method to set change the state of the tableEvent of Views Class. Please note tableEvent in Views is empty/nothing there. Model passes values of rs to Controller which will then change the display of the table and populate values.
Heres what I mean:
view.tableEvent.setModel(model.getTableData());
However, I am trying to set the width of the columns in Model rather than inViews through tableEvent.getColumnModel().getColumn(1).setPreferredWidth(60);. if I pass the table itself to the method getTableData() in order to set the width of the column, it doesnt really work. Is there a way I can specify my desired width of the first 4 column of the table in Model class in geTableData() method somehow so that it is consistent at all times. Right now I have this at part of the constructor of Views class which obviously means its only to my desired width only at initialisation.
If the JTable or TableModel are empty and have no column information, then you need to supply that information yourself.
You could either create a new TableColumnModel, add the required TableColumns to it, providing the width information you want/need and apply that model to the JTable.
You would then need to fill in the TableModel and supply that to the JTable as well.
I would, personally, extract the meta data from the ResultSet BEFORE I tried retrieving the data from it.

Categories