How to trigger Jtable update after delete or insert in DB? - java

I don't know how to refresh data in JTable after delete or after insert from other JDialog. I tried to initiate with calling tabela(); after delete to refresh data in JTable but that don't work.
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class LekariD extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTable table;
private String lekar;
private DefaultTableModel model1;
public static void main(String[] args) {
try {
LekariD dialog = new LekariD();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
dialog.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
Connection con = null;
public void tabela () {
Vector<Object> columnNames = new Vector<Object>();
Vector<Object> data = new Vector<Object>();
try {
String sql = "Select * from lekari";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery( sql );
java.sql.ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
columnNames.addElement("Ime Lekara");
columnNames.addElement("LBO");
while (rs.next()) {
Vector<Object> row = new Vector<Object>(columns);
for (int i = 1; i <= columns; i++) {
row.addElement( rs.getObject(i) );
}
data.addElement( row );
}
rs.close();
stmt.close();
} catch (Exception e) {
System.out.println( e );
}
model1 = new DefaultTableModel(data, columnNames) {
#Override
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;
}
};
}
/**
* Create the dialog.
*/
public LekariD() {
con = DatabaseConnector.dbConnector();
tabela();
setBounds(100, 100, 514, 654);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
contentPanel.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 126, 339, 478);
contentPanel.add(scrollPane);
table = new JTable(model1);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
DefaultTableModel model=(DefaultTableModel)table.getModel();
int selectedRowIndex = table.getSelectedRow();
lekar = model.getValueAt(selectedRowIndex, 0).toString();
}
});
table.setFillsViewportHeight(true);
scrollPane.setViewportView(table);
JButton btnNewButton = new JButton("Unos");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
NoviLekarD nl = new NoviLekarD();
nl.setLocationRelativeTo(null);
nl.setVisible(true);
}
});
btnNewButton.setBounds(359, 126, 129, 44);
contentPanel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Brisanje");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from lekari where ime_lekar = '"+lekar+"' ";
Statement stmt1 = con.prepareStatement(query);
stmt1.executeUpdate(query);
stmt1.close();
JOptionPane.showMessageDialog(contentPanel, "Uspešno obrisan podatak", "Brisanje !", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e2) {
System.out.println( e2 );
}
//tabela(); - tried with this but don't work
}
});
btnNewButton_1.setBounds(359, 212, 129, 44);
contentPanel.add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("Izlaz");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
con.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
dispose();
}
});
btnNewButton_2.setBounds(359, 560, 129, 44);
contentPanel.add(btnNewButton_2);
JLabel lblSpisakLekara = new JLabel("Spisak lekara");
lblSpisakLekara.setFont(new Font("Tahoma", Font.BOLD | Font.ITALIC, 18));
lblSpisakLekara.setBounds(10, 42, 139, 38);
contentPanel.add(lblSpisakLekara);
}
}

Let's take a look at what's happening:
When you call tabela() you query the database and create a new DefaultTableModel in model1.
During construction in LekariD() you create a new instance of JTable and provide it with model1.
On change you update the database and call tabela() again. This creates a new DefaultTableModel in model1. Your table still holds the previous DefaultTableModel and queries it whenever you require some data to be drawn.
So, what you have to do after tabela() is to provide your table with the new table model:
table.setModel(model1);
This let's your table know about the new data and makes it recalculate columns, redraw itself, etc.

Related

why data is appearing multiple time after refreshing the button in jdbc swing table?

Here I have created a JTable and surround it with JScrollPane. I have created an update and refresh button so that I can refresh and update the values in the data set. But the problem is with the refresh button whenever I click the button it appears the data more than one time. Like I have 10 data set after updating the name when I refresh the button it is showing again 10 data means a total of 10+10=20 same types of data.
package insertData;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import com.mysql.cj.xdevapi.Statement;
import com.sun.jdi.connect.spi.Connection;
//import com.sun.tools.sjavac.pubapi.PubApi;
import java.awt.Color;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.event.ActionEvent;
import javax.swing.JSplitPane;
public class Table_formate {
private JFrame frame;
private JTextField nametextField;
private JTextField idtextField;
private JTextField textFieldname;
private JTextField textFieldid;
private JTable table;
//Connection connection;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Table_formate window = new Table_formate();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Table_formate() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 539);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
nametextField = new JTextField();
nametextField.setBounds(140, 11, 152, 37);
frame.getContentPane().add(nametextField);
nametextField.setColumns(10);
idtextField = new JTextField();
idtextField.setColumns(10);
idtextField.setBounds(140, 68, 152, 37);
frame.getContentPane().add(idtextField);
JButton btnNewButton = new JButton("Submit");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("com.mysql.jdbc.Driver");//load driver
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root"); //Establish connection
System.out.println("sucess");
String drop="insert into student values(?,?) ";
java.sql.PreparedStatement ps=((java.sql.Connection) connection).prepareStatement(drop);
//System.out.println(ps);
ps.setInt(1, Integer.parseInt(idtextField.getText()));
ps.setString(2, nametextField.getText());
System.out.println("id="+idtextField.getText()+" "+"name="+nametextField.getText());
ps.executeUpdate();
ps.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnNewButton.setBounds(324, 36, 89, 46);
frame.getContentPane().add(btnNewButton);
JLabel lblNewLabel = new JLabel("Name:");
lblNewLabel.setBounds(27, 11, 76, 37);
frame.getContentPane().add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Id:");
lblNewLabel_1.setBounds(27, 68, 76, 37);
frame.getContentPane().add(lblNewLabel_1);
JButton Refreshbtn = new JButton("Refresh");
Refreshbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
DefaultTableModel tableModel=(DefaultTableModel) table.getModel();
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
java.sql.Statement stmt=((java.sql.Connection) connection).createStatement();
System.out.println("connection sucessful");
ResultSet rs= ((java.sql.Statement) stmt).executeQuery("select * from student order by id");
//PreparedStatement ps=connection.prepareStatement("select * from student order by id");
while ( rs.next()) {
String name=rs.getString("name");
int id=rs.getInt("id");
System.out.println(id+ "name="+name);
tableModel.addRow(new Object[] {id,name});
}
stmt.close();
rs.close();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
Refreshbtn.setBounds(122, 139, 89, 30);
frame.getContentPane().add(Refreshbtn);
JLabel lblNewLabel_2 = new JLabel("Name:");
lblNewLabel_2.setBounds(27, 395, 76, 37);
frame.getContentPane().add(lblNewLabel_2);
JLabel lblNewLabel_1_1 = new JLabel("Id:");
lblNewLabel_1_1.setBounds(27, 452, 76, 37);
frame.getContentPane().add(lblNewLabel_1_1);
textFieldname = new JTextField();
textFieldname.setColumns(10);
textFieldname.setBounds(140, 395, 152, 37);
frame.getContentPane().add(textFieldname);
textFieldid = new JTextField();
textFieldid.setColumns(10);
textFieldid.setBounds(140, 452, 152, 37);
frame.getContentPane().add(textFieldid);
JButton btnUpdat = new JButton("update");
btnUpdat.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String drop="update student set name=? where id=?";
try {
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/student","root","root");
PreparedStatement ps=((java.sql.Connection) connection).prepareStatement(drop);
ps.setString(1, textFieldname.getText());
ps.setInt(2, Integer.parseInt(textFieldid.getText()));
ps.executeUpdate();
System.out.println("Record updated");
ps.close();
Refreshbtn.doClick();
} catch (ClassNotFoundException | SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
btnUpdat.setBounds(324, 420, 89, 46);
frame.getContentPane().add(btnUpdat);
JButton btnEdit = new JButton("Edit");
btnEdit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultTableModel tableModel=(DefaultTableModel) table.getModel();
tableModel.fireTableDataChanged();
int row=table.getSelectedRow();
String name=(String) tableModel.getValueAt(row, 1);
String id=(String) tableModel.getValueAt(row, 0).toString();
textFieldid.setText(id);
textFieldname.setText(name);
}
});
btnEdit.setBounds(231, 139, 89, 30);
frame.getContentPane().add(btnEdit);
table = new JTable();
table.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"id", "name"
}
));
table.setBounds(10, 203, 414, 167);
frame.getContentPane().add(table);
}
}
As #Abra mentioned, just clear the contents of your DefaultTableModel when refreshing and before adding the new data as follows:
DefaultTableModel tableModel = (DefaultTableModel) table.getModel();
tableModel.setRowCount(0);
tableModel.setColumnCount(0);
After cleaning the model, populate it again (in this example, adding some random user):
model.addColumn("id");
model.addColumn("Name");
Vector<String> userName = new Vector<>();
userName.add(user);
model.addRow(userName);

How can I make my table update?

I use SQLite. I have 2 JFrames. 1st is consists of table and "Load data", "Edit data". Click on Edit make the new, 2nd JFrame to appear. I want my table to be updated after I make some changes with a help of class Edit. How do I make it? One idea is to use ActionListener so that after I click save, delete or update buttons in JFrame2 method of Jframe 1, which stays for updating of the table(using query), is called. I have tried, but it does not work. I do not want the method of the 1 Jframe to be called in 2nd Jframe, I want this method to be called in 1st Jframe. What are possible solutions?
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
public class Diary extends JFrame {
private JPanel contentPane;
JTable table;
private JButton btnLoadData;
public void refreshTabel(){
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Diary frame = new Diary();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
/**
* Create the frame.
*/
public Diary() {
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 1250, 650);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(34, 58, 1182, 530);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
btnLoadData = new JButton("Load data");
btnLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select * from Diary";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
pst.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadData.setBounds(33, 17, 117, 29);
contentPane.add(btnLoadData);
JButton btnAddData = new JButton("Edit");
btnAddData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
AddData nw = new AddData();
nw.addData();
refreshTabel();
}
});
btnAddData.setBounds(153, 17, 117, 29);
contentPane.add(btnAddData);
}
}
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.sun.glass.events.WindowEvent;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class AddData extends JFrame {
private JPanel contentPane;
private JTextField Date;
private JTextField ExerciseName;
private JTextField Weight;
private JTextField Sets;
private JTextField Reps;
/**
* Launch the application.
* #return
*/
public static void addData() {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddData frame = new AddData();
frame.setVisible(true);
frame.setAlwaysOnTop(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
private JTextField Exercise;
private JTextField N;
/**
* Create the frame.
*/
public AddData() {
setTitle("Edit");
setResizable(false);
connection = Main.dbConnector();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 465, 368);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDate = new JLabel("Date");
lblDate.setBounds(29, 49, 61, 16);
contentPane.add(lblDate);
JLabel ExerciseLabel = new JLabel("Exercise");
ExerciseLabel.setBounds(29, 88, 90, 16);
contentPane.add(ExerciseLabel);
JLabel lblNewLabel_1 = new JLabel("Sets");
lblNewLabel_1.setBounds(29, 169, 61, 16);
contentPane.add(lblNewLabel_1);
JLabel lblReps = new JLabel("Reps");
lblReps.setBounds(29, 213, 61, 16);
contentPane.add(lblReps);
JLabel lblWeight = new JLabel("Weight");
lblWeight.setBounds(29, 126, 61, 16);
contentPane.add(lblWeight);
Date = new JTextField();
Date.setBounds(169, 56, 150, 26);
contentPane.add(Date);
Date.setColumns(10);
ExerciseName = new JTextField();
ExerciseName.setBounds(169, 60, 150, 26);
contentPane.add(ExerciseLabel);
ExerciseName.setColumns(10);
Weight = new JTextField();
Weight.setBounds(169, 132, 150, 26);
contentPane.add(Weight);
Weight.setColumns(10);
Sets = new JTextField();
Sets.setBounds(169, 170, 150, 26);
contentPane.add(Sets);
Sets.setColumns(10);
Reps = new JTextField();
Reps.setBounds(169, 208, 150, 26);
contentPane.add(Reps);
Reps.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "insert into Diary (Date, Exercise, Weight, Sets, Reps) values (?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, Date.getText());
pst.setString(2, Exercise.getText());
pst.setString(3, Weight.getText());
pst.setString(4, Sets.getText());
pst.setString(5, Reps.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Saved");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnSave.setBounds(29, 261, 117, 29);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "update Diary set N ='"+N.getText()+"', Exercise ='"+Exercise.getText()+"', Weight ='"+Weight.getText()+"', Sets ='"+Sets.getText()+"', Reps ='"+Reps.getText()+"' where N ='"+N.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Updated");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
btnUpdate.setBounds(176, 261, 117, 29);
contentPane.add(btnUpdate);
Exercise = new JTextField();
Exercise.setBounds(169, 94, 150, 26);
contentPane.add(Exercise);
Exercise.setColumns(10);
N = new JTextField();
N.setBounds(169, 18, 150, 26);
contentPane.add(N);
N.setColumns(10);
JLabel lblN = new JLabel("N");
lblN.setBounds(29, 23, 61, 16);
contentPane.add(lblN);
JButton Delete = new JButton("Delete");
Delete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "delete from Diary where N = '"+N.getText()+"'";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Deleted");
pst.close();
} catch (Exception ea) {
ea.printStackTrace();
}
}
});
Delete.setBounds(305, 261, 117, 29);
contentPane.add(Delete);
}
}

JTable storing row values as object

At the moment, i have a table that has no row values when it is built, rows are added in after i click the add button. when i click the add button, it will add a row to the table and there are cells for the user to key in values. And then when i click the save button it will store each of the col value into an object. I just wanted to know if there is a more efficient way to do it instead of my if else.
package UI;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JButton;
public class TableManage extends JFrame {
/**
*
*/
private static final long serialVersionUID = 4353951253754938210L;
private JPanel contentPane;
private JTable tablemanage;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TableManage frame = new TableManage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TableManage() {
#SuppressWarnings("unused")
DefaultTableModel manageModel;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
DefaultTableModel model=new DefaultTableModel(
new Object[][] {
},
new String[] {
"NAME", "AGE", "GENDER"
}
);
tablemanage = new JTable(model);
JScrollPane managementpane=new JScrollPane(tablemanage);
managementpane.setBounds(40, 11, 355, 118);
contentPane.add(managementpane);
JButton btnAdd = new JButton("ADD");
btnAdd.setBounds(40, 164, 89, 23);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.addRow(new Object [][] {{null, null,null}});
model.setValueAt(null,tablemanage.getRowCount()-1,0);
}
});
contentPane.add(btnAdd);
JButton btnRemove = new JButton("REMOVE");
btnRemove.setBounds(172, 164, 89, 23);
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(tablemanage.getSelectedRow()<0)
{
JOptionPane.showMessageDialog(null,"Select value To Remove");
}
else
{
model.removeRow(tablemanage.getSelectedRow());
}
}
});
contentPane.add(btnRemove);
JButton btnSave = new JButton("SAVE");
btnSave.setBounds(306, 164, 89, 23);
contentPane.add(btnSave);
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int nu=tablemanage.getRowCount();
int co=tablemanage.getColumnCount();
tablemanage.getSelectionModel().clearSelection();
int i;
int j;
ArrayList<TestingObject> testList=new ArrayList<TestingObject>();
TestingObject test=new TestingObject();
for( i=0;i<nu;i++)
{
test=new TestingObject();
for( j=0;j<co;j++)
{
System.out.println(j);
if(j==0){
test.setName((String) tablemanage.getModel().getValueAt(i,j));
}
else if(j==1){
test.setAge((String) tablemanage.getModel().getValueAt(i,j));
}
else{
test.setGender((String) tablemanage.getModel().getValueAt(i,j));
}
}
testList.add(test);
System.out.println ();
}
for(int k=0;k<testList.size();k++){
testList.get(k).print();
}
}
});
}
}
just remove inner for-loop inside btnSave action lister and put this codes
because your column count is always 3
test=new TestingObject();
test.setName((String) tablemanage.getModel().getValueAt(i,0));
test.setAge((String) tablemanage.getModel().getValueAt(i,1));
test.setGender((String) tablemanage.getModel().getValueAt(i,2));
testList.add(test);
and use this standard code it can be used with jdk 1.8 to print array list values
testList.stream().forEach((var) -> {
System.out.println(var);
});

Adding values to JTable as dynamicly

I have a textbox which sent something to database and jtable list the values from database. But when i add something to database. Jtable dont show it in same time. when i close the program and debug again, it shows that time. I want Jtabel to show textbox value when i click the save button. How can i create a dynamic jtable?
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Topic extends JFrame {
private static final long serialVersionUID = 1L;
JFrame frmTopic;
JPanel pnl, pnl_generaltopic;
static JTextField txt_topic;
JLabel lbl_topicNme, lbl_topicpage;
JButton btn_close, btn_update, btn_save;
public static Connection con = null;
public static ResultSet rs = null;
public static Statement st = null;
static Vector<Vector<String>> data = new Vector<Vector<String>>();
private JScrollPane scrollPane;
private static JTable table;
public Topic() {
pnl_generaltopic = new JPanel();
pnl_generaltopic.setBackground(Color.lightGray);
pnl_generaltopic.setLayout(null);
frmTopic = new JFrame("Topic");
frmTopic.addWindowListener(new WindowAdapter() {
#Override
public void windowOpened(WindowEvent arg0) {
con = Dbconnect.conect();
}
});
frmTopic.setTitle("E-TEST");
frmTopic.setBounds(100, 100, 500, 500);
frmTopic.setVisible(true);
frmTopic.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmTopic.getContentPane().setLayout(new BorderLayout(0, 0));
frmTopic.getContentPane().add(pnl_generaltopic);
topicPanel();
topicTable();
}
public void topicPanel() {
JPanel panel_addingNewTopic = new JPanel();
panel_addingNewTopic.setBounds(10, 0, 464, 203);
pnl_generaltopic.add(panel_addingNewTopic);
panel_addingNewTopic.setLayout(null);
btn_save = new JButton("Save");
btn_save.setBounds(65, 166, 67, 23);
panel_addingNewTopic.add(btn_save);
btn_update = new JButton("Update");
btn_update.setBounds(142, 162, 90, 30);
panel_addingNewTopic.add(btn_update);
btn_close = new JButton("Close");
btn_close.setBounds(240, 162, 90, 30);
panel_addingNewTopic.add(btn_close);
txt_topic = new JTextField();
txt_topic.setBounds(65, 59, 270, 71);
panel_addingNewTopic.add(txt_topic);
lbl_topicNme = new JLabel("Topic Name");
lbl_topicNme.setBounds(10, 65, 150, 59);
panel_addingNewTopic.add(lbl_topicNme);
lbl_topicpage = new JLabel("Topic Page");
lbl_topicpage.setBounds(10, 11, 300, 20);
panel_addingNewTopic.add(lbl_topicpage);
lbl_topicpage.setFont(new Font("arial", Font.BOLD, 15));
btn_close.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frmTopic.dispose();
}
}
);
btn_save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
st = con.createStatement();
String sorgu = "insert into topic " + "(topicname)"
+ "VALUES ('" + txt_topic.getText() + "')";
st.executeUpdate(sorgu);
JOptionPane.showMessageDialog(Topic.this, "Topic was added");
} catch (Exception s) {
System.out.print(s.getMessage());
}
}
}
);
}
public void topicTable() {
scrollPane = new JScrollPane();
scrollPane.setBounds(10, 226, 464, 190);
pnl_generaltopic.add(scrollPane);
Vector<String> headers = new Vector<String>();
headers.add("Topic Name");
getData();
//this is the model which contain actual body of JTable
DefaultTableModel model = new DefaultTableModel(data, headers);
table = new JTable(model);
scrollPane.setColumnHeaderView(table);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
//table=new JTable(model);
//table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
header_size();
//JScrollPane scroll = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
pack();
setResizable(false);
setVisible(true);
}
/**
* Setting the particular Column Size in JTable
*/
public static void header_size() {
TableColumn column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(100);
column = table.getColumnModel().getColumn(0);
column.setPreferredWidth(350);
}
/**
* Fetching Data From MySql Database
* and storing in a Vector of a Vector
* to Display in JTable
*/
private static void getData() {
// Enter Your MySQL Database Table name in below Select Query.
String str = "select * from topics";
Connection con;
ResultSet rs;
Statement st;
try {
con = DriverManager.getConnection("jdbc:mysql://" + "localhost:3306/database", "root", "1234");
st = con.createStatement();
rs = st.executeQuery(str);
while (rs.next()) {
Vector<String> d = new Vector<String>();
d.add(rs.getString("topicname"));
d.add("\n\n\n\n\n\n\n");
data.add(d);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Topic topic = new Topic();
topic.setVisible(false);
}
}
You can use the addRow(...) method of the DefaultTableModel to dynamically add a row of data in the model.
So if the update to your database is successful, then you would invoke the addRow() method.
Also, you should use a PreparedStatement when using SQL. It will make creating the SQL easier since you don't need to worry about the delimiters. Simple example to give you an idea:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, "Name1" );
stmt.setString( 2, textField.getText() );
stmt.executeUpdate();

How to "animate" the adding of rows to a JTable

I want to display the JTable each time a row is added.
The code that i write below add a new row to table , then display the jtable for 2 seconds ,then add another row , then display the table. But the jtable is not displaying ,
It only display after adding all rows
Vector<Object> rowVector = null;
while(rs.next()){
rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
//System.out.print(rs.getString(i));
}
System.out.println(rowVector.toString());
//data.add(rowVector);
model.addRow(rowVector);
JTable table1 = new JTable(model);
JTableHeader header1 = table1.getTableHeader();
table1.setEnabled(false);
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
jpanedisplay.setViewportView(table1);
jpanedisplay.getViewport().setBackground(Color.white);
jpanedisplay.setBorder(BorderFactory.createLineBorder(Color.black));
Thread.sleep(3000);
}
You're creating a new JTable in each iteration, you don't need to do that. Add the model to the table before the loop. And just add rows to the model in the loop
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setEnabled(false);
JTableHeader header1 = table.getTableHeader();
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
jpanedisplay.setViewportView(table1);
jpanedisplay.getViewport().setBackground(Color.white);
jpanedisplay.setBorder(BorderFactory.createLineBorder(Color.black));
...
while(rs.next()){
Vector<Object> rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
//System.out.print(rs.getString(i));
}
model.addRow(rowVector);
// DON'T CALL Thread.sleep();
}
UPDATE
If you dont want the table added until the database task is finished, just use a method
private JTable createTable(ResultSet rs) {
DefaultTableModel model = new DefaultTableModel(columnNames, 0);
JTable table = new JTable(model);
table.setEnabled(false);
JTableHeader header1 = table.getTableHeader();
header1.setResizingAllowed(false);
header1.setReorderingAllowed(false);
header1.setForeground(Color.white);
header1.setBackground(Color.black);
while(rs.next()){
Vector<Object> rowVector = new Vector<Object>();
for(int i=1;i<=columnCount;i++){
rowVector.add(rs.getString(i));
}
model.addRow(rowVector);
}
return table;
}
Then you can just add it to what ever panel
panel.add(new JScrollPane(createTable(rs));
UPDATE #2 after Op explained that they were trying to get a dynamic look the rows being added, instead of all at One time.
I used a java.swing.Timer to add the rows.
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableModel;
public class TestTimerTable {
String[] cols = {"ID", "Name", "Country Code", "District", "Population"};
DefaultTableModel model = new DefaultTableModel(cols, 0);
JTable table = new JTable(model);
ResultSet rs = null;
JButton start = new JButton("Start");
Timer timer = new Timer(0, null);
public TestTimerTable() {
initDB();
JScrollPane scroll = new JScrollPane(table);
scroll.setViewportView(table);
JFrame frame = new JFrame("Test Timer Table");
frame.add(scroll);
frame.add(start, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
timer = new Timer(200, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
String s1 = rs.getString(1);
String s2 = rs.getString(2);
String s3 = rs.getString(3);
String s4 = rs.getString(4);
String s5 = rs.getString(5);
model.addRow(new Object[]{s1, s2, s3, s4, s5});
} else {
((Timer) e.getSource()).stop();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
}
});
}
private void initDB() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/...", "...", "...");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM city");
rs = ps.executeQuery();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestTimerTable();
}
});
}
}

Categories

Resources