I'm trying to allow the user to delete a record/edit a record and then once they've done that they can click refresh and the JTable should update but it doesn't want to! Any ideas?
I have tried repaint, revalidate, validate and none of these work regardless of if i call them on the table, panel or the frame itself.
Thanks in advance :)
public class Test extends JPanel {
public Test(CardLayout card, JPanel panelCont) {
init();
}
public void init() {
System.out.println("this");
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db"); //In this case it connects to the test.db
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT COL1, COL2, COL3, COL4, COL5, COL6"
+ ", COL7, COL8, COL9 FROM DBTEST;");
JFrame frame = new JFrame("TESTDB");
JPanel panel = new JPanel();
JPanel subpan = new JPanel();
JButton delete = new JButton("Delete");
JButton refresh = new JButton("Refresh");
subpan.add(refresh);
subpan.add(delete);
panel.setLayout(new BorderLayout());
JTable table = new JTable(buildTableModel(rs));
table.getTableHeader().setReorderingAllowed(false);
panel.add(new JScrollPane(table), BorderLayout.CENTER);
panel.add(subpan, BorderLayout.SOUTH);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
frame.setSize(1000, 500);
stmt.close();
rs.close();
c.close();
refresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("refreshed");
}
});
delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int selected = table.getSelectedRow();
if (selected == -1) {
JOptionPane.showMessageDialog(null, "No row selected. Please select a row.");
} else {
int reply = JOptionPane.showConfirmDialog(null, "Are you sure you wish to delete "
+ "the selected record? This cannot be undone.", "Delete Confirmation",
JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:test.db");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM VEHICLETEST;");
int y = 0;
int id = 60;
while (rs.next()) {
if (y == selected) {
id = rs.getInt("id");
}
y++;
}
String sql = "DELETE from DBTEST where COL9=" + id + ";";
stmt.executeUpdate(sql);
c.commit();
rs.close();
stmt.close();
c.close();
frame.dispose();
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
}
}
});
} catch (Exception e) {
System.err.println(e.getClass().getName() + ": " + e.getMessage());
System.exit(0);
}
}
public static DefaultTableModel 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 = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
}
Related
Hi so i was wondering why my the Jtable didnt have any column title however it does have the data from my postgres db
I want to be able to choose a column title for each data
public class aaaaa extends JFrame {
private JPanel contentPane;
private static JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
Connection c = null;
Statement stmt = null;
try{
Class.forName("org.postgresql.Driver");
c = DriverManager
.getConnection("jdbc:postgresql://localhost:5432/MovieDatabase",
"postgres", "password");
c.setAutoCommit(false);
System.out.println("Opened database successfully");
stmt = c.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT * FROM film" );
table = new JTable(buildTableModel(rs));
while ( rs.next() ) {
int filmid = rs.getInt("filmid");
String filmtitle = rs.getString("filmtitle");
int filmyear = rs.getInt("filmyear");
String filmgenre = rs.getString("filmgenre");
System.out.println( "ID = " + filmid );
System.out.println( "TITLE = " + filmtitle );
System.out.println( "YEAR = " + filmyear );
System.out.println( "GENRE = " + filmgenre );
System.out.println();
}
rs.close();
stmt.close();
c.close();
}catch ( Exception e ) {
System.err.println( e.getClass().getName()+": "+ e.getMessage() );
System.exit(0);
}
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
aaaaa frame = new aaaaa();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public aaaaa() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 411);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table.setBounds(10, 11, 414, 350);
contentPane.add(table);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 414, 350);
contentPane.add(scrollPane);
}
public static DefaultTableModel 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 = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
}
Thanks for ur help.
You are using your table outside of a scrollpane. If you really wish to use the JTable in a standalone view, you can get the headers using getTableHeader():
JTableHeader header = table.getTableHeader();
And then add the header to where you want it to be.
The other, more prefered, way would be to simply add the table to a scrollpane:
contentPane.add(new JScrollPane(table));
See here:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JTable.html
Note that if you wish to use a JTable in a standalone view (outside of a JScrollPane) and want the header displayed, you can get it using getTableHeader() and display it separately.
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 have seen similar questions here, on the stackoverflow but anyway I couldn't resolve my problem with these answers.
What i would like to do:
click double on cell in the JTable (which is editable thanks to isCellEditable method)
save new value of a cell in my custom TableModel to print this new value
update data in my database (SQlite)
What I have done:
this is my custom TableModel
.
import javax.swing.table.AbstractTableModel;
public class KierunkiTableModel extends AbstractTableModel {
private boolean DEBUG = false;
private String[] columnNames = { "Id", "Data Wstawienia",
"Data Modyfikacji", "Kierunek", "Opis" };
private Object[][] data = DodEdKierunki.populateData(DodEdKierunki.count);
#Override
public int getRowCount() {
return data.length;
}
#Override
public int getColumnCount() {
return columnNames.length;
}
#Override
public boolean isCellEditable(int row, int col) {
return true;
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
#Override
public String getColumnName(int columnIndex) {
return columnNames[columnIndex];
}
public void setValueAt(Object value, int row, int col) {
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
this is my JPanel where I print my JTable:
.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import baza.danych.DBConnector;
public class DodEdKierunki extends JPanel implements ActionListener {
private JButton dodaj;
private JButton edytuj;
private JButton next;
private JButton previous;
static JTable table;
static Object[][] data = new Object[1][5];
static int count = setValue();
public DodEdKierunki() {
dodaj = new JButton("Dodaj");
edytuj = new JButton("Edytuj");
next = new JButton("Pokaż kolejne 5");
previous = new JButton("Pokaż poprzednie 5");
setLayout(new FlowLayout());
dodaj.addActionListener(this);
edytuj.addActionListener(this);
next.addActionListener(this);
previous.addActionListener(this);
add(dodaj);
add(edytuj);
add(next);
add(previous);
table = new JTable(new KierunkiTableModel());
table.setFillsViewportHeight(true);
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(100);
table.getColumnModel().getColumn(3).setPreferredWidth(130);
table.getColumnModel().getColumn(4).setPreferredWidth(130);
table.setEnabled(true);
add(table.getTableHeader(), BorderLayout.PAGE_START);
add(table, BorderLayout.CENTER);
}
#Override
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == dodaj) {
new DodajKierunekFrame();
} else if (source == edytuj) {
new EdytujKierunekJFrame();
} else if (source == next) {
DBConnector db = new DBConnector();
int id = db.getHighestID("Kierunki");
int currId = count + 5;
if (currId <= id) {
count = count + 5;
data = populateData(count);
KierunkiTableModel model = new KierunkiTableModel();
model.fireTableDataChanged();
table.setModel(model);
setLayout(new FlowLayout());
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(130);
table.getColumnModel().getColumn(2).setPreferredWidth(130);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(130);
table.repaint();
db.closeConnection();
}
} else if (source == previous) {
if (count > 5) {
count = count - 5;
data = populateData(count);
KierunkiTableModel model = new KierunkiTableModel();
model.fireTableDataChanged();
table.setModel(model);
setLayout(new FlowLayout());
table.getColumnModel().getColumn(0).setPreferredWidth(30);
table.getColumnModel().getColumn(1).setPreferredWidth(130);
table.getColumnModel().getColumn(2).setPreferredWidth(130);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(130);
table.repaint();
}
}
}
static Object[][] populateData(int count) {
DBConnector db = new DBConnector();
Object[][] lista = db.selectKierunki(count, "Kierunki");
db.closeConnection();
return lista;
}
private static int setValue() {
DBConnector db = new DBConnector();
int value = db.getHighestID("Kierunki");
db.closeConnection();
return value;
}
}
My problem is: I can edit a cell but I don't know how to save this changes. So my question is: How to change data model after editing a row in JTable ?
I have read http://download.oracle.com/javase/tutorial/uiswing/components/table.html
Try this
Use DefaultTableModel if you are not
if(ae.getSource()==update){
int row=table.getSelectedRow();
int n=JOptionPane.showConfirmDialog(mainPanel, "Would you like to update the record?", "Confirm", JOptionPane.YES_NO_OPTION);
if (n == JOptionPane.YES_OPTION) {
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:/db.accdb";
url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};"+
"DBQ="+dbFileName+";";
//sql = "SELECT * FROM tblUserProfile";
con=DriverManager.getConnection(url);//,"system","manager"
//con=DriverManager.getConnection("jdbc:odbc:shop");
st=con.createStatement();
rs=st.executeQuery("select * from Credit where TID="+table4.getValueAt(row, 3));
if(rs.next()){
s1=rs.getString(1);
s2=rs.getString(2);//accounno
s3=rs.getString(3);//name
s4=rs.getString(4);
s5=rs.getString(5);//paid
s6=rs.getString(6);//unpaid
}
PreparedStatement smt=con.prepareStatement("select * from Debit where Name=?");
smt.setObject(1, s3);
rs=smt.executeQuery();
if(rs.next()){
u1=rs.getString(1);
u2=rs.getString(2);
u3=rs.getString(3);
u4=rs.getString(4);
u5=rs.getString(5);
u6=rs.getString(6);//unpaid
}
st.executeUpdate("delete from Credit where TID="+table4.getValueAt(row,3));
st.executeUpdate("delete from Debit where Name='"+s3+"'");
tid=Integer.parseInt(table4.getValueAt(row, 3).toString());
date=table.getValueAt(row, 0).toString();
jama=table.getValueAt(row, 1).toString();//s5
baki=table.getValueAt(row, 2).toString();//s6
nett=table4.getValueAt(row, 4).toString();
rs1=st.executeQuery("select * from NettDate where Name='"+s3+"'");
while(rs1.next()){
nettdate=rs1.getString(2);
nettbal=rs1.getString(3);
}
String tpaid=Integer.toString(Integer.parseInt(s5)-Integer.parseInt(jama));
String tunpaid=Integer.toString(Integer.parseInt(s6)-Integer.parseInt(baki));
if(u6.contains("-")){
System.out.println("Contains -");
if(tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("1-"+tupdate);
}else if(!tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("2-"+tupdate);}
else if(tpaid.contains("-")&!tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("3-"+tupdate);
}else{
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("4-"+tupdate);
}
}else{
System.out.println("Not Contains -");
if(tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("1"+tupdate);
}else if(!tpaid.contains("-")&tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("2"+tupdate);}
else if(tpaid.contains("-")&!tunpaid.contains("-")){
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("3"+tupdate);
}else{
tupdate=Integer.toString(Integer.parseInt(u6)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
nettb=Integer.toString(Integer.parseInt(nettbal)+Integer.parseInt(tpaid)-Integer.parseInt(tunpaid));
System.out.println("4"+tupdate);
}
}
// tupdate=Integer.toString(Integer.parseInt(a)+Integer.parseInt(paid)-Integer.parseInt(unpaid));
// }else{
// tupdate=Integer.toString(Integer.parseInt(a)-Integer.parseInt(paid)+Integer.parseInt(unpaid));
// }
int i=st.executeUpdate("insert into Credit values("+tid+",'"+s2+"','"+s3+"','"+date+"','"+jama+"','"+baki+"','"+nett+"')");
st.executeUpdate("insert into Debit values('"+s2+"','"+s3+"','"+u3+"','"+u4+"','"+date+"','"+tupdate+"')");
//if(Integer.parseInt(table.getValueAt(row, 4).toString())==1){
if(Integer.parseInt(table4.getValueAt(row, 4).toString())==1){
st.executeUpdate("delete from NettDate where Name='"+s3+"'");
st.executeUpdate("insert into NettDate values('"+s3+"','"+date+"','"+nettb+"')");
}
if(i==0){
String msg="Record not updated Successfully";
String ss="Sorry..........";
int res=JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog((Component) null,msg,ss,res);
}else{
String msg="Record updated Successfully";
String ss="Congratlations..........";
int res=JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog((Component) null,msg,ss,res);
//dispose();
}
jComboBox.requestFocusInWindow();
model.setRowCount(0);
model1.setRowCount(0);
model2.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(s3);
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 table5=new JTable(data,header3);
for(int i2=0;i2<table5.getRowCount();i2++){
Object[] d={data.get(i2).get(0),data.get(i2).get(1),data.get(i2).get(2),data.get(i2).get(3),data.get(i2).get(4)};
model2.addRow(d);
}
JTable table1=new JTable(data,header);
for(int i1=0;i1<table1.getRowCount();i1++){
Object[] d={data.get(i1).get(0),data.get(i1).get(1),data.get(i1).get(2)};//,data.get(i).get(3),data.get(i).get(4)};
model.addRow(d);
}
for(int i2=0;i2<table1.getRowCount();i2++){
a=a+Integer.parseInt(data.get(i2).get(1));
b=b+Integer.parseInt(data.get(i2).get(2));
}
tj=Integer.toString(a);
tb=Integer.toString(b);
Object[] d1={"Total",tj,tb};//,"",""};
Object[] d11={"Total",tj,tb,"",""};
model.addRow(d1);
model2.addRow(d11);
t=Integer.parseInt(tb)-Integer.parseInt(tj);
gt=Integer.toString(t);
Object[] d2={"Nett Balance","",gt};//,"",""};
Object[] d21={"Nett Balance","",gt,"",""};
model.addRow(d2);
model2.addRow(d21);
jlab7.setText(gt);
tablePanel.repaint();
con.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(ManageCustomer.class.getName()).log(Level.SEVERE, null, ex);
}catch(Exception err){
System.out.println("GG Yes"+err);
}
} else if (n == JOptionPane.NO_OPTION) {
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 * from Credit where TID="+table.getValueAt(row, 0));
rs=st.executeQuery("select * from Credit where TID="+table4.getValueAt(row, 3));
if(rs.next()){
s1=rs.getString(1);
s2=rs.getString(2);//accounno
s3=rs.getString(3);//name
s4=rs.getString(4);
s5=rs.getString(5);//paid
s6=rs.getString(6);//unpaid
}
model.setRowCount(0);
model1.setRowCount(0);
model2.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(s3);
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 table5=new JTable(data,header3);
for(int i2=0;i2<table5.getRowCount();i2++){
Object[] d={data.get(i2).get(0),data.get(i2).get(1),data.get(i2).get(2),data.get(i2).get(3),data.get(i2).get(4)};
model2.addRow(d);
}
JTable table1=new JTable(data,header);
for(int i1=0;i1<table1.getRowCount();i1++){
Object[] d={data.get(i1).get(0),data.get(i1).get(1),data.get(i1).get(2)};//,data.get(i).get(3),data.get(i).get(4)};
model.addRow(d);
}
for(int i2=0;i2<table1.getRowCount();i2++){
a=a+Integer.parseInt(data.get(i2).get(1));
b=b+Integer.parseInt(data.get(i2).get(2));
}
tj=Integer.toString(a);
tb=Integer.toString(b);
Object[] d1={"Total",tj,tb};//,"",""};
Object[] d11={"Total",tj,tb,"",""};
model.addRow(d1);
model2.addRow(d11);
t=Integer.parseInt(tb)-Integer.parseInt(tj);
gt=Integer.toString(t);
Object[] d2={"Nett Balance","",gt};//,"",""};
Object[] d21={"Nett Balance","",gt,"",""};
model.addRow(d2);
model2.addRow(d21);
jlab7.setText(gt);
tablePanel.repaint();
jComboBox.requestFocusInWindow();
// rs=st.executeQuery("select TID,Date,Paid,Unpaid,Nett from Credit where Name='"+s3+"' order by Date");
// table.setModel(buildTableModel(rs));
con.close();
//pstmt.close();
JOptionPane.showMessageDialog((Component) null,"You choose not to update the data !");
}catch (ClassNotFoundException err) {
// System.out.println(e);
err.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println(ex);
}
}
}//end btn1
public Vector getJamaCustomer(Object name)throws Exception
{
Vector<Vector<String>> jamacustomerVector = new Vector<Vector<String>>();
Connection conn = dbConnection();
PreparedStatement pre = conn.prepareStatement("select * from Credit where Name='"+name+"' order by TID");
ResultSet rs = pre.executeQuery();//
while(rs.next())
{
Vector<String> jamacustomer = new Vector<String>();
//jamacustomer.add(rs.getString(2)); //Empid
jamacustomer.add(rs.getString(4)); //Empid
jamacustomer.add(rs.getString(5)); //Empid
jamacustomer.add(rs.getString(6)); //Empid
jamacustomer.add(rs.getString(1)); //Empid
jamacustomer.add(rs.getString(7)); //Empid
jamacustomerVector.add(jamacustomer);
}
/*Close the connection after use (MUST)*/
if(conn!=null)
conn.close();
return jamacustomerVector;
//return bakicustomerVector;
}
I could really need your help, I tried to solve this problem for over one week, but haven't found a solution yet.
My Aim: I want to create a table, which can read the Data from a Database. I can also add Data to the DB by inserting it in my program.
My Problem: After inserting the Data i want the Database to refresh, so that it also shows my new record set. But no matter what i tried, it didn't work.
My Code: Here is my Mainframe-Class:
public class Gui_Test extends JFrame {
JButton addMovieButton;
JFrame frame = new JFrame("Movie Database");
JPanel panel;
JMenuBar menubar;
JMenu fileMenu;
JLabel label;
JTable table = new JTable();
MovieTableModel mtm;
public static void main(String[] args) {
Gui_Test test = new Gui_Test();
test.run();
}
public void run() {
// Gui ///
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
panel = new JPanel();
panel.setVisible(true);
panel.setBackground(Color.black);
// Add - Movie Button ///
addMovieButton = new JButton("Add Movie");
addMovieButton.addActionListener(new addMovieButtonListener());
panel.add(addMovieButton);
// Table select ///
mtm = new MovieTableModel();
table.setModel(mtm);
JScrollPane pane = new JScrollPane(table);
frame.getContentPane().add(pane);
frame.getContentPane().add(BorderLayout.WEST, panel);
}
class addMovieButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
AddMoviePanel addmoviepanel = new AddMoviePanel();
addmoviepanel.moviepanel(mtm);
}
}}
Here is my TableModel:
public class MovieTableModel extends AbstractTableModel {
Connection con = null;
Vector columnNames = new Vector();
Vector data = new Vector();
ResultSet rs;
ResultSetMetaData meta;
public MovieTableModel() {
showResult();
}
void showResult() {
Connection con;
try {
con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/...", "sa",
"");
java.sql.Statement stmt = con.createStatement();
String query = "SELECT * FROM movies ORDER BY id DESC";
ResultSet rs = stmt.executeQuery(query);
meta = rs.getMetaData();
int columns = meta.getColumnCount();
// get column names
for (int i = 1; i <= columns; i++) {
columnNames.addElement(meta.getColumnName(i));
}
// get row data
while (rs.next()) {
Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rs.getObject(i));
}
data.addElement(row);
}
if (con != null)
try {
rs.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
#Override
public String getColumnName(int column) {
return columnNames.get(column).toString();
}
#Override
public int getColumnCount() {
try {
return meta.getColumnCount();
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
#Override
public Class getColumnClass(int column) {
// TODO Auto-generated method stub
return getValueAt(0, column).getClass();
}
#Override
public int getRowCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getValueAt(int row, int column) {
return ((Vector) data.get(row)).get(column);
}
#Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
void addRow(final String value1, final String value2, final String value3,
final String value4, final String value5, final String value6,
final String value7) {
try {
Connection con = DriverManager.getConnection(
"jdbc:hsqldb:file:C:/Users/Jonas/workspace/movieDB", "sa",
"");
try {
final java.sql.Statement state = con.createStatement();
try {
state.addBatch("INSERT INTO movies VALUES (DEFAULT, '"
+ value1 + "', '" + value2 + "'," + value3 + ", '"
+ value4 + "', " + value5 + ", '" + value6 + "', '"
+ value7 + "')");
state.executeBatch();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e) {
e.printStackTrace();
}
} catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
} finally {
if (con != null)
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}}
And here is my addMovieFrame, which opens to add new Movies:
public class AddMoviePanel {
MovieTableModel mtm;
JPanel addMoviePanel;
JFrame addMovieFrame;
JTextField value1Input;
JTextField value2Input;
// ... value3 - value7
Connection con = null;
public void moviepanel(MovieTableModel mtm) {
this.mtm = mtm;
addMovieFrame = new JFrame("Add Movie");
addMovieFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMovieFrame.setVisible(true);
addMovieFrame.setSize(550, 300);
addMoviePanel = new JPanel();
GroupLayout layout = new GroupLayout(addMoviePanel);
addMoviePanel.setLayout(layout);
JLabel label1 = new JLabel("label1:");
JLabel label2 = new JLabel("label2");
// ...JLabel 3-7 same as Label 1&2
addMoviePanel.add(label1);
addMoviePanel.add(label2);
// ...add Label 3-7
value1Input = new JTextField();
value2Input = new JTextField();
// ... value3- value7 Input
addMoviePanel.add(value1Input);
addMoviePanel.add(value2Input);
// ... add value3Input - value7Input
JButton ok = new JButton("Ok");
ok.addActionListener(new okActionListener());
addMovieFrame.add(ok);
addMovieFrame.getContentPane().add(addMoviePanel);
// here was just Layout Stuff //
}
class okActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
mtm.addRow(value1Input.getText(), value2Input.getText()
// ... value3Input.getText() - value7Input.getText()
);
mtm.fireTableDataChanged();
addMovieFrame.dispose();
}
}}
I already tried several types and positions of fireXXX-Methods...
Maybe somebody got an idea, how to refresh my jtable, when hitting the OK-Button in my addMovie-Frame? :)
As shown here and discuseed here, only your TableModel should fire table model events. While this is typically done in setValueAt(), you can insert a whole row and fire a single event, as shown here.
This program is used to read data from database. In the database,there are three tables pki17, pki18, pkn18. For viewing different tables,JComboBox is used and it works by changing the TableModel of the table. Also by using tableChanged method I made table editable. When a cell value in the table is changed the corresponding value in the database has to change to.
When I use tableChanged and actionPerformed methods together, value in database doesn’t get changed when I’m editing a cell in the swing table. When I remove actionPerformed method, then I can update database by editing table cells.
I need to have both abilities, to choose a table from the database by using JComboBox and update database values by editing values in the swing table.
I think the problem exists because TableModel of the table is changed in both methods. But I don’t know how to solve it.
public class TableCombobox extends JPanel implements ActionListener, TableModelListener {
static JTable table;
static JComboBox box;
static MyTableModel model;
static Connection con = null;
static Statement stmt = null;
public TableCombobox() throws SQLException {
super(new BorderLayout());
table = new JTable(new MyTableModel("pki18"));
table.setPreferredScrollableViewportSize(new Dimension(500, 400));
table.setFillsViewportHeight(true);
table.getModel().addTableModelListener(this);
JScrollPane scrollPane = new JScrollPane(table);
JPanel menuPanel = new JPanel();
menuPanel.setLayout(new BoxLayout(menuPanel, BoxLayout.Y_AXIS));
menuPanel.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1,
Color.black));
String[] dalykas = { "Chose groop", "pki17", "pki18", "pkn18" };
box = new JComboBox(dalykas);
box.setMaximumSize(new Dimension(150, 25));
box.setAlignmentX(Component.LEFT_ALIGNMENT);
box.addActionListener(this);
box.setSelectedIndex(2);
menuPanel.add(box);
JPanel cards = new JPanel(new CardLayout());
cards.add(scrollPane, "view");
add(menuPanel, BorderLayout.LINE_START);
add(cards, BorderLayout.CENTER);
}
public void tableChanged(TableModelEvent e) {
int row = e.getFirstRow();
int col = e.getColumn();
model = (MyTableModel) e.getSource();
String stulpPav = model.getColumnName(col);
Object data = model.getValueAt(row, col);
Object studId = model.getValueAt(row, 0);
System.out.println("tableChanded works");
try {
new ImportData(stulpPav, data, studId);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
e1.printStackTrace();
}
}
public void actionPerformed(ActionEvent event) {
JComboBox cb = (JComboBox) event.getSource();
String pav = (String) cb.getSelectedItem();
if (pav != "Chose groop") {
try {
model = new MyTableModel(pav);
table.setModel(model);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
private static void GUI() throws SQLException {
JFrame frame = new JFrame("E-gradebook");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new TableCombobox());
frame.pack();
frame.setSize(800, 400);
frame.setVisible(true);
}
public static void main(String[] args) throws SQLException {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/pki18",
"root", "");
GUI();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
}
}
static Connection getConnection() {
return con;
}
}
public class ImportData {
static Connection con = TableCombobox.getConnection();
public ImportData(String a, Object b, Object c)
throws ClassNotFoundException, SQLException {
Statement stmt = null;
try {
String stulpPav = a;
String duom = b.toString();
String studId = c.toString();
System.out.println(duom);
con.setAutoCommit(false);
stmt = con.createStatement();
stmt.addBatch("update pki18 set " + stulpPav + " = " + duom
+ " where studento_id = " + studId + ";");
stmt.executeBatch();
con.commit();
} catch (BatchUpdateException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null)
stmt.close();
con.setAutoCommit(true);
System.out.println("Data was imported to database");
}
}
}
public class MyTableModel extends AbstractTableModel{
static int rowCount;
static Object data [][];
static String columnNames [];
public MyTableModel(String grupName) throws SQLException{
String query ="select Studento_id, vardas_pavarde, 1_semestras,"+
" 2_semestras, egzaminas, bendras_balas "+
"from pki18." + grupName;
ResultSet rs ;
Connection con = TableCombobox.getConnection();
Statement stmt = null;
stmt = con.createStatement();
rs = stmt.executeQuery(query);
rs.last();
rowCount = rs.getRow();
data = new Object[rowCount][6];
rs = stmt.executeQuery(query);
for (int iEil = 0; iEil < rowCount; iEil++){
rs.next();
data[iEil][0] = rs.getLong("Studento_id");
data[iEil][1] = rs.getString("Vardas_Pavarde");
data[iEil][2] = rs.getByte("1_semestras");
data[iEil][3] = rs.getByte("2_semestras");
data[iEil][4] = rs.getByte("Egzaminas");
data[iEil][5] = rs.getByte("bendras_balas");
}
String[] columnName = {"Asmens_kodas","Vardas_Pavarde","1_Semestras"
,"2_Semestras","Egzaminas","Bendras_Balas"};
columnNames = columnName;
}
public int getColumnCount(){
return columnNames.length;
}
public int getRowCount(){
return data.length;
}
public String getColumnName(int col){
return columnNames[col];
}
public Object getValueAt(int row, int col){
return data[row][col];
}
public Class getColumnClass(int col){
return getValueAt(0, col).getClass();
}
public boolean isCellEditable(int row, int col){
return true;
}
public void setValueAt(Object value, int row, int col){
data[row][col] = value;
fireTableCellUpdated(row, col);
}
}
In the constructor, you add the table model listener to the current model only:
table.getModel().addTableModelListener(this);
In the action event, however, you replace the table model:
model = new MyTableModel(pav);
table.setModel(model);
As a consequence, the new table model won't have the listener, and you won't receive notifications any more. Have the actionPerformed method add the listener as well, and your problem should be fixed.