How to refresh JTable after inserting data to database? - java

I'm populating JTable from access database. when running the code for the first time, table loads perfectly. Then adding new records to database from JDialog. What I was trying to do is to call loadData() method when JDialog is closed, but table is not updating.
This is my loadData() method:
private void loadData() {
System.out.println("sssss");
final String [] columnNames={"Seq", "First Name", "Last Name","Num1","Num2","Num3"};
connectDb();
data = new Object[rows][columns];
int row = 0;
try {
while(rs.next()){
for(int col = 0 ; col<columns; col++ ){
if(col==0)
data[row][col]=rs.getString("contact_seq");
if(col==1)
data[row][col]=rs.getString("contact_fname");
if(col==2)
data[row][col]=rs.getString("contact_lname");
if(col==3)
data[row][col]=rs.getString("contact_num1");
if(col==4)
data[row][col]=rs.getString("contact_num2");
if(col==5)
data[row][col]=rs.getString("contact_num3");
}
row++;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames){
/**
*
*/
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
}
};
table = new JTable(model);
}`
this how I call loadData method when closing the JDialog.
JMenuItem mntmNew = new JMenuItem("New Contact");
mntmNew.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addData gui = new addData(viewData.this,rs);
gui.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
gui.setVisible(true);
gui.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e){
loadData();
}
});
}
});
mnFile.add(mntmNew);
My database is updated when adding the records but Jtable is not refreshed.

Here:
private void loadData() {
...
table = new JTable(model); // don't re-create the table here
}
Don't re-create the table but update its model instead, either by setting a new table model or by clearing and re-filling the current one:
private void loadData() {
...
table.setModel(model);
// Of course, table should have been initialized
// and placed first, and only once!
}
See examples here (includes SwingWorker to make database calls in a background thread), here and here. Please have a look to those answers, there are explanations to make the point clear.

This worked for me:
if (model.getRowCount() > 0) {
for (int i = model.getRowCount() - 1; i > -1; i--) {
model.removeRow(i);
}
}
setTablevalue();
I removed all the rows from the JTable and again called the setTableValue method to re-populate the table.

This is a shot in the dark, but maybe this will work?:
public void windowClosed(WindowEvent e) {
loadData();
// Add this line:
table.repaint();
}
If I understand what is going on, the underlying database is getting updated but the JTable component is not showing the updates. My guess is that you just have to call the repaint() method so that the JTable gets updated as well.

Related

Why won't JTable with DefaultTableModel Refreshed?

basically what i am trying to do is, i have a JList which contain a list of available drive, if one of that drive selected by user then i will show all html files which located in selected drive in a JTable, so i put an event listener for my JList and then i create a JTable and put all data there and show it in the container. the code look like this:
static class HtmlListing implements ListSelectionListener
{
public void valueChanged(ListSelectionEvent event)
{
if (!event.getValueIsAdjusting())
{ //trying to remove and re-add controls in container.
EastCont.removeAll();
globarr = new ArrayList<File>(); // global variable
FileListing fl = new FileListing();
fl.walk(fileList1.getSelectedValue() + "work\\airasia\\html", 500, 0);
//if(globarr.size() > 0)
//{
Object[][] data = new Object[globarr.size()][globarr.size()];
for(int i = 0; i < globarr.size(); i++)
{
if(globarr.get(i).isFile())
{
String filename = globarr.get(i).getName().toString();
String date = sdf.format(globarr.get(i).lastModified());
Object[] obj = new Object[] {filename, filename.substring(filename.lastIndexOf(".") + 1), date, globarr.get(i).getAbsolutePath()};
data[i] = obj;
}
}
Object[] column = new Object[]{"name ", "type", "date modified", "path"};
DefaultTableModel model = new DefaultTableModel(data, column);
model.fireTableDataChanged();
table = new JTable(model)
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
};
};
table.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
if (e.getClickCount() == 2)
{
int rowIdx = table.getSelectedRow(); // path to your new file
TableModel tm = table.getModel();
String path = tm.getValueAt(rowIdx, 3).toString();
File htmlFile = new File(path);
try // open the default web browser for the HTML page
{
Desktop.getDesktop().browse(htmlFile.toURI());
//Desktop.getDesktop().open(htmlFile);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
table.removeColumn(table.getColumnModel().getColumn(3)); //hide column path from display
table.setFillsViewportHeight(true);
table.setIntercellSpacing(new Dimension(0, 5));
table.setShowGrid(false);
scrollPane = new JScrollPane(table);
EastCont = new JPanel();
EastCont.setLayout(new BorderLayout());
EastCont.add(scrollPane);
EastCont.setPreferredSize(new Dimension(1050, 1000));
//EastCont.repaint();
//EastCont.revalidate();
gui.add(EastCont, BorderLayout.EAST);
gui.revalidate();
gui.repaint();
// }
// else
// {
// EastCont.remove(table);
// gui.remove(EastCont);
// gui.revalidate();
// gui.repaint();
// }
}
this code work only for first time, but does not working for second time and so on, so what i miss here? any help would be great. thank you.
DefaultTableModel model = new DefaultTableModel(data, column);
//model.fireTableDataChanged();
//table = new JTable(model)
table.setModel( model );
Don't create a new table change reset the model of your current table. The rest of the code in that method is not necessary either since you are not creating any new GUI components.
Also, never invoke a fireXXX method. That is the responsibility of the TableModel.

How to update the view of JTable after adding a new row?

This is my TableModel, I have extended AbstractTableModel
class CustomTableModel extends AbstractTableModel
{
String[] columnNames = {"Name","Contact","eMail","Address","City","Pin","State","Type","ID"};
Vector<String[]> data = new Vector<String[]>();
CustomTableModel()
{
try
{
//Using JDBC connection//
while(rs.next())
{
String[] s=new String[9];
s[0]=rs.getString(1);
//System.out.println(s[0]);
s[1]=rs.getString(2);
s[2]=rs.getString(3);
s[3]=rs.getString(4);
s[4]=rs.getString(5);
s[5]=rs.getString(6);
s[6]=rs.getString(7);
s[7]=rs.getString(8);
s[8]=rs.getString(9);
data.add(s);
}
}
catch(Exception e)
{
System.out.println("the exception is :"+e.toString());
}
}
public int getColumnCount() {
int columnCount = columnNames.length;
return columnCount;
}
public int getRowCount() {
int rowCount = data.size();
return rowCount;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return data.get(rowIndex)[columnIndex];
}
public String getColumnName(int column) {
return columnNames[column];
}
public void removeRow(int r)
{
for(int i=0;i<data.size();i++)
{
String[] s = (String[])data.get(i);
if(s[0]==getValueAt(r,0))
{
try
{
//using JDBC connections to delete the data from DB//
//also removing the value from data and also updating the view//
data.remove(data.get(i));
fireTableRowsDeleted(r, r);
}
catch (Exception e)
{
System.out.println(e.toString());
}
break;
}
}
}
//I am using the following code to update the view but it doesnot work//
public void addRow(String[] a)
{
data.add(a);
fireTableRowsInserted(data.size() - 1, data.size() - 1);
}
}
I have a table class which extends CustomTableModel .
class table extends CustomTableModel
{
final JButton editButton = new JButton("Edit");
final JButton deleteButton = new JButton("Delete");
final JTable mytable = new JTable(new CustomTableModel());
.
.
.
}
I have a add button , and in its action listener i use the following code to pass the values that i wanted to add.
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);
Pls let me know where i am going wrong . Thanks
Pls let me know where i am going wrong . Thanks
String[] a = {"a","b","c","d","e","f","g","h","i"};
table myTableObj = new table();
myTableObj.addRow(a);
code lines talking about
create a new row
create a new JTable
row is added to a new JTable
result is that a new JTable is never added to visible Swing GUI
don't do that, why is a new JTable recreated on every JButtons event
add String[] a... to the CustomTableModel directly
for better help sooner post an SSCCE, short, runnable, compilable
The table class makes no sense. It is supposed to be a TableModel that shoud be set into a JTable. Instead you have JTable declared as a field inside this table class (which should be Table btw according to Java naming convention). The result is that when constructing a new table object, a JTable is constructed inside it with another CustomTableModel inside. So the tableModel you are adding rows into is not the tableModel actually used by your JTable.
You can also use the myCustomTable.fireTableStructureChanged();

Remove JTable row that read file records

I am New in java, I have a JTable that can read records from a txt file and show they perfectly.
I want to add a new book to my JFrame that when user select a row on table and clicked the "delete" button, that row should delete and that deleted row records must delete from txt file,too.
my code is this, but it has errors and not seen JTable! :
public class CopyOfAllUserTable extends AbstractTableModel {
Vector data;
Vector column;
public static void main(String[] args){
new CopyOfAllUserTable();
}
public CopyOfAllUserTable() {
String line;
data = new Vector();
column = new Vector();
try {
FileInputStream fis = new FileInputStream("D:\\AllUserRecords.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while (st1.hasMoreTokens())
column.addElement(st1.nextToken());
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, " ");
while (st2.hasMoreTokens())
data.addElement(st2.nextToken());
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
final JFrame frame1=new JFrame();
JTable table=new JTable(data,column);
JButton button1=new JButton("Delete");
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model=new DefaultTableModel(data, column);
JTable table=new JTable(model);
}
});
JPanel panel=new JPanel();
panel.add(table);
panel.add(button1);
frame1.add(panel);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setBounds(200, 80, 600, 500);
frame1.setVisible(true);
frame1.setEnabled(true);
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return column.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
}
My problem is in delete row, and read records from file to jtable are perfectly successful.
Firstly you're not adding your JTable to the content of the frame.
For containers like: frame.getContentPane() and JPanel you should add the child components by using their #add(...) method.
For example:
final JPanel panel=new JPanel(new BorderLayout());
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel model=new DefaultTableModel(data, column);
JTable table=new JTable(model);
panel.add(new JScrollPane(table));
panel.revalidate();
}
});
Note that JPanel default layout is FlowLayout. Second thing - if you want to have headers and scrolling in your JTable you need to wrap it with JScrollPane.
Next - you should revalidate the panel after adding/removing/etc.
The second issue is removing rows from JTable. I usually write a method to handle it:
protected void removeRows(final int[] rows) {
int modelRows[] = new int[rows.length];
for(int i = 0; i < rows.length; ++i) {
modelRows[i] = table.convertRowIndexToModel(rows[i]);
}
Arrays.sort(modelRows);
for(int i = modelRows.length - 1; i >= 0; --i) {
int row = modelRows[i];
model.removeRow(row);
}
model.fireTableDataChanged();
}
The convertRowIndexToModel method converts index returned by JTable#getSelectedRows() or JTable#getSelectedRow() (which are the visible indices) to the model indices. If you set RowSorter for your JTable or you leave it to standard implementation:
table.setAutoCreateRowSorter(true);
You are adding table directly to the panel with out using the JScrollPane. Your table header will not be visible if you do like this,
So instead of this,
JPanel panel=new JPanel();
panel.add(table);
Do this,
JPanel panel=new JPanel();
panel.add(new JScrollPane(table));
Why to use JScrollPane? Read this.
When user selects a row and clicks on delete, then get the selected row and remove it from the table list. As you are using AbstractTableModel then you have to write your custom removeRow(..) method to perform this.
Example:
private boolean removeSelectedRow(int row) {
// Remove the row from the list that the table is using.
dataList.remove(row);
// You need to call fireXXX method to refresh the table model.
fireTableDataChanged();
return true;
// If fail return false;
}
If delete is the action then first get the selected row and then call removeSelectedRow(int) like the following,
private void deleteRow() {
int selectedRow = table.getSelectedRow();
boolean deleteStatus = removeSelectedRow(selectedRow);
// Only if the deletion is success then delete from the file.
if(deleteStatus) {
// Delete it from the file too.
}
}
first you have to make sure that something has been selected: when there is something selected than enable the delete button. please look up the JTable java source code #
http://developer.classpath.org/doc/javax/swing/JTable-source.html
and the following code:
1331: /**
1332: * Receives notification when the row selection changes and fires
1333: * appropriate property change events.
1334: *
1335: * #param event the list selection event
1336: */
1337: public void valueChanged(ListSelectionEvent event)
1338: {
1339: firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
1340: Boolean.FALSE, Boolean.TRUE);
1341: int r = getSelectedRow();
1342: int c = getSelectedColumn();
1343: if (r != lastSelectedRow || c != lastSelectedColumn)
1344: {
1345: Accessible o = getAccessibleAt(lastSelectedRow,lastSelectedColumn);
1347: Accessible n = getAccessibleAt(r, c);
1348: firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY, o, n);
1350: lastSelectedRow = r;
1351: lastSelectedColumn = c;
1352: }
1353: }
You need to register for the last event to be notified when the selected rows have been changed. Add your own listener to enable the deletebutton based on whether or not a row has been selected which is as you can see in the event itself.
Please use to start with the DefaultTableModel because it will work in 90% of the cases.
And any change is applied to the tabledatamodel which will automatically propogate to the JTable View: normally you never change the view because all selection and scroll information is lost which is something you don't want.
When the delete button is fired the approach is straight forward: there is a row selected, otherwise it is impossible to click it: remove that selected row number from the defaultTableModel, and last but not least I would write simply the entire contents of the datamodel model to the designated file because the table's model hold the actual rows that are indeed displayed in the View.
So please think in terms of models models and models: Views are instantiated only once, packed scrolled etc and than you leave them as is. Models are normally also never changed: you change the contents of the models by adding and or deleting rows. One other tip: use always renderers: those that don't don't, in my humble opinion, don't understand how to work with JTables.
And yes you can leave out the first part to listen for selection changes: sure and pop up a warning to indicate the problem. And in a later stage add the functionality that listens for selection changes to enable and or disable the JButton delete row.
Hope this helps.

Java update jtable row from another thread

I have a multi threaded program and I'm trying to use a JTable to view the progress of each thread. Each thread is a row the JTable. I have posted a simplified and relevant code of what I have now. Each time I press start a new thread is started and the row is added to the JTable. But how do I update the "Column 2" which of the row which belongs to that thread from the running thread?
In main this is what I have
JTable table = new JTable(new DefaultTableModel(new Object[]{"Thread Name", "Progress"}, 0));
btnBegin.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
Thread newThread = new Thread(new MyThreadClass(country, category));
newThread.start();
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Thread " + threadNumber, "Column 2"});
}
});
If you can add a field tableModel to MyThreadClass (field+constructor argument), from this class, you can invoke the code #sedran was mentioning.
Example:
public class T {
static int threadNumber = 0;
public static void main(String[] args) throws Exception {
final JTable table = new JTable(new DefaultTableModel(new Object[] { "Thread Name", "Progress" }, 0));
JButton btnBegin = new JButton("Begin");
btnBegin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
MyThreadClass newThread = new MyThreadClass(model, threadNumber++);
newThread.start();
model.addRow(new Object[] { "Thread " + threadNumber, "Column 2" });
}
});
JFrame frame = new JFrame();
frame.add(btnBegin, BorderLayout.NORTH);
frame.add(table);
frame.setSize(400, 400);
frame.setVisible(true);
}
static class MyThreadClass extends Thread {
private final DefaultTableModel model;
private final int threadNumber;
public MyThreadClass(DefaultTableModel model, int threadNumber) {
super();
this.model = model;
this.threadNumber = threadNumber;
}
#Override
public void run() {
for (int i = 0; i <= 5; i++) {
final int index = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
model.setValueAt(index * 20, threadNumber, 1);
}
});
}
}
}
}
Please note that the use of SwingUtilities.invokeLater is important as the view MUST be refreshed in the EDT.
if you want to update the column at runtime and if you know in which row you want to update, you can use it this way:
int row; // row number you want to update.
int column = 1; // You want to update the first row.
DefaultTableModel model = (DefaultTableModel)table.getModel();
Object value = "New Value Of This Cell";
model.setValueAt(value, row, column);
You can pass or set your table, and the row in which the thread is showing to the MyThreadClass, so it can update its row by itself.
You can write a method insie MyThreadClass like this:
public void setTableAndRow(int row, JTable table) {
this.table = table;
this.row = row;
}
You can pass those arguments while creating the thread:
btnBegin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
MyThreadClass myThread = new MyThreadClass(country, category);
Thread newThread = new Thread(myThread);
/**
* We know, if there is n rows starting from 0,
* index of the row that we're adding is n.
*/
int row = model.getRowCount();
myThread.setTableAndRow(row, table);
// Now we add the row before starting the thread, because it
// will try to reach that row, we don't want any exceptions.
model.addRow(new Object[]{"Thread " + threadNumber, "Column 2"});
newThread.start();
}
});
Suggestions:
Use a SwingWorker object to create your background thread.
One way to get updates from the SwingWorker is by using its publish/process method pair. This allows the background thread to pass data to the Swing application on the Swing event thread. This will allow the background process to "push" data onto the GUI.
The other way to get updates is to add a PropertyChangeListener to the SwingWorker and have the SwingWorker update bound properties. Either will work fine. This will allow data to be "pulled" from the background process onto the GUI.
To update the data in a specific data row, you'll need to somehow connect a row of the model with the thread you're following. You could always iterate through the cells of the a certain column of the table model using getValueAt(...) until you've found one that contains data that matches that of the thread, perhaps a field of the watched class. Then you can update the data held by a different column of that row using JTable's setValueAt(...)
I think SwingUtilies.invokeLater() is what you are looking for, so you can access event dispatch thread.

How to provide pagination support to a JTable in Swing?

I have created one GUI in Swing Java in which I have used JTable.Now I want to display next page information into it by using pagination. How should I do that ?
Another option to implement this is to use a scrollbar-less scrollpane and a couple nav buttons to effect the control. The buttons that have been added are normal JButtons for the prototype.
A quick prototype is added below. It makes a couple assumptions, one of which is that the table model has all of its data. Work could be done to ensure that rows end up flush at the top of the view upon navigation.
private void buildFrame() {
frame = new JFrame("Demo");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addStuffToFrame();
frame.setVisible(true);
}
private void addStuffToFrame() {
final JTable table = getTable();
final JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
final JButton next = new JButton("next");
final JButton prev = new JButton("prev");
ActionListener al = new ActionListener(){
public void actionPerformed(ActionEvent e) {
Rectangle rect = scrollPane.getVisibleRect();
JScrollBar bar = scrollPane.getVerticalScrollBar();
int blockIncr = scrollPane.getViewport().getViewRect().height;
if (e.getSource() == next) {
bar.setValue(bar.getValue() + blockIncr);
} else if (e.getSource() == prev) {
bar.setValue(bar.getValue() - blockIncr);
}
scrollPane.scrollRectToVisible(rect);
}
};
next.addActionListener(al);
prev.addActionListener(al);
JPanel panel = new JPanel(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.add(prev);
buttonPanel.add(next);
panel.add(buttonPanel, BorderLayout.NORTH);
panel.add(scrollPane, BorderLayout.CENTER);
frame.getContentPane().add(panel);
}
private JTable getTable() {
String[] colNames = new String[]{
"col 0", "col 1", "col 2", "col 3"
};
String[][] data = new String[100][4];
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 4; j++) {
data[i][j] = "r:" + i + " c:" + j;
}
}
return new JTable(data,colNames);
}
alt text http://img7.imageshack.us/img7/4205/picture4qv.png
Paging in a Swing JTable looks like a nice article.
Here is an excerpt:
As far as I remember the solution for this problem lies in the concept of paging: just retrieve the data that the user wants to see and nothing more. This also means you have to sometimes get extra data from the db server (or appserver) if your user scrolls down the list.
Big was my surprise that there wasn't really an out-of-the-box solution (not even a copy- paste solution) for this problem. Anyone that knows one, please don't hesitate to extend my (rather limited) knowledge of the J2EE platform.
So we dug in, and tried to build a solution ourselves.
What we eventually came up with was an adapted TableModel class to takes care of the paging.
You can try with 2 query, first query is to count total rows in DB and second query is for the real data :) And for the UI side, you can try like this:
public class MainForm extends javax.swing.JFrame {
private void initDefaultValue() {
rowsPerPage = Integer.valueOf(cmbPageSize.getSelectedItem().toString());
totalRows = Main.getTablePagingService().countComments();
Double dblTotPage = Math.ceil(totalRows.doubleValue()/rowsPerPage.doubleValue());
totalPage = dblTotPage.intValue();
if (pageNumber == 1) {
btnFirst.setEnabled(false);
btnPrevious.setEnabled(false);
} else {
btnFirst.setEnabled(true);
btnPrevious.setEnabled(true);
}
if (pageNumber.equals(totalPage)) {
btnNext.setEnabled(false);
btnLast.setEnabled(false);
} else {
btnNext.setEnabled(true);
btnLast.setEnabled(true);
}
txtPageNumber.setText(String.valueOf(pageNumber));
lblPageOf.setText(" of " + totalPage + " ");
lblTotalRecord.setText("Total Record " + totalRows + " rows.");
List wPComments = Main.getTablePagingService().findAllComment(pageNumber, rowsPerPage);
jTable1.setModel(new CommentTableModel(wPComments));
autoResizeColumn(jTable1);
}
private void btnFirstActionPerformed(ActionEvent evt) {
pageNumber = 1; initDefaultValue();
}
private void btnPreviousActionPerformed(ActionEvent evt) {
if (pageNumber > 1) {
pageNumber -= 1; initDefaultValue();
}
}
private void btnNextActionPerformed(ActionEvent evt) {
if (pageNumber
And in service layer, you just need use limit function like this :
public List findAllComment(Integer pageNumber, Integer rowsPerPage) {
try {
List listWP = new ArrayList();
preparedFindAll.setInt(1, (rowsPerPage*(pageNumber-1)));
preparedFindAll.setInt(2, rowsPerPage);
ResultSet rs = preparedFindAll.executeQuery();
while (rs.next()) {
WPComment comment = new WPComment();
comment.setCommentID(rs.getInt("comment_ID"));
comment.setCommentAuthor(rs.getString("comment_author"));
comment.setCommentDate(rs.getDate("comment_date"));
comment.setCommentContent(rs.getString("comment_content"));
listWP.add(comment);
}
return listWP;
} catch (SQLException ex) {
Logger.getLogger(TablePagingServiceJDBC.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public Integer countComments() {
try {
Integer totalRows = 0;
ResultSet rs = preparedCount.executeQuery();
while (rs.next()) {
totalRows = rs.getInt("count(*)");
}
return totalRows;
} catch (SQLException ex) {
Logger.getLogger(TablePagingServiceJDBC.class.getName()).log(Level.SEVERE, null, ex);
}
return 0;
}
Or you can fork me on github at Project Page Table Paging on Swing :)
I have written a Java pagination tool dataj. It uses JQuery dataTables plug-in pagination metadata to build up the result page.
I have also added some client classes for Java Swing including a TableRowSorter that calls the (server side) sorting instead of sorting inside the table model.
Feel free to download it and contact me if you have any questions. It's under Apache 2 license.
Alternatively, you can make use of the QuickTable project.
Screenshot
Here is the DBTable component in action:
The DBTable component is embedded in a traditionnal JFrame.
Sample code
The following sample code produces the window shown in the previous screenshot:
import javax.swing.JFrame;
import javax.swing.UIManager;
import quick.dbtable.DBTable;
public class QuickTableFrame extends JFrame {
private static final long serialVersionUID = -631092023960707898L;
public QuickTableFrame() {
try {
// Use system look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// set Frame properties
setSize(300, 200);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// create a new quicktable
DBTable dBTable1 = new DBTable();
// add to frame
getContentPane().add(dBTable1);
// set the database driver to be used, we are using jdbc-odbc driver
dBTable1.setDatabaseDriver("org.h2.Driver");
/*
* set the jdbc url,"quicktabledemo" is the data source we have
* created for the database
*/
dBTable1.setJdbcUrl("jdbc:h2:mem:test;INIT=create table employee as select * from CSVREAD('test.csv');");
// set the select statement which should be used by the table
dBTable1.setSelectSql("select * from employee");
// to create the navigation bars for the table
dBTable1.createControlPanel();
// connect to database & create a connection
dBTable1.connectDatabase();
// fetch the data from database to fill the table
dBTable1.refresh();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
// create a new table frame
QuickTableFrame myframe = new QuickTableFrame();
}
}
Resources and dependencies
test.csv
empid,emp_name,emp_dept,emp_salary
1,Azalia,ornare,114918
2,Jade,tristique,152878
3,Willa,In scelerisque scelerisque,166733
...
H2
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.187</version>
</dependency>
References
QuickTable basic tutorial
QuickTable official tutorials
Download latest jar
h2 database

Categories