I'm working on a Java database application, where the user has one side to insert data and another to show in a JTable (in a JScrollPane) the content of the linked HSQLDB database. Everthing works so far so good, but I searched for a very long time without finding how to update my JTable dynamically when a change is made to the database (add, update or delete) for each instance of my program because several persons can work on it simultaneously.
It actually works by replacing my table model for local update, but for other instances, i have set a Timer which is not very clean.
Could you help me resolving this please ?
Here is my code (I have an Interface.java for "visible" part and a SQL.java to manage my db) :
My timer
JTable table = new JTable(sql.showTable("SELECT * FROM suivi_flotte"));
Timer timer = new Timer(900000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sql.updateTable();
nbLinesOrRefresh.setText("Actualisation...");
Timer timer2 = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
nbLinesOrRefresh.setText("");
}
});
timer2.start();
timer2.setRepeats(false);
}
});
timer.setDelay(900000);
timer.start();
formatTable(table);
My updateTable() method (called each time there is an insert, update or delete)
protected void updateTable() {
Interface.f.table.setModel(showTable("SELECT * FROM suivi_flotte"));
Interface.f.formatTable(Interface.f.table); // a method to custom JTable appearance
}
My showTable(String query) method
protected DefaultTableModel showTable(String query) {
String[] columnsTitles = {"N°", "Propriétaire", "Service", "Grade", "Nom", "Prénom", "Mail", "N° SIM", "N° Tél", "Modèle", "N° Série", "IMEI", "N° Crypto", "Date début", "Date fin", "DS", "Commentaire", "Date de création"};
ArrayList<String> columnNames = new ArrayList<>();
ArrayList<Object> data = new ArrayList<>();
connectDB(); // only to connect to db
try (ResultSet rs = stmt.executeQuery(query)) {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++) {
columnNames.add(columnsTitles[i - 1]);
}
while (rs.next()) {
ArrayList<Object> row = new ArrayList<>(columns);
for (int i = 1; i <= columns; i++) {
row.add(rs.getObject(i));
}
data.add(row);
}
shutdownDB(); // to fully disconnect from db
} catch (SQLException e) {
System.out.println(e.getMessage());
}
Vector<Vector<?>> dataVector = new Vector<>();
Vector<String> columnNamesVector = new Vector<>();
for (int i = 0; i < data.size(); i++) {
ArrayList<?> subArray = (ArrayList<?>) data.get(i);
Vector<Object> subVector = new Vector<>();
for (int j = 0; j < subArray.size(); j++) {
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++) {
columnNamesVector.add(columnNames.get(i));
}
DefaultTableModel tModel = new DefaultTableModel(dataVector, columnNamesVector) {
private static final long serialVersionUID = 1L;
public Class<?> getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object o = getValueAt(row, column);
if (o != null) {
return o.getClass();
}
}
return Object.class;
}
#Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// tModel.fireTableDataChanged(); // <-- does not work
return tModel;
}
Thank you for your help.
UPDATE 1 :
All my connection/disconnection code :
private void connectDB() {
JFrame op = new JFrame();
op.setAlwaysOnTop(true);
try {
Class.forName("org.hsqldb.jdbcDriver");
co = DriverManager.getConnection("jdbc:hsqldb:file:db;shutdown=true");
stmt = co.createStatement();
} catch (SQLException | ClassNotFoundException e) {
JOptionPane.showMessageDialog(op, "Erreur de connexion à la base de données :\n" + e.getMessage(), Interface.windowTitle, JOptionPane.ERROR_MESSAGE);
}
}
private void openDB() throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("db.sql"));
String line;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
stmt.executeUpdate(sb.toString());
} catch (SQLException e) {}
}
private void shutdownDB() throws SQLException {
stmt.close();
co.close();
}
UPDATE 2 :
I changed everything in SQL.java to non-static. Each SQL.[...] has been changed to sql.[...] with private SQL sql = new SQL(); on top of the class and public SQL() {} in the class. I also changed it in the above code.
So I have two JFrames. The first one just has a button with an Event to call the second one. This second JFrame contains a table filled with data from a MySQL database, which is the following code:
public class NewClass extends JFrame {
public NewClass()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
String url = "jdbc:mysql://localhost:3306/MYDB";
String userid = "root";
String password = "password";
String sql = "SELECT * FROM MYTABLE";
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
}
public static void main(String[] args)
{
NewClass frame = new NewClass();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
When I run NewClass directly, pack() works as is supposed to and resizes the JFrame depending on the size of the talble that's within. However, whenever I run the first JFrame with the button and then press the button to call the event, NewClass pops up but the window is way too small. I have tried using setSize and obviously pack().
When I resize the JFrame manually the columns and rows are all there like they're supposed to, it's just that I can't figure out why pack() isn't working.
Do you have any ideas on how to resize this second JFrame without having to do it manually?
Thanks in advance!
EDIT:
The code for the button on first JFrame which calls NewClass is the following:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
NewClass frame = new NewClass();
frame.setVisible(true);
}
Change...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
NewClass frame = new NewClass();
frame.setVisible(true);
}
to something more like...
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
{
NewClass frame = new NewClass();
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
which would seem to match what you're doing in your main method
i am trying to make an application that sends a number of string added by the user to my SQL server. however when i try to add an string to my jlist from jtextfield it gets added twice..
here is the thing
user adds a name to jtextfield . when he hits the + button it is send to jlist
public void addBrand() {
int index = BrandList.getSelectedIndex(); // get selected index
if (index == -1) { // no selection, so insert at beginning
index = 0;
}
else { // add after the selected item
index++;
}
model.insertElementAt(BrandLbl.getText(), index);
BrandLbl.setText(null);
}
all fine here i see one item added to my jlist
when the user decides the list is complete he hits the "next" button and
the sendArraytoDB(JList list) method is called
public static void sendArraytoDB(JList<String> list){
Connection con = null;
PreparedStatement stm = null;
String updQuery = "insert into brand_names (name) values (?)";
try{
con = DB.getConnection();
//con.setAutoCommit(false);
int x =1;
stm = con.prepareStatement(updQuery);
int f = list.getModel().getSize();
System.out.print(f);
for (int i=0; i<list.getModel().getSize(); i++){
String name =list.getModel().getElementAt(i);
stm.setString(x, name);
//try{
stm.executeUpdate();
//}finally{
//stm.close();
//}
}
}catch(SQLException ex){
System.out.printf("error while sending array to db");
ex.printStackTrace();
}finally{
if (stm != null){
etc etc....
for my bad luck the my databse shows that there are two names sent..
i cant post images so its like
aa brand
1
2 "the string i sent"
the list has allways one more empty record before my record...
trying to see wtf is happening i counted the list size just before i send it
int f = list.getModel().getSize();
System.out.print(f);
and the answer is 2 ... if i enter 3 records its 6 .. etc...
i narrowed the problem to the model since changing the addBrand() method to
public void addBrand() {
String all = "xghxc";
model.addElement(all);
}
impudently shows two of "xghxc" being added to my list at the same time in front of my very own amazed eyes
i searched google but it doesnt even have a similar problem to mine :(
what i need is a code or an advice or smth to point me to not adding an empty useless record amongst my records
here is my full code for anyone who has the patience and time
MyMain.java
package tweGraf;
import javax.swing.JFrame;
public class MyMain {
public static void main(String[] args) {
// TODO Auto-generated method stub
Gui g = new Gui();
DB.MakePool();
g.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
g.setSize(1000, 800);
g.setVisible(true);
}
}
Gui.java
package tweGraf;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Gui extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frameYesNo = new JFrame();
String message = "all data will perish. are you sure";
private JPanel Container = new JPanel(); // panels
private JPanel FirstPanel = new JPanel();
private JPanel NewSession = new JPanel();
private JPanel LoadSession = new JPanel();
private JPanel LoadList = new JPanel();
private JPanel GraphSub1 = new JPanel();
private JPanel GraphSub2 = new JPanel();
private JPanel GraphSub3 = new JPanel();
private JTabbedPane GraphPanel = new JTabbedPane();
private JButton NewSessBtn = new JButton(); // buttons
private JButton LoadSessBtn = new JButton();
private JButton BackFP = new JButton();
private JButton plusBrand = new JButton();
private JButton minusBrand = new JButton();
private JButton Next = new JButton();
private JLabel EnterBrandLbl = new JLabel(
"Please insert brands for analysis "); // Labels
private JTextField BrandLbl = new JTextField(20); // textfields
public DefaultListModel<String> model = new DefaultListModel<String>
public JList BrandList = new JList(model); // list
private JScrollPane MyScrollPane = new JScrollPane(BrandList);
private CardLayout cardLayout = new CardLayout(); // layouts
private GridBagLayout MyLayout = new GridBagLayout();
GridBagConstraints MyConstr = new GridBagConstraints();
public Gui() {
super("twegraph");
NewSessBtn.setText("New Session"); // button configuration
LoadSessBtn.setText("Load Session");
BackFP.setText("Back");
plusBrand.setText("+");
minusBrand.setText("-");
Next.setText("Next");
actionListener al = new actionListener();
NewSessBtn.addActionListener(al); // add action listeners
LoadSessBtn.addActionListener(al);
BackFP.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Next.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Container.setLayout(cardLayout); // panels to container+
Container.add(FirstPanel, "FirstPanel");
Container.add(NewSession, "NewSession");
Container.add(LoadSession, "LoadSession");
Container.add(GraphPanel, "GraphPanel");
Container.add(LoadList, "LoadList");
FirstPanel.setLayout(MyLayout); // first panel
MyConstr.gridwidth = 3;
MyConstr.gridheight = 3;
MyConstr.weightx = 1.0;
MyConstr.weighty = 1.0;
MyConstr.ipadx = 100;
MyConstr.ipady = 50;
MyConstr.insets = new Insets(50, 20, 50, 20);
MyConstr.gridx = 1;
MyConstr.gridy = 0;
MyConstr.anchor = GridBagConstraints.NORTH;
MyLayout.setConstraints(NewSessBtn, MyConstr);
FirstPanel.add(NewSessBtn);
MyConstr.gridx = 1;
MyConstr.gridy = 2;
MyConstr.anchor = GridBagConstraints.SOUTH;
MyLayout.setConstraints(LoadSessBtn, MyConstr);
FirstPanel.add(LoadSessBtn);
NewSession.setLayout(MyLayout); // New Session panel
MyConstr.gridwidth = 3;
MyConstr.gridheight = 3;
MyConstr.ipadx = 0; // size
MyConstr.ipady = 0; // size
MyConstr.gridx = 0;
MyConstr.gridy = 2;
MyConstr.insets = new Insets(10, 20, 10, 20);
MyConstr.anchor = GridBagConstraints.SOUTHWEST;
MyLayout.setConstraints(BackFP, MyConstr);
NewSession.add(BackFP);
MyConstr.anchor = GridBagConstraints.SOUTHEAST;
MyLayout.setConstraints(Next, MyConstr);
NewSession.add(Next);
MyConstr.ipadx = 0; // size
MyConstr.ipady = 0; // size
MyConstr.gridx = 0; // place
MyConstr.gridy = 1; // place
MyConstr.insets = new Insets(0, 0, 0, 0);
MyConstr.anchor = GridBagConstraints.PAGE_START;
MyLayout.setConstraints(EnterBrandLbl, MyConstr);
NewSession.add(EnterBrandLbl);
MyConstr.gridx = 0;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.CENTER;
MyLayout.setConstraints(BrandLbl, MyConstr);
NewSession.add(BrandLbl);
MyConstr.gridx = 2;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.LAST_LINE_START;
MyLayout.setConstraints(plusBrand, MyConstr);
NewSession.add(plusBrand);
MyConstr.gridx = 2;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.LAST_LINE_END;
MyLayout.setConstraints(minusBrand, MyConstr);
NewSession.add(minusBrand);
MyConstr.ipadx = 0; // size
MyConstr.ipady = 0;
MyConstr.gridx = 0;
MyConstr.gridy = 1;
MyConstr.anchor = GridBagConstraints.SOUTH;
MyLayout.setConstraints(MyScrollPane, MyConstr);
NewSession.add(MyScrollPane);
GraphPanel.addTab("overall",GraphSub1); //Graph panel
GraphPanel.addTab("tweets/time",GraphSub2);
GraphPanel.addTab("fame",GraphSub3);
this.setContentPane(Container);
cardLayout.show(Container, "FirstPanel");
}
public class actionListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
JButton src = (JButton) event.getSource();
int answer = 0;
if (src.equals(NewSessBtn))
{
answer = JOptionPane.showConfirmDialog(frameYesNo, message);
if (answer == JOptionPane.YES_OPTION) {
cardLayout.show(Container, "NewSession");
try {
DB.flushData();
} catch (SQLException ex) {
Logger.getLogger(Gui.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (answer == JOptionPane.NO_OPTION) {
frameYesNo.dispose();
}
}
if (src.equals(LoadSessBtn)){
cardLayout.show(Container, "LoadSession");
}
if (src.equals(BackFP)){
cardLayout.show(Container, "FirstPanel");
}
if (src.equals(Next)){
cardLayout.show(Container, "GraphPanel");
DB.sendArraytoDB(BrandList);
}
if (src.equals(plusBrand)){
addBrand();
}
if (src.equals(minusBrand))
{
removeBrand();
}
}
}
public void addBrand() {
/*int index = BrandList.getSelectedIndex(); // get selected index
if (index == -1) { // no selection, so insert at beginning
index = 0;
}
else { // add after the selected item
index++;
}*/
String all = "xghxc";
//model.insertElementAt(BrandLbl.getText(), index);
model.addElement(all);
//BrandLbl.setText(null);
}
public void removeBrand() {
int index2 = BrandList.getSelectedIndex();
if (index2 != -1){
model.remove(index2);
}
int size = model.getSize();
if (size == 0) {
minusBrand.setEnabled(false);
} else {
//if (index == model.getSize()) {
//index--;
//}
}
}
}
DB.java
package tweGraf;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JList;
/**
*
* #author cheval
*/
public class DB {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/twegrahpdb";
static final String USER = "root";
static final String PASS = "Xrt38H0a";
private static ComboPooledDataSource cdps = new ComboPooledDataSource();
public static void MakePool(){
try {
cdps = new ComboPooledDataSource();
cdps.setDriverClass(JDBC_DRIVER);
cdps.setJdbcUrl(DB_URL);
cdps.setUser(USER);
cdps.setPassword(PASS);
cdps.setMaxPoolSize( 50 );
cdps.setMaxStatements(50);
}catch(Exception ex){
System.out.printf("error smth wrong happened");
}
}
public static Connection getConnection() throws SQLException{
return cdps.getConnection();
}
public static void flushData() throws SQLException{
Statement stm = null;
Connection con = null;
try{
con = DB.getConnection();
stm = con.createStatement();
String flushquery1 = "TRUNCATE json_cache";
String flushquery2 = "TRUNCATE tweets";
String flushquery3 = "TRUNCATE tweet_mentions";
String flushquery4 = "TRUNCATE tweet_tags";
String flushquery5 = "TRUNCATE tweet_urls";
String flushquery6 = "TRUNCATE users";
String flushquery7 = "TRUNCATE brand_names";
stm.executeUpdate(flushquery1);
stm.executeUpdate(flushquery2);
stm.executeUpdate(flushquery3);
stm.executeUpdate(flushquery4);
stm.executeUpdate(flushquery5);
stm.executeUpdate(flushquery6);
stm.executeUpdate(flushquery7);
}catch (SQLException e) {
System.out.printf("error executing db clear");
} finally {
if (stm != null){
try{
stm.close();
System.out.printf("statement closed successfuly \n");
} catch (SQLException e){
System.out.printf("error closing statement");
}
}
if (con != null){
try{
con.close();
System.out.printf("connection closed succesfully \n");
} catch (SQLException e){
System.out.printf("error closing connection");
}
}
}
}
public static void sendArraytoDB(JList<String> list){
Connection con = null;
PreparedStatement stm = null;
String updQuery = "insert into brand_names (name) values (?)";
try{
con = DB.getConnection();
//con.setAutoCommit(false);
int x =1;
stm = con.prepareStatement(updQuery);
int f = list.getModel().getSize();
System.out.print(f);
for (int i=0; i<list.getModel().getSize(); i++){
String name =list.getModel().getElementAt(i);
stm.setString(x, name);
//try{
stm.executeUpdate();
//}finally{
//stm.close();
//}
}
}catch(SQLException ex){
System.out.printf("error while sending array to db");
ex.printStackTrace();
}finally{
if (stm != null){
try {
stm.close();
} catch (SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null){
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(DB.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
if you still dont know dont care about my actual problem but STILL see smth wrong regarding my coding style or my techniques plz post it
thanks for your time
i narrowed the problem to the model since changing the addBrand() method to...
So this tells me the addBrand() method is called multiple times.
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
Next.addActionListener(al);
plusBrand.addActionListener(al);
minusBrand.addActionListener(al);
As you can see above you add the listener twice to the button.
I'm making a simple program that show the teams, the matches and racking goal of Euro2016 in France.
I have some problem with JTable when changing query.
Here is what happens:
when I change from a Table of (for example) 10 rows to another one that contains only 5 rows it works. But if I change from a table that contains 5 rows to another of 10, the table doesn't change, it displays only 5 rows.
Here the code:
public class Euro2016GUI extends JFrame {
private Container container;
private Sfondo pnlSfondo;
JTable table;
JPanel panel;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
static Vector<String> headers = new Vector<String>();
public Euro2016GUI() {
data.removeAll(data);
headers.removeAll(headers);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(600, 400);
this.setTitle("Euro2016");
this.setLocationRelativeTo(null);
pnlSfondo = new Sfondo();
container = this.getContentPane();
container.add(pnlSfondo);
}
public void createTable(String pQuery) {
data.removeAll(data);
headers.removeAll(headers);
Control control = new Control();
panel = new JPanel(new BorderLayout());
panel.setSize(300, 300);
panel.setBackground(Color.red);
control.getData(pQuery);
data = control.getData();
headers = control.getHeaders();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setEnabled(false);
table.setMaximumSize(new Dimension(100, 300));
header_size();
JScrollPane scroll = new JScrollPane(table);
//scroll.setSize(600, 400);
scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
this.getContentPane().add(panel);
panel.add(scroll, BorderLayout.CENTER);
}
public void header_size() {
int colonne = table.getColumnModel().getColumnCount();
TableColumn column;
for (int i = 0; i < colonne; i++) {
column = table.getColumnModel().getColumn(i);
column.setPreferredWidth(200);
}
}
public void cleanData() {
if (table != null) {
DefaultTableModel dm = (DefaultTableModel) table.getModel();
dm.setRowCount(0);
table.revalidate();
}
data.removeAll(data);
headers.removeAll(headers);
}
}
CLASS CONTROL
public class Control {
private static Vector<Vector<String>> data = new Vector<Vector<String>>();
private static Vector<String> headers = new Vector<String>();
public void getData(String pQuery) {
// Enter Your MySQL Database Table name in below Select Query.
String query = pQuery;
Connection con = null;
ResultSet rs;
Statement st = null;
int colonne = 0;
data.removeAll(data);
headers.removeAll(headers);
try {
con = DBConnectionPool.getConnection();
st = con.createStatement();
rs = st.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
colonne = rsmd.getColumnCount();
for (int i = 1; i <= colonne; i++) {
headers.add(rsmd.getColumnName(i));
}
while (rs.next()) {
Vector<String> d = new Vector<String>();
for (int i = 1; i <= colonne; i++) {
d.add(rs.getString(i));
}
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (st != null) {
try {
st.close();
} catch (SQLException ex) {
Logger.getLogger(DataInJTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (con != null) {
DBConnectionPool.releaseConnection(con);
}
}
}
public Vector<Vector<String>> getData() {
return this.data;
}
public Vector<String> getHeaders() {
return this.headers;
}
}
HERE THE ACTION LISTENER IN THE MENU:
...
//----ROSE---//
private class OnClickRose implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
String str = e.getActionCommand();
str = str.replace("[", "");
str = str.replace("]", "");
String sx = "'";
String dx = "'";
String query = query2.concat(sx.concat(str.concat(dx)));
//frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query);
}
}
//----CALENDARIO----//
private class OnClickCalendario implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query4);
}
}
//----CLASSIFICA MARCATORI----//
private class OnClickMarcatori implements ActionListener {
Sfondo sfondo;
#Override
public void actionPerformed(ActionEvent e) {
frame.cleanData();
sfondo = frame.getPnlSfondo();
if (sfondo.isVisible() && sfondo.getParent().isVisible()) {
sfondo.setVisible(false);
}
frame.createTable(query3);
}
}
...
Could anybody tell me where I wrong?
Basically to tell the table to refresh itself, you just call the method fireTableDataChanged() of it's table model.
So in your example, after you run the query, you could just call:
((DefaultTableModel)yourTable.getModel()).fireTableDataChanged();
But I suggest you to stop using default table model, and implement your own table model. It's a lot easier to work.
I'm passing values for a java file which creates a JTable.
ResultSet res = np.InvestmentByInvestType(IType);
String tablename = "Investment By Invest Type";
int customAmt = np.showCustomizeInvestAmount1(IType);
CommonTable ct = new CommonTable();
ct.CommonSearchTable(res, customAmt,tablename);
I created a button in CommonSearchTable to export the JTable data using the ResultSet. But it showing error "Operation not allowed after ResultSet closed". A method in CommonSearchTable.java is as below:
public void CommonSearchTable( final ResultSet res, int totally, final String tablename) throws SQLException
{
JButton exportTable= new JButton ("Export");
ResultSetMetaData metaData = res.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++)
{
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<String>> data = new Vector<Vector<String>>();
while (res.next())
{
Vector<String> vector = new Vector<String>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++)
{
vector.add(res.getString(columnIndex));
}
data.add(vector);
}
model1 = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model1);
int rows = table.getRowCount();
Sorter = new TableRowSorter<DefaultTableModel> (model1);
table.setRowSorter(Sorter);
showSearchPages(30, 1);
table.setModel(model1);
String showTotal = "Total Amount : Rs."+totally+"/-";
JPanel footer = new JPanel();
JLabel show = new JLabel(showTotal);
box1.setBounds(10,30,800,30);
show.setBounds(10, 60, 100, 30);
show.setFont(new Font("Tahoma",Font.BOLD,16));
footer.add(box1);
footer.add(show);
footer.setPreferredSize(new Dimension(800,100));
JPanel holdingPanel = new JPanel(null);
JScrollPane sp = new JScrollPane(table);
JButton print = new JButton ("Print");
print.setBounds(10,10,100,30);
exportTable.setBounds(120,10,100,30);
sp.setBounds(10,50,780,580);
holdingPanel.add(print);
holdingPanel.add(exportTable);
holdingPanel.add(sp);
JFrame f = new JFrame("Search Results");
f.getContentPane().add(holdingPanel,BorderLayout.CENTER);
f.getContentPane().add(sp.getVerticalScrollBar(),BorderLayout.EAST);
f.getContentPane().add(footer,BorderLayout.SOUTH);
f.setPreferredSize(new Dimension(850,680));
f.pack();
f.setLocationRelativeTo(null);
f.dispose();
f.setResizable(false);
f.setIconImage(img.getImage());
f.setVisible(true);
exportTable.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent aev)
{
try
{
ExportFile ef = new ExportFile();
ef.WriteFile(res, tablename);
}
catch (SQLException | IOException ex)
{
Logger.getLogger(CommonTable.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
print.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
PrinterJob printJob = PrinterJob.getPrinterJob();
if (printJob.printDialog())
try
{
printJob.print();
}
catch(PrinterException pe)
{
}
}
});
}
Please show me the way.
As you can read in the docs for Resultset:
A ResultSet object is automatically closed when the Statement object
that generated it is closed, re-executed, or used to retrieve the next
result from a sequence of multiple results.
This means you have to copy the result data into another data structure (like a list, map, whatever suits your needs) before closing the database connection.
Look at this example this will help you. In this example we fetch all data from database on jcombobox actionlistener. Change this according to your need.
class Credit extends JFrame implements ActionListener{
private String value4="0";
private String val="0";
private String val1="0";
private String jama="0",baki="0";
private String nettdate="0",nettb="0",nettbal="0";
private int row=0,count=0,aa=0,bb=0,t1=0;
private String tj1="0",tb1="0",gt1="0";
String h[]={"TID","Date","Jama","Baki","Nett"};
private TableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 0; column < columnCount; column++) {
//columnNames.add(metaData.getColumnName(column));
columnNames.add(h[column]);
}
// data of the table
//Vector<Object> vector = new Vector<Object>();
//Vector<Object> vector1 = new Vector<Object>();
Vector<String> vector1 = new Vector<String>();
Vector<String> vector2 = new Vector<String>();
Vector<Vector<String>> data = new Vector<Vector<String>>();
//Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
//for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
Vector<String> vector = new Vector<String>();
//vector.add(rs.getString(columnIndex));
vector.add(rs.getString(1));
vector.add(rs.getString(2));
vector.add(rs.getString(3));
vector.add(rs.getString(4));
vector.add(rs.getString(5));
// System.out.println(vector);
//}
count++;
data.add(vector);
//System.out.println(data.get(0).get(0));
}
for(int i=0;i<count;i++){
//aa=aa+Integer.parseInt(data.get(i).get(2));
aa=aa+Integer.parseInt(table.getValueAt(i, 2).toString());
System.out.println(table.getValueAt(i, 2).toString());
System.out.println("A:"+aa);
//bb=bb+Integer.parseInt(data.get(i).get(3));
bb=bb+Integer.parseInt(table.getValueAt(i, 3).toString());
System.out.println(table.getValueAt(i, 3).toString());
System.out.println("B:"+bb);
}
tj1=Integer.toString(aa);
System.out.println("TJ:"+tj1);
//header1 = new Vector<String>();
vector1.add("");
vector1.add("Total");
vector1.add(tj1);
tb1=Integer.toString(bb);
//header1 = new Vector<String>();
//header3.add("Total");
vector1.add(tb1);
vector1.add("");
//data1.setSize(table1.getRowCount()+1);
//data1.set(table1.getRowCount()-1, header3);
//data.setSize(count++);
//data.setSize(table.getRowCount()+1);
//data.set(count, header2);
System.out.println("h2:"+vector1);
data.add(vector1);
System.out.println("data:"+data);
//data.set(table.getRowCount()-1, header2);
t1=Integer.parseInt(tb1)-Integer.parseInt(tj1);
gt1=Integer.toString(t1);
System.out.println("GT:"+gt1);
vector2.add("");
vector2.add("Nett Balance");
//header4.add("");
vector2.add("");
vector2.add(gt1);
vector2.add("");
//data.setSize(table.getRowCount()+1);
//data.setSize(count++);
data.add(vector2);
System.out.println("data1:"+data);
//data.set(count, header3);
//data.set(table.getRowCount()-1, header3);
//header2.add("");
count=0;
aa=0;
bb=0;
t1=0;
tj1="0";
tb1="0";
gt1="0";
return new DefaultTableModel(data, columnNames);
}
private static final int GAP = 5;
private static final Font BTN_FONT = new Font(Font.DIALOG, Font.PLAIN, 15);
private JPanel mainPanel = new JPanel();
JButton add,cancel,show,search,print,update,delete,net;
JTextField jTextField,jTextField1,jTextField2,jTextField3,jTextField4,jTextField5;
JComboBox jComboBox;
String Select[]={"Select"};
Object name,s1;
String an="0",nam="0",mono="0",cit="0";
int token=0,tid=1,a,stid=0;
JFrame f;
AbstractAction action;
private String id;
Connection con=null;
Statement st=null;
ResultSet rs=null;
//private String stid;
JPanel tablePanel;
DefaultTableModel model;
DefaultTableModel model1;
JTable table,table3;
private Vector<Vector<String>> data; //used for data from database
private Vector<Vector<String>> data1; //used for data from database
private Vector<String> header; //used to store data header
private Vector<String> header2; //used to store data header
private Vector<String> header3;
private Vector<String> header4;
private JLabel jlab4,jlab5,jlab6,jlab7;
Credit(JFrame frm){
Toolkit tk=Toolkit.getDefaultToolkit();
Image img=tk.getImage("1.jpg");
setIconImage(img);
JPanel creditPanel = createPanel1("Customer Credit & Debit Amount");
tablePanel = createPanel2("Customer Credit & Debit Table");
creditPanel.setBackground(Color.WHITE);
tablePanel.setBackground(Color.WHITE);
mainPanel.setLayout(new BorderLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
mainPanel.add(creditPanel, BorderLayout.PAGE_START);
mainPanel.add(tablePanel, BorderLayout.CENTER);
creditPanel.setVisible(true);
mainPanel.setBackground(Color.BLACK);
frm.add(mainPanel);
}
private JPanel createPanel2(String title){
tablePanel=new JPanel();
tablePanel.setLayout(new BoxLayout(tablePanel,BoxLayout.Y_AXIS));
header = new Vector<String>();
header.add("TID");
header.add("Date");
header.add("Jama");
header.add("Baki");
header.add("Nett");
header4 = new Vector<String>();
header4.add("A/C No.");
header4.add("Name");
//header4.add("Date");
header4.add("Mobile");
header4.add("City");
model=new DefaultTableModel(data,header);
model1=new DefaultTableModel(data1,header4);
table = new JTable(model);
table3 = new JTable(model1);
table.setRowSorter(new TableRowSorter(model));
table.setRowHeight(30);
table3.setRowHeight(30);
table.setFont(new Font("Times New Roman",Font.BOLD,15));
table3.setFont(new Font("Times New Roman",Font.BOLD,15));
table.getTableHeader().setFont( new Font( "Times New Roman" , Font.BOLD, 15 ));
table3.getTableHeader().setFont( new Font( "Times New Roman" , Font.BOLD, 15 ));
table.setDefaultRenderer(Object.class, new TableCellRenderer(){
table3.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table3.getColumnModel().getColumn(0).setPreferredWidth(123);
table3.getColumnModel().getColumn(1).setPreferredWidth(250);
table3.getColumnModel().getColumn(2).setPreferredWidth(123);
table3.getColumnModel().getColumn(3).setPreferredWidth(125);
JScrollPane scroll=new JScrollPane(table);
JScrollPane scroll1=new JScrollPane(table3);
scroll1.setPreferredSize(new Dimension(50,63));
JPanel p=new JPanel();
JButton btn=new JButton("Print");
JButton btn1=new JButton("Export");
p.add(btn);
p.add(btn1);
tablePanel.add(p);
tablePanel.add(scroll1);
tablePanel.add(scroll);
tablePanel.setBorder(BorderFactory.createTitledBorder(title));
return tablePanel;
}
private JPanel createPanel1(String title) {
JPanel addUnitPanel = new JPanel();
addUnitPanel.setLayout(new GridLayout(4,1, GAP, GAP));
JLabel jlab=new JLabel("Name:");
jComboBox=new JComboBox(Select);//Select
jlab.setPreferredSize(new Dimension(100,10));
jComboBox.setPreferredSize(new Dimension(150,30));
jComboBox.addActionListener(new ActionListener(){
private int b=0,a=0;
private String tj="0";
private String tb="0";
private int t=0;
private String gt="0";
public void actionPerformed(ActionEvent ae){
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
// ResultSet rs1=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/Program Files/Shop/shop.accdb";
//userID = "Admin";
password = "3064101991";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
Object name=jComboBox.getSelectedItem();
con=DriverManager.getConnection(url);//,"system","manager"
st=con.createStatement();
model.setRowCount(0);
model1.setRowCount(0);
b=0;
a=0;
tj="0";
tb="0";
t=0;
gt="0";
an="0";nam="0";mono="0";cit="0";
DBEngine dbengine = new DBEngine();
data = dbengine.getJamaCustomer(name);
data1 = dbengine.getIdName(name);
System.out.println("data:"+data1);
Object[] d3={data1.get(0).get(0),data1.get(0).
get(1),data1.get(0).get(3),data1.get(0).get(4)};
model1.addRow(d3);
JTable table1=new JTable(data,header);
for(int i=0;i<table1.getRowCount();i++){
Object[] d={data.get(i).get(0),data.get(i).get(1),
data.get(i).get(2),data.get(i).get(3),data.get(i).get(4)};
model.addRow(d);
}
for(int i=0;i<table1.getRowCount();i++){
a=a+Integer.parseInt(data.get(i).get(2));
b=b+Integer.parseInt(data.get(i).get(3));
}
tj=Integer.toString(a);
tb=Integer.toString(b);
Object[] d1={"","Total",tj,tb,""};
model.addRow(d1);
t=Integer.parseInt(tb)-Integer.parseInt(tj);
gt=Integer.toString(t);
Object[] d2={"","Nett Balance","",gt,""};
model.addRow(d2);
table = new JTable(model);
table3 = new JTable(model1);
table.setRowHeight(30);
table3.setRowHeight(30);
JScrollPane scroll=new JScrollPane(table);
JScrollPane scroll1=new JScrollPane(table3);
//scroll.setBackground(Color.red);
tablePanel.add(scroll1);
tablePanel.add(scroll);
rs.close();
// rs1.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
});
JPanel p1=new JPanel();
p1.add(jlab);
p1.add(jComboBox);
addUnitPanel.add(p1);
loadcombo2();
addUnitPanel.setBorder(BorderFactory.createTitledBorder(title));
return addUnitPanel;
}
void loadcombo2()
{
try
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
// ResultSet rs1=null;
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url=null,userID=null,password=null;
String dbFileName=null;
String sql=null;
dbFileName = "C:/Program Files/Shop/shop.accdb";
//userID = "Admin";
password = "3064101991";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";"+
"Pwd="+password+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
st=con.createStatement();
rs= st.executeQuery("select distinct(Name) from ManageCustomer");
//rs1=st.executeQuery("select Unit from AddUnit");
while(rs.next())
{
jComboBox.addItem(rs.getString(1));
//jComboBox1.addItem(rs1.getString(1));
}
rs.close();
// rs1.close();
st.close();
con.close();
}
catch(Exception e)
{
System.out.println("GG"+e);
}
}
#Override
public void actionPerformed(ActionEvent ae){
if(ae.getSource()==print){
//Your print code
}
if(ae.getSource()==Export){
//Add jComboBox.addActionListener code here
}
}
public static void main(String args[]){
JFrame frm=new JFrame("Title");
Credit b=new Credit(frm);
//frm.setSize(650, 236);
frm.setSize(650, 700);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.setLocationRelativeTo(null);
frm.show();
}
}