Simple JTable with DefaultTableModel - java

I use DefaultTableModel for my JTable model, But not show my table!
public class RecordTableGUI2 extends JFrame {
JTable table;
RecordTableModel2 model2;
public RecordTableGUI2() {
model2 = new RecordTableModel2();
table = new JTable(model2);
add(new JScrollPane(table), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new RecordTableGUI2();
}
});
}
}
Model Class:
public class RecordTableModel2 extends DefaultTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
Vector data = new Vector();
Vector column = new Vector();
public RecordTableModel2() {
try {
con = DriverManager.getConnection(dbUrl, "root", "2323");
statement = con.createStatement();
result = statement.executeQuery(query);
int c = result.getMetaData().getColumnCount();
for (int i = 1; i <= c; i++) {
column.add(result.getMetaData().getColumnName(i));
System.out.println(result.getMetaData().getColumnName(i)); //prints correct
}
while (result.next()) {
Vector eachRow = new Vector(c);
for (int i = 1; i <= c; i++) {
eachRow.add(result.getString(i));
System.out.println(result.getString(i)); //prints correct
}
data.add(eachRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
}
}
How to introduce vectors to DefaultTableModel?
Output just show a blank JFrame

Add this at first statement of constructor:
super(data,column);
And declare data and column as static

Related

how to refresh JTable

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.

Why Jtable Does not refresh from other class

I have the following cod!
when i call the fruitsTable() from refreshButton() it refreshes the JTable! but when i call it from another class it does not refresh the Table! bellow is the simplified code
public ResultSet sqlCommand(String sqlStatement) throws SQLException
{
this.sqlStatement = sqlStatement;
ConnectingToMysql fruitsConnection = new ConnectingToMysql();
Connection myConnection = fruitsConnection.ConnectingToMysql();
Statement st = myConnection.createStatement();
ResultSet result = st.executeQuery(sqlStatement);
return result;
}
public Vector<String> getColumnData() throws SQLException
{
ResultSetMetaData metaData = sqlCommand(sqlStatement).getMetaData();
int columnCount = metaData.getColumnCount();
Vector<String> allColumn = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
allColumn.add(metaData.getColumnName(i));
}
return allColumn;
}
public Vector<Vector<String>> getData() throws SQLException
{
ResultSet result = sqlCommand(sqlStatement);
ResultSetMetaData metaData = result.getMetaData();
int columnCount = metaData.getColumnCount();
Vector<Vector<String>> allRow = new Vector<Vector<String>>(columnCount);
while(result.next())
{
Vector<String> eachRow = new Vector<String>();
for(int i = 1; i <= columnCount; i++)
{
eachRow.add(result.getString(i));
}
allRow.add(eachRow);
}
return allRow;
}
public JScrollPane fruitsTable() throws SQLException
{
Vector<String> columnData = getColumnData();
Vector<Vector<String>> rowData = getData();
fruitsTableModel.setDataVector(rowData,columnData);
Font font = new Font("Courier", Font.PLAIN,16);
fruitsTable = new JTable();
fruitsTable.setModel(fruitsTableModel);
fruitsTable.setPreferredScrollableViewportSize(new Dimension(850,310));
fruitsTable.setRowHeight(30);
fruitsTable.setFont(font);
JScrollPane fruitsScrollPane = new JScrollPane(fruitsTable);
dataValue();
return fruitsScrollPane;
}
private JButton refreshButton() throws SQLException
{
JButton refreshButton = new JButton("Refresh Record");
refreshButton.setPreferredSize(new Dimension(100,40));
refreshButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try
{
fruitsTable();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
return refreshButton;
}
and this is the only code from the other class that calls the fruitsTable().
saveButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
try
{
String number = numberTextField.getText();
int ID = Integer.parseInt(number);
String fruit = fruitTextField.getText();
String color = colorTextField.getText();
String taste = tasteTextField.getText();
System.out.println("The value is: " + number + " " + fruit + " " + color + " " + taste);
String sqlText = "Insert into fruits(ID,Fruit,Color,Tast) values(?,?,?,?)";
ConnectingToMysql connectingToMysql = new ConnectingToMysql();
Connection makeConnection = connectingToMysql.ConnectingToMysql();
PreparedStatement pdt = makeConnection.prepareStatement(sqlText);
pdt.setInt(1,ID);
if(fruit.isEmpty())
{
pdt.setNull(2,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(2,fruit);
}
if(color.isEmpty())
{
pdt.setNull(3,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(3,color);
}
if(taste.isEmpty())
{
pdt.setNull(4,java.sql.Types.VARCHAR);
}
else
{
pdt.setString(4,taste);
}
pdt.executeUpdate();
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
}
catch(SQLIntegrityConstraintViolationException e)
{
JOptionPane.showMessageDialog(null, "The 'Number' you entered already exist!", "Error", JOptionPane.ERROR_MESSAGE);
System.out.println(e);
}
GetFruits getFruits = new GetFruits();
getFruits.fruitsTable();
You're creating a new GetFruits object and refreshing it's table instead of updating the existing one. Try creating a class variable of GetFruits so you're using the same instance instead of creating a new one each time. Just guessing since I can't see all the code that contains the action listener.

nullpointer exception on table.getSelectedRow()

I have a class A and a class B.
In class A there is a constructor:
public A() {
getSelectedRow();
}
This constructor calls:
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
Up to here everything works fine!
The class B then calls the method getSelectedRow() like that:
A results = new A();
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
I just want to find out the selected table row from class A. The problem is that I am getting a null pointer exception and i dont know why. if I dont call the method everything works fine.
CLASS A:
public class AllResultsFromDB extends JFrame {
#SuppressWarnings("compatibility:9056676689615464658")
private static final long serialVersionUID = 188850508334531506L;
GUI ins = new GUI();
JTable table;
public AllResultsFromDB(GUI x) {
final Vector columnNames = new Vector();
final Vector data = new Vector();
this.ins = x;
try {
/** Initializing GUI class
* in order to call
* getSelectedTable() method. **/
Login sgui = new Login();
String dburl = "jdbc:oracle:thin:#localhost:1521:ORCL";
Connection connection = DriverManager.getConnection(dburl, sgui.getUsername(), sgui.getPassword());
// Fetch data from table specified by user
String query = "SELECT * FROM " + ins.getSelectedTable() + " ORDER BY id";
System.out.println(query);
Statement stmt = connection.createStatement();
ResultSet rset = stmt.executeQuery(query);
ResultSetMetaData metad = rset.getMetaData();
int columns = metad.getColumnCount();
// This loop gets the names of the columns
for (int i = 1; i <= columns; i++) {
columnNames.addElement(metad.getColumnName(i));
}
// This loop gets the data inside the rows
while (rset.next()) {
final Vector row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.addElement(rset.getObject(i));
}
data.addElement(row);
}
rset.close();
stmt.close();
connection.close();
// Create table with results
table = new JTable(data, columnNames) {
public boolean isCellEditable(int row, int col) {
return false;
}
public Class getColumnClass(int column) {
for (int row = 0; row < getRowCount(); row++) {
Object obj = getValueAt(row, column);
if (obj != null) {
return obj.getClass();
}
}
return Object.class;
}
};
JScrollPane scroll = new JScrollPane(table);
getContentPane().add(scroll);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.SOUTH);
table.addMouseListener(new MouseListener() {
public void mousePressed(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseReleased(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseEntered(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseExited(MouseEvent e) {
//System.out.println(table.getSelectedRow());
}
public void mouseClicked(MouseEvent e) {
getSelectedRow();
if (e.getClickCount() == 2) {
//System.out.println(table.getSelectedRow());
Profile profile = new Profile();
try {
profile.getData();
//wait(500000);
profile.getImage();
} catch (Exception f) {
}
profile.setVisible(true);
}
}
});
} catch (SQLException e) {
}
}
public AllResultsFromDB(int x) {
x = getSelectedRow();
System.out.println(table.getSelectedRow());
}
public int getSelectedRow() {
System.out.println("The row is : " + table.getSelectedRow());
return table.getSelectedRow();
}
}
CLASS B:
public class Profile extends JFrame {
AllResultsFromDB results = new AllResultsFromDB();
public Profile(AllResultsFromDB x) {
this.results=x;
try {
getData();
getImage();
} catch (Exception e) {
e.printStackTrace();
}
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
}
public void getImage() throws Exception {
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
public void getData() throws Exception {
String url = "jdbc:oracle:thin:#localhost:1521:ORCL";
String username = "c##lambros";
String password = "16111111";
Connection conn = null;
try {
System.out.println("YEAH! IT'S: " + results.getSelectedRow());
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, username, password);
String sql = "SELECT foto FROM criminals WHERE id = 5";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet resultSet = stmt.executeQuery();
while (resultSet.next()) {
//String name = resultSet.getString(1);
//System.out.println("Name = " + name);
File image = new File("java.jpg");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[256];
//
// Get the binary stream of our BLOB data
//
InputStream is = resultSet.getBinaryStream(1);
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null && !conn.isClosed()) {
conn.close();
}
}
}
private void jbInit() throws Exception {
this.setSize(new Dimension(816, 380));
JLabel label;
Image img;
ImageIcon pic;
JPanel panel;
img = new ImageIcon("java.jpg").getImage();
pic = new ImageIcon(img);
label = new JLabel("", pic, JLabel.CENTER);
panel = new JPanel(new BorderLayout());
panel.setBounds(new Rectangle(0, 0, 340, 310));
panel.add(label, null);
panel.add(label, BorderLayout.CENTER);
this.getContentPane().setLayout(null);
this.setSize(new Dimension(1148, 336));
this.getContentPane().add(panel, null);
}
}
In the classB since you are creating a new instance
A results = new A();
The value present in the table.getSelectedRow() also gets created newly and will point to null.
So make sure that you do somthing
A results = new A(selectedRow);
and in the constructor of the A,pass the argument to the function
getSelectedRow(selectedRow);
Please note : Make sure that the value of the "table.selectedRow" is maintained
If table is your instance variable in Class A then it might not be initialized when you are trying to access it in constructor of A.
And calling getSelectedRow from the constructor is not making any sense too.
Try to initialize the table variable in constructor instead of calling that method, it should work after it.
This is because the table object is not being initialized.
Try to initialize the table object in constructor....it is a good practice

fireTableRowsUpdated() Not work after update done in JTable [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
In my JTable, after update done, it need to refresh to show the changes:
public class RecordTableGUI extends JFrame implements ActionListener {
private String newName;
private JTable table;
private RecordTableModel myModel;
private JButton editButton;
public RecordTableGUI() {
myModel = new RecordTableModel();
table = new JTable(myModel);
add(new JScrollPane(table), BorderLayout.CENTER);
add(buttonsPanel(), BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(700, 550);
setLocation(300, 80);
setVisible(true);
}
public JPanel buttonsPanel() {
JPanel bPanel = new JPanel();
editButton = new JButton("Edit");
editButton.addActionListener(this);
bPanel.add(editButton);
return bPanel;
}
#Override
public void actionPerformed(ActionEvent e) {
if (table.getSelectedRow() > -1) {
Object oldName = table.getValueAt(table.getSelectedRow(), 1);
UpdateGUIDialog updDialog = new UpdateGUIDialog(this,String.valueOf(oldName), this);
int rowToEdit = table.getSelectedRow();
int rowToModel = table.convertRowIndexToView(rowToEdit);
Object nameID = table.getValueAt(table.getSelectedRow(), 0);
myModel.updateRow(rowToModel, nameID, getNewName());
} else {
JOptionPane.showMessageDialog(null, "Select a row");
}
}
}
Model Class:
public class RecordTableModel extends AbstractTableModel {
Connection con;
Statement statement;
ResultSet result;
String dbUrl = "jdbc:mysql://localhost/mydb";
String query = "Select * from mytable";
ArrayList<String> cols = new ArrayList<String>();
ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
public RecordTableModel() {
try {
con = DriverManager.getConnection(dbUrl, "root", "2323");
statement = con.createStatement();
result = statement.executeQuery(query);
int c = result.getMetaData().getColumnCount();
for (int i = 1; i <= c; i++) {
cols.add(result.getMetaData().getColumnName(i));
}
while (result.next()) {
ArrayList<String> eachRow = new ArrayList<String>();
for (int i = 1; i <= c; i++) {
eachRow.add(result.getString(i));
}
data.add(eachRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
if (statement != null) {
statement.close();
}
} catch (SQLException sqlee) {
sqlee.printStackTrace();
}
}
}
#Override
public int getRowCount() {
return data.size();
}
#Override
public int getColumnCount() {
return cols.size();
}
#Override
public Object getValueAt(int rowIndex, int columnIndex) {
ArrayList<String> selectedRow = data.get(rowIndex);
return selectedRow.get(columnIndex);
}
#Override
public String getColumnName(int col) {
return cols.get(col);
}
public void updateRow(int modelRow, Object nameID, Object newName) {
String query = "update mytable set name = '" + newName + "' where id = " + nameID;
Connection conn;
PreparedStatement pstate;
try {
conn = DriverManager.getConnection(dbUrl, "root", "2323");
pstate = conn.prepareStatement(query);
pstate.executeUpdate();
fireTableRowsUpdated(tableRow, tableRow);
fireTableDataChanged();
fireTableCellUpdated(modelRow, 1);
} catch (SQLException sql) {
sql.printStackTrace();
}
}
Here's your original code:
public class RecordTableModel extends AbstractTableModel {
...
public void updateRow(int modelRow,...) {
String query = ...;
Connection conn;
PreparedStatement pstate;
try {
conn = DriverManager.getConnection(...);
pstate = conn.prepareStatement(query);
pstate.executeUpdate();
fireTableRowsUpdated(modelRow, modelRow); // Not Work!
fireTableDataChanged(); // Not Work!
fireTableCellUpdated(modelRow, 1); // Not Work!
} catch (SQLException sql) {
sql.printStackTrace();
}
}
This code does nothing to the data held by the table model itself, and so it should come as no surprise that calling fireTableXXX(...) does nothing. If the model is unchanged, you can fire anything you want, and the table won't change.
You should perhaps not be using executeUpdate but executeQuery so you can get a ResultSet from the database, and then use it to update the data held by your table model. Then call your appropriate fireTableXXX(...) method.

Using java swing table to update MySQL database values

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.

Categories