Refresh JTable after insert - java

Am programming of the application that manage football's players and clubs
I'm real stopped in small part and I couldn't find for it any solution after the try of many ideas.
Simply: I have a JTable and I want to refresh it after any task (Insert, Update or Delete).
That's the code
//for fill the JTable
// class controllApp
class controllApp(){
public DefaultTableModel getCleubData() {
Vector<Vector<String>> data = new Vector<Vector<String>>();
Vector<String> colum = new Vector<String>();
colum.add("id_c");
colum.add("coach");
colum.add("nom_cleub");
colum.add("DATE_CREATION");
colum.add("COULEUR_MAILLOT");
colum.add("COUNTRY");
String query = "select id_c,coach,nom_cleub,date_creation,couleur_maillot,country from CLEUB ORDER BY ID_C";
try {
Connection conn = ReportDriver.connectDB(DB_CONNECTION, DB_USER,
DB_PASSWORD);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
Vector<String> vstring = new Vector<String>();
vstring.add(rs.getString("id_c"));
vstring.add(rs.getString("coach"));
vstring.add(rs.getString("nom_cleub"));
java.sql.Date date = rs.getDate("date_creation");
java.text.DateFormat df = java.text.DateFormat.getDateInstance();
vstring.add(df.format(date));
vstring.add(rs.getString("couleur_maillot"));
vstring.add(rs.getString("country"));
vstring.add("\n\n\n\n\n\n\n");
data.add(vstring);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException ex) {
}
}
}
DefaultTableModel d = new DefaultTableModel(data, colum);
return d;
}
}
//fill frame in other class (frame classe)
// class frame() to call controllAPP.getJoueurdata()
class frame(){
private static JTable table1;
AbstractTableModel model;
model = new controllApp().getJoueurData();
table1 = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table1);
scrollPane.setBounds(6, 29, 807, 297);
panel.add(scrollPane);
}

the solution is to get the Jtable's Model then add Vector data to it, then you have to set the model to the existing JTable.

Related

Use a Java Class to display data to jTable from a jFrame

I would like to know how can I reference a java class in my jFrame form to display data on the jTable. This is a code from my jFrame and I want to know how can I put it in a java class and just reference the class here in the JFrame so I could save space in this JFrame form
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
Something like this?
public class CustomActionHandler {
private JComboBox jComboBox1;
// all the necessary stuff you need for the code to work
CustomActionHandler(JComboBox jComboBox1, etc...) {
this.jComboBox1 = jComboBox1;
// finish passing all the data here
}
public static void JComboActionFollowup() {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
and in your JFrame:
private CustomActionHandler actionhandler = new CustomActionHandler(jComboBox1, etc...)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
actionhandler.JComboActionFollowup();
}

Populating jTable from database based on a column value entered in same table column

I have a jTable. It has 6 column. I need to enter name in column 1 and once I press enter key the other 5 columns must be populated from database. Can anyone help please?
private void jTable2KeyPressed(java.awt.event.KeyEvent evt) {
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// Object s=jTable2.getModel().getValueAt(1, 1);
//System.out.println("Value" +s);
Object Name= jTable2.getModel().getValueAt(1, 1);;
try {
openconn();
PreparedStatement ps;
System.out.println("Val" +Name);
ps = conn.prepareStatement("select * from inventory.addproducts where name='"+Name+"'");
rs= ps.executeQuery();
if(rs.next())
{
String rate=rs.getString(2);
jTable2.getModel().setValueAt(rate, 2, 3);
}
else
{
JOptionPane.showInputDialog("Wrong input");
}
conn.close();
}
catch(Exception ex)
{
}
}}
}
Hope this will make sense how to do it, use DefaultTableModel to populate your JTabel, a simple example, have not tried it out:
private DefaultTableModel model=new DefaultTableModel();
private JTable table=new JTable(model);
private JButton submit =new JButton("Submit");
public void populate(){
submit.addActionListener(e->{model.addRow(new Object[]{textField.getText(),database.getSurname(),database.getAge()});})
}

Sqlite data and Auto created buttons on ScrollPane [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I am trying to do something a bit awkward.
I want to check if there in data in my Sqlite database and according to the number of tables, I want to create buttons in a scroll pane and make it responsive. This is just java "JDBC" not android. I know you guys will tell me to show what i've tried, but I have no idea at all.
Thank you in advance.
Maybe this will get you started.
This code should display the tables from the database in a combo box. Then when you select a table from the combo box is should display all the column in the table.
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class DatabaseInformation extends JFrame implements ActionListener
{
DatabaseMetaData dmd;
ResultSet rs;
ResultSetMetaData md;
int columns;
JComboBox comboBox;
JTable table;
String catalog;
public DatabaseInformation()
{
comboBox = new JComboBox();
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
// Connect to the Database
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
// String url = "jdbc:odbc:Teenergy"; // if using ODBC Data Source name
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/teenergy/data/teenergy.mdb";
String userid = "";
String password = "";
Class.forName( driver );
Connection connection = DriverManager.getConnection( url, userid, password );
dmd = connection.getMetaData();
// Get the first Catalog
// Note: the result set can contain multiple catalogs, just look at the first one
rs = dmd.getCatalogs();
if (rs.next())
{
catalog = rs.getObject(1).toString();
System.out.println( catalog );
}
rs.close();
// Get Tables
rs = dmd.getTables(catalog, null, null, new String[] { "TABLE" });
md = rs.getMetaData();
columns = md.getColumnCount();
while (rs.next())
{
comboBox.addItem( rs.getObject(3) );
}
rs.close();
}
catch(Exception e)
{
System.out.println( e );
}
comboBox.addActionListener( this );
getContentPane().add(comboBox, BorderLayout.NORTH);
// Create table with database data
table = new JTable();
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
}
public void actionPerformed(ActionEvent e)
{
String table = (String)comboBox.getSelectedItem();
displayTableColumns( table );
}
private void displayTableColumns(String tableName)
{
try
{
// Get Columns
rs = dmd.getColumns(catalog, null, tableName, null);
md = rs.getMetaData();
int columns = md.getColumnCount();
Vector columnNames = new Vector(columns);
Vector data = new Vector();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.addElement( md.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 );
}
rs.close();
// Reset Table
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table.setModel( model );
}
catch(Exception e)
{
System.out.println( e );
}
}
public static void main(String[] args)
{
DatabaseInformation frame = new DatabaseInformation();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
I have only ever tested the code on an Access database so I'm not sure what you will need to change for SQLite.

JTable not refreshing after insert using DefaultTableModel

Java program with GUI controlling derby database using DefaultTableModel:
I've a method which successfully inserts a new record to my database. When I restart the program, the new record is visible in JTable (GUI). However, I can't get the JTable to refresh and display the added record promptly.
I've read through a lot of answered questions here but nothing has worked for me so far. Any idea?
GUI class:
public class GUIClients {
ClientDatabase cDB = new ClientDatabase();
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
JScrollPane scrollPane = new JScrollPane(table);
JPanel panel = new JPanel(new BorderLayout());
public JPanel createPanel() {
cDB.createTable(tableModel);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
panel.add(scrollPane);
panel.add(table, BorderLayout.CENTER);
panel.add(table.getTableHeader(), BorderLayout.NORTH);
...
return panel;
}
Insert dialogue with save button:
public class InsertDialog extends GUIClients {
...
saveB = new JButton("Save");
saveB.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
cl = cDB.getClient(InsertDialog.this);
cDB.insert(cl);
tableModel.setRowCount(0);
cDB.createTable(tableModel);
table.setModel(tableModel);
dialogPanel.dispose();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
});
dialogPanel.add(saveB);
...
Method for creating DefaultTableModel from database data:
public class ClientDatabase implements Database {
public static ResultSet rs;
public void createTable(DefaultTableModel d) {
try {
d.addColumn("ID");
d.addColumn("Name");
d.addColumn("Surname");
d.addColumn("Mobile");
d.addColumn("Email");
d.addColumn("Notes");
rs.beforeFirst();
while (rs.next()) {
int id = rs.getInt("ID");
String name = rs.getString("NAME");
String surname = rs.getString("SURNAME");
String mobile = rs.getString("MOBILE");
String email = rs.getString("EMAIL");
String notes = rs.getString("NOTES");
d.addRow(new Object[]{id, name, surname, mobile, email, notes});
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
...
I've a method which successfully inserts a new record to my database.
Then you are also responsible for adding the data to the TableModel at the same time.
You can either use the addRow(...) or insertRow(..) method of the DefaultTableModel to update the date in your TableModel and the JTable will then be updated.
Or the other approach is to redo the query and then use the JTable.setModel(...) method to replace the old TableModel with the new TableModel.
There is no automatic synching of database and TableModel.

dynamic Jtree from database

I have a database table named tree1, which has a table names student_details.This table has 3 columns student_name,student_details,student_phone
Now, am able to retrieve student details from the database but only in static way.
Question is when I insert a new student detail row {student_name,student_details,student_phone} I want it to show on my Jtree. Although Hashmap is the solution I am not able to understand how to use hashmap in a Jtree to create dynamic nodes.
below is the code from which I could do a static Jtree, and i want to make it dynamic. Can anyone tell me how to do this with a code sample?
package tree_try;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.Statement;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.*;
public class SimpleTree extends JFrame
{
public Connection connect = null;
public Statement statement = null;
public Statement statement2 = null;
public Statement statement3 = null;
public Statement statement4 = null;
public Statement statement5 = null;
public Statement statement6 = null;
public ResultSet resultSet = null;
public ResultSet resultSet2 = null;
public ResultSet resultSet3 = null;
public ResultSet resultSet4 = null;
public ResultSet resultSet5 = null;
public ResultSet resultSet6 = null;
public ArrayList arrayList = new ArrayList();
public ArrayList arrayList2 = new ArrayList();
public ArrayList arrayList3 = new ArrayList();
public ArrayList arrayList4 = new ArrayList();
static String store[] = new String[10];
static String store2[] = new String[10];
static String store3[] = new String[10];
//for the panel
static String store4[] = new String[10];
static String store5[] = new String[10];
static String store6[] = new String[10];
static String store7[] = new String[10];
//for panel over
int i=0;
int i1=0;
int i2=0;
int i3=0;
JPanel jp1 = new JPanel();
JPanel jp2 = new JPanel();
JFrame jf1 = new JFrame();
JButton jb1 = new JButton("Save");
JButton jb2 = new JButton("Cancel");
JTextField jt1= new JTextField();
JTextField jt2 = new JTextField();
JTextField jt3= new JTextField();
JTextField jt4 = new JTextField();
JLabel jl0 = new JLabel();
JLabel jl1 = new JLabel("Name : ");
JLabel jl2 = new JLabel("Adress : ");
JLabel jl3 = new JLabel("Phone Number : ");
JLabel jl4 = new JLabel("Other Deatils : ");
JLabel jl5 = new JLabel("");
public static void main(String[] args)
{
new SimpleTree();
}
public SimpleTree()
{
super("Schools database");
WindowUtilities.setNativeLookAndFeel();
addWindowListener(new ExitListener());
//db part
try
{
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
connect = DriverManager.getConnection("jdbc:derby://localhost:1527/treedata1","suraj","suraj");
PreparedStatement statement = connect.prepareStatement("SELECT * from school_details");
PreparedStatement statement2 = connect.prepareStatement("select student_name from student_details where s_id =1");
PreparedStatement statement3 = connect.prepareStatement("select student_name from student_details where s_id =2");
//for the panel display
//PreparedStatement statement5 = connect.prepareStatement("select student_name from student_details where s_id =1");
//PreparedStatement statement6 = connect.prepareStatement("select student_name from student_details where s_id =2");
resultSet = statement.executeQuery();
while (resultSet.next())
{
String sname = resultSet.getString("school_name");
String sid = resultSet.getString("s_id");
arrayList.add(sname);
System.out.println("this is stsement one"+sname);
//arrayList.add(number);
}
resultSet2 = statement2.executeQuery();
while (resultSet2.next())
{
String user2 = resultSet2.getString("student_name");
//int number2 = resultSet2.getInt("s_id");
arrayList2.add(user2);
System.out.println("this is stsement two"+user2);
}
// System.out.println(arrayList);
resultSet3 = statement3.executeQuery();
while (resultSet3.next())
{
String user3 = resultSet3.getString("student_name");
//int number2 = resultSet2.getInt("s_id");
arrayList3.add(user3);
System.out.println("this is stsement three"+user3);
}
System.out.println("this is after statement 3 before 4");
}
catch (Exception e2)
{
e2.printStackTrace();
}
//
Iterator it = arrayList.iterator();
while (it.hasNext())
{
store[i]= (String) it.next();
i++;
//System.out.println(it.next());
}
Iterator it2 = arrayList2.iterator();
while (it2.hasNext())
{
store2[i1]= (String) it2.next();
i1++;
//System.out.println(it.next());
}
Iterator it3 = arrayList3.iterator();
while (it3.hasNext())
{
store3[i2]= (String) it3.next();
i2++;
// System.out.println(it.next());
}
// ------------------------- Visible Settings start here --------------------//
Object[] hierarchy ={"Click for schools",new Object[] {store[0],new Object[] { "Student Details",store2[0],store2[1] } },new Object[] { store[1],new Object[] { "Student Details",store3[0],store3[1]}}};
DefaultMutableTreeNode root = processHierarchy(hierarchy);
final JTree tree = new JTree(root);
// setSize(275, 300);
jp1.setSize(50,50);
jp1.setBackground(Color.WHITE);
jf1.setExtendedState(Frame.MAXIMIZED_BOTH);
jf1.setLayout(new GridLayout(1,2));
jf1.setVisible(true);
jf1.add(new JScrollPane(tree), BorderLayout.WEST);
jf1.add(jp1);
jp1.setLayout(null);
jl0.setBounds(10,1,500,100);
jp1.add(jl0);
jl1.setBounds(55,90,150,100);
jt1.setBounds(225,130, 155, 25);
jp1.add(jl1);
jp1.add(jt1);
jl2.setBounds(55,160, 150, 100);
jt2.setBounds(225,200, 155, 25);
jp1.add(jl2);
jp1.add(jt2);
jl3.setBounds(55,230,150,100);
jt3.setBounds(225,270, 155, 25);
jp1.add(jl3);
jp1.add(jt3);
jl4.setBounds(55,295, 150, 100);
jt4.setBounds(225,330, 155, 25);
jp1.add(jl4);
jp1.add(jt4);
jb1.setEnabled(false);
jb2.setEnabled(false);
jb1.setBounds(150,430, 100, 50);
jb2.setBounds(350,430, 100, 50);
jp1.add(jb1);
jp1.add(jb2);
//-----------------Visible setting stop here--------------------------//
//------------------- Element actions here------------------------//
jt1.addFocusListener(new FocusListener() {
#Override
public void focusGained(FocusEvent e)
{
jb1.setEnabled(true);
jb2.setEnabled(true);
}
#Override
public void focusLost(FocusEvent e)
{
jb1.setEnabled(false);
jb2.setEnabled(false);
}
});
//now for the tree
tree.addTreeSelectionListener(new TreeSelectionListener() {
#Override
public void valueChanged(TreeSelectionEvent e) {
jf1.dispose();
//jl0.setText("Displaying information About : "+tree.getLastSelectedPathComponent().toString());
store7[0]= tree.getLastSelectedPathComponent().toString();
System.out.println("in store 7 of 0"+store7[0]);
dbaction db = new dbaction(store7[0]);
}
});
}
//------------------------------------end of action listening-------------------------
private DefaultMutableTreeNode processHierarchy(Object[] hierarchy)
{
DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);DefaultMutableTreeNode child;
for(int i=1; i<hierarchy.length; i++)
{
Object nodeSpecifier = hierarchy[i];
if (nodeSpecifier instanceof Object[]) // Ie node with children
child = processHierarchy((Object[])nodeSpecifier);
else
child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
node.add(child);
}
return(node);
}
private void close()
{
try {
if (resultSet != null)
{
resultSet.close();
}
if (statement != null)
{
//statement.
}
if (connect != null)
{
connect.close();
}
}
catch (Exception e3)
{
e3.printStackTrace();
}
}
}
of course dbaction.java is where I connect to the database and get details.
It is best to create a data model for the tree. How to Use Trees tutorial has good examples. Also go through Understanding the TreeModel for more details.
By the way, don't execute long running tasks such as accessing database on Event Dispatch Thread . Look into SwingWorker for such tasks.
The JTree tutorial to which Max linked has a section covering 'Dynamic updates of a JTree' which contains the necessary snippets on how to update a TreeModel. The basic idea is that you update the model behind the JTree (the TreeModel) and fire the correct events from the TreeModel. The JTree will listen for those events and update itself accordingly.
Next to that, some other advise:
You should only access Swing components on the Event Dispatch Thread (EDT), which is currently not the case in your example. See the Concurrency in Swing tutorial for more information
The moment you adjust your main method to run on the EDT, you should avoid the long running taks (the database access), as it will block the EDT and leave you with an unresponsive UI (as Max already indicated).
You should avoid the null layout and the manual placing of all your components using setBounds. Otherwise simple things like resizing the UI will results in a messed-up layout. Use a LayoutManager instead. The usage of LayoutManagers is also covered in the 'LayoutManager tutorial' on the Oracle site.

Categories