Sqlite data and Auto created buttons on ScrollPane [closed] - java

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.

Related

Reset JTable depending on content (number of rows)

I have a JTable inside a JPanel which in turn is in a Jframe. The JTable loads users from a table (database in MySQL).
I have a search engine using DNIs in which key-to-key, with a KeyTyped event, is updating the contacts in the table, and show only those that meet the browser pattern (JTextField). If there are only 2-3-4 clients, the table is not resized to the customer size, but fills the rest of the table with a gray background. (see image). How could the lower bound of the table be reset?
Code:
public class Listado_clientes1 extends javax.swing.JFrame{
private TableRowSorter<DefaultTableModel> TRSFiltro;
public Listado_clientes1() {
this.getContentPane().setBackground(Color.orange);
panel_top.setBackground(Color.orange);
tabla_clientes.setPreferredScrollableViewportSize(
new Dimension(tabla_clientes.getPreferredSize().width, tabla_clientes.getRowHeight()*20)
);
try {
DefaultTableModel modelo = new DefaultTableModel();
tabla_clientes.setModel(modelo);
PreparedStatement ps = null;
ResultSet rs = null;
Connection con = Conexiones.conexion_a_BBDD("agenda");
String sql = "SELECT dni, nombre, apellidos, telefono, direccion, ciudad, email FROM clientes";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
ResultSetMetaData rsMd = (ResultSetMetaData) rs.getMetaData();
int cantidadColumnas = rsMd.getColumnCount();
modelo.addColumn("DNI");
modelo.addColumn("NOMBRE");
modelo.addColumn("APELLIDOS");
modelo.addColumn("TLFONO");
modelo.addColumn("DIRECCION");
modelo.addColumn("CIUDAD");
modelo.addColumn("EMAIL");
while (rs.next()) {
Object[] filas = new Object[cantidadColumnas];
for (int i=0; i<cantidadColumnas; i++) {
filas[i] = rs.getObject(i+1);
}
modelo.addRow(filas);
}
} catch (SQLException ex) {
System.err.println(ex.toString());
}
}
/**
* Filtrar: Buscar por DNI.
*/
public void filtrar_dni() {
int columna = 0; //Es la fila del DNI.
TRSFiltro.setRowFilter(RowFilter.regexFilter(textfield_buscar.getText(), columna));
}
private void textfield_buscarKeyTyped(java.awt.event.KeyEvent evt) {
Character letra = evt.getKeyChar();
evt.setKeyChar(Character.toUpperCase(letra));
textfield_buscar.addKeyListener(new KeyAdapter(){
public void keyReleased(final KeyEvent e){
String texto = (textfield_buscar.getText());
textfield_buscar.setText(texto);
filtrar_dni();
}
});
TRSFiltro = new TableRowSorter<DefaultTableModel>((DefaultTableModel) tabla_clientes.getModel());
tabla_clientes.setRowSorter(TRSFiltro);
}
}
Outline / Scheme:
Any time the number of rows in the view of the table changes you need to recalculate the
preferred scrollable viewport size of the table. Once this size is recalculated you need to invoke the layout manager of the panel containing the table:
A reusable method would be something like:
public void resetTablePreferredScrollableViewportSize(JTable table, int maxRows)
{
Dimension size = table.getPreferredSize();
int displayRows = Math.min(table.getRowCount(), maxRows);
size.height = displayRows * table.getRowHeight();
table.setPreferredScrollableViewportSize( size );
Container parent = SwingUtilities.getAncestorOfClass(JPanel.class, table);
parent.revalidate();
parent.repaint();
}
So after setting the row filter you could use:
tabla_clientes.setRowSorter(TRSFiltro);
resetTablePreferredScrollableViewportSize(tabla_clientes, 10);
Now the scroll pane should be sized to display up to 10 rows after which the scrollbar of the scroll pane will appear.
Edit:
I don't know how to put a reproducible example
Then you don't understand what your problem is.
Your question is that you want to:
Reset JTable (size) depending on number of rows
So the data is irrelevant, only the number of rows is relevant.
It is easy to test this because you can create a DefaultTableModel with a specified number of rows.
Below is a simple MRE. To test you:
enter a number in the text field
press enter
The table will be resized to display the specified number of rows. If the number is greater that 10 the table size will be fixed and a scrollbar will appear:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.table.*;
public class SSCCE extends JPanel
{
JTextField textField;
JTable table;
public SSCCE()
{
setBackground(Color.YELLOW);
textField = new JTextField(5);
add(textField);
table = new JTable(new DefaultTableModel(0, 4));
table.setPreferredScrollableViewportSize(table.getPreferredSize());
add( new JScrollPane(table) );
textField.addActionListener((e) ->
{
int rows = Integer.parseInt( textField.getText() );
table.setModel( new DefaultTableModel(rows, 4) );
resetTablePreferredScrollableViewportSize(table, 10);
});
}
public void resetTablePreferredScrollableViewportSize(JTable table, int maxRows)
{
Dimension size = table.getPreferredSize();
int displayRows = Math.min(table.getRowCount(), maxRows);
size.height = displayRows * table.getRowHeight();
table.setPreferredScrollableViewportSize( size );
Container parent = SwingUtilities.getAncestorOfClass(JPanel.class, table);
parent.revalidate();
parent.repaint();
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// frame.pack();
frame.setSize(500, 250);
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}

Refresh JTable after insert

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.

Garbage value in jtable after adding row dynamically

I have JTable which has few columns.In that I have JComboBox. At program start I want them to be empty.I have one JButton on click action of button i have the code to add row dynamically in table.
But after adding the row i get garbage value in the cell having JComboBox. As shown in below figure :
And here is the code :
Code to add JComboBox in table
// Create columns names
String columnNames[] = { "Item", "Sun Item", "Required Quantity","Price","Gross Amount" };
// Create some data
final String dataValues[][] =
{
{ "", "", "","","", },
};
tableModel = new DefaultTableModel(dataValues, columnNames);
// Create a new table instance
table = new JTable( tableModel );
updateItemCombo();
TableColumn itemColumn = table.getColumnModel().getColumn(0);
itemColumn.setCellEditor(new DefaultCellEditor(comboItem));
public void updateItemCombo(){
Vector<String> s = new Vector<String>();
try{
setConnectin();
String str = "select * from ItemTable";
stmt = conn.createStatement();
rs = stmt.executeQuery(str);
while(rs.next())
{
String nm = rs.getString("Item_Name");
s.add(nm);
}
conn.close();
}catch(Exception e2){
e2.printStackTrace();
}
DefaultComboBoxModel<String> modelData = new DefaultComboBoxModel<String>(s);
comboItem.setModel(modelData);
}
Code to add row dynamically on button click :
btnAddOrder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
tableModel.addRow(dataValues);
tableModel.fireTableDataChanged();
}
});
What should i do to remove this garbage value from table? Please help
The addRow(...) method takes a 1-Dimensional array as a parameter. You are attempting to add a 2-Dimensional array.
Also, do not use:
tableModel.fireTableDataChanged();
it is the job of the TableModel to invoke the appropriate fireXXX() method, which by the way in this case would be fireTableRowsInserted(...).

Adding component to JTable

I want to add JButton in table. I am using table to display database records. Actually I want to add button for each record in table but, the button is not displayed on table. It doesnt show any errors. Please help. Thanks in advance.
package addPanel;
import java.sql.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class panelShowData extends JPanel
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
String url = "jdbc:mysql://localhost:3306/records";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
JScrollPane scrollPane;
JTable table;
DefaultTableModel tableModel;
String nameSearch="";
public panelShowData()
{
this.setLayout(null);
setVisible(true);
setBounds(0, 200, 500, 450);
}
public void searchData( String nameSearch)
{
tableModel = new DefaultTableModel();
try
{
Class.forName( driver ).newInstance( );
connection = DriverManager.getConnection( url, userName, password );
statement = connection.createStatement( ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE );
resultSet = statement.executeQuery( "select * from registration where firstname='"
+ nameSearch
+ "'or lastname ='"
+ nameSearch + "'" );
System.out.println( "Query executed" );
System.out.println( "nameSearch="+nameSearch );
String firstName;
String lastName;
int id;
JButton add=new JButton("ADD");
while ( resultSet.next( ) )
{
System.out.print( resultSet.getString( 2 ) + "\t" );
System.out.print( resultSet.getString( 4 ) + "\n" );
firstName = resultSet.getString( 2 );
lastName = resultSet.getString( 4 );
id = resultSet.getInt(1);
String[ ] columnName = { "Id","First Name", "Last Name","click" };
Object[ ] data = { id, ""+firstName, "" + lastName, add };
System.out.println("Names is:"+firstName);
tableModel.setColumnIdentifiers( columnName );
tableModel.addRow( data );
tableModel.fireTableDataChanged();
}
table = new JTable( tableModel );
table.setEnabled(false);
scrollPane = new JScrollPane( table );
scrollPane.setBounds( 10, 10, 350, 100 );
scrollPane.revalidate();
scrollPane.repaint();
add( scrollPane );
connection.close( );
}
catch (Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog( null, "Record Not Found",
"Sorry", JOptionPane.ERROR_MESSAGE );
}
}
}
all code lines in your post are important reasons, why ResultSetTableModel, TableFromDatabase (and/or to invoked JDBC from SwingWorker, Runnable#Thread) are there
never to call tableModel.fireTableDataChanged();,
outside XxxTableModel defintion
DefaultTableModel has implemented this notifier and correctly
your code required to override this notifiers because talking about Concurency in Swing (Oracle tutorial), again about my point 1st.
everything important is there, please to read this answer about ListModel and JList, all points, the same issue,
JPanel has FlowLayout implemented in API, no reason to use NullLayout, change that to BorderLayout
override getPreferredSize for reasonable Dimension for JPanel, contains JTable wrapped in JScrollPane
JButton added in JTable is here solved a few times

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