How to populate data from a database table into JList?
I can retrieve the data from the database table ok. No Problem but now want to populate those data into the JList. What are the code for this?
I need to know the class and methods for this.

Thanks!!!!

Dani AI

Generated

A practical, modern pattern for 's question is to build a ListModel from the ResultSet off the Event Dispatch Thread and then attach that model to the JList on the EDT. For quick, mutable lists the standard DefaultListModel works well; for reusable or very large datasets a custom AbstractListModel (similar in spirit to 's approach) is preferable. The default JList renderer calls toString() on stored objects, so consider storing POJOs in the model and using a ListCellRenderer for richer displays.

A compact, thread-safe example that formats a timestamp column and sets the model when ready:

import javax.swing.*;
import java.sql.*;
import java.time.*;
import java.time.format.DateTimeFormatter;

JList<String> list = new JList<>(new DefaultListModel<>());

SwingWorker<DefaultListModel<String>, Void> worker = new SwingWorker<>() {
    @Override
    protected DefaultListModel<String> doInBackground() throws Exception {
        DefaultListModel<String> model = new DefaultListModel<>();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        try (Connection conn = DriverManager.getConnection(url, user, pass);
             PreparedStatement ps = conn.prepareStatement("SELECT name, created_at FROM my_table");
             ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                String name = rs.getString("name");
                Timestamp ts = rs.getTimestamp("created_at");
                String when = (ts == null) ? "" : ts.toLocalDateTime().format(fmt);
                model.addElement(name + " (" + when + ")");
            }
        }
        return model;
    }
    @Override
    protected void done() {
        try {
            list.setModel(get()); // runs on EDT
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
};
worker.execute();

Notes and common pitfalls: always close JDBC resources (try-with-resources); prefer rs.getObject(col, LocalDateTime.class) on modern drivers when available; do not update Swing models from background threads (use SwingWorker.publish/process for incremental updates or setModel in done()); for very large result sets use paging or a virtual/custom ListModel to avoid high memory use; use a custom ListCellRenderer rather than assembling long strings when displaying complex objects. This complements 's mutable-model idea and gives a practical, thread-safe pattern while keeping the door open for 's more reusable model-wrapper solution.

Recommended Answers

All 5 Replies

Member Avatar for Member #46692

How to populate data from a database table into JList?
I can retrieve the data from the database table ok. No Problem but now want to populate those data into the JList. What are the code for this?
I need to know the class and methods for this.

Thanks!!!!

Googling for the JList api would be a good start?

How to populate data from a database table into JList?
I can retrieve the data from the database table ok. No Problem but now want to populate those data into the JList. What are the code for this?
I need to know the class and methods for this.

Thanks!!!!

Well, as you can use a Vector to fill the JList, this would be one option.

I chose a slightly bigger solution. I wrote my own DatabaseTransaction class, which basically wraps query(), update() and get[Type]() functions of the JDBC interface.

Then I wrote my own TableModel and ListModel classes, providing a function which takes the transaction class and the column name of the value to be displayed as a parameter (resp. an array of column names and one of column captions for tables).

This works pretty smooth, as long as all of your values can be retreived as a string, which is making trouble with date/time fields.

Wow, that sounds very nice to me. Would be nice if you could share the code. I love reuse!!! :p

THANKS!

Well, as you can use a Vector to fill the JList, this would be one option.

I chose a slightly bigger solution. I wrote my own DatabaseTransaction class, which basically wraps query(), update() and get[Type]() functions of the JDBC interface.

Then I wrote my own TableModel and ListModel classes, providing a function which takes the transaction class and the column name of the value to be displayed as a parameter (resp. an array of column names and one of column captions for tables).

This works pretty smooth, as long as all of your values can be retreived as a string, which is making trouble with date/time fields.

Wow, that sounds very nice to me. Would be nice if you could share the code. I love reuse!!! :p

THANKS!

:) I can imagine, that you love reuse.

The library is not ready, yet. I still need to fix problems with date/time fields (autodetecting field types from tables) and kill dependencies to other librarys used in the project.

Maybe you should simply use the Vector method for now, if you don't want to write a rather big solution like mine.

I'll check if I can post some code snippets for you, to give an idea of what the classes do. But that's not only my decission!!

A JList with a default model could be used as a mutable list.

MutableList myList = new MutableList();
myList.getContents().removeAllElements();

myList.getContents().addElement(something);

import javax.swing.JList;
import javax.swing.DefaultListModel;
public class MutableList extends JList
{
    public MutableList()
    {
        super(new DefaultListModel());
    }
    
    public DefaultListModel getContents()
    {
        return (DefaultListModel)getModel();
    }
    
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.