Riempire JComboBox da MySQL

Mattepuffo's logo
Riempire JComboBox da MySQL

Riempire JComboBox da MySQL

Qui vi mostrerò come riempire una JComboBox tenendo separando il valore che si vede a video dal valore attuale che il componente; un pò come una <select> HTML.

In pratica la tabella Autori che ho nel db ha solo due campi, che sono rappresentati dalla classe wrapper qua sotto:

public class Author {

    public int id;
    public String name;

    public Author(String name) {
        this.name = name;
    }

    public Author(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    @Override
    public String toString() {
        return name;
    }
}

Niente di complicato, una semplice classe con un costruttore che accetta due argomenti che rappresentano l'id e il nome degli autori.

A questo punto occupiamoci del db.

Prima la "classica" connessione:

public class DBManager {

    private static DBManager instance = null;
    final static String HOSTLOCAL = "";
    final static String HOST = "";
    final static String DB = "";
    private String defHost = "";
    private String user = "";
    private String pwd = "";
    private static Connection conn = null;

    private DBManager() {
    }

    public static DBManager getInstance() {
        return (instance == null) ? (instance = new DBManager()) : instance;
    }

    public void init(String user, String pwd, boolean localOrNot) {
        this.user = user;
        this.pwd = pwd;
        if (localOrNot) {
            this.defHost = HOSTLOCAL;
        } else {
            this.defHost = HOST;
        }
    }

    public Connection takeConnection() throws ClassNotFoundException, SQLException, IOException {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://" + defHost + ":3306/" + DB + "?user=" + user + "&password=" + pwd + "&noAccessToProcedureBodies=true");
        return conn;
    }

public ArrayList<Author> fillAuthor() throws SQLException, ClassNotFoundException, IOException {
        ArrayList<Author> list = new ArrayList<Author>();
        conn = DBManager.getInstance().takeConnection();
        CallableStatement cstmt = conn.prepareCall("{ CALL getAuthor() }");
        ResultSet rs = cstmt.executeQuery();
        while (rs.next()) {
            list.add(new Author(rs.getInt("author_id"), rs.getString("author_name")));
        }
        cstmt.close();
        return list;
    }

Con un ResultSet eseguiamo la query.

Nel while diciamo di creare un oggetto Author per ogni risultato trovato, passondogli come argomenti l'id e il nome e di memorizzarlo dentro list (che è un ArrayList).

Come vedete il metodo ritorna un ArrayList di tipo Author.

Questo modo di procedere, oltre a seguire i canoni dell'OOP, ci servirà per il nostro scopo principale.

A questo punto, nel mio caso specifico, è meglio creare una classe apposita che si occupi di riempire la JCB in modo da poterla richiamare ogni volta che serve senza dover riscrivere le stesse righe:

public class RiempiCombo {

    private DBManager dbman = DBManager.getInstance();

    public void fillAuthorCombo(JComboBox box) throws SQLException, ClassNotFoundException, IOException {
        box.removeAllItems();
        box.addItem("*");
        ArrayList<Author> listA = dbman.fillAuthor();
        for (Author objA : listA) {
            box.addItem(objA);
        }
    }
}

A questo punto nel JFrame avremo una cosa del genere:

private RiempiCombo rcombo = new RiempiCombo();

private void reset() {
        try {
            rcombo.fillAuthorCombo(comboAuthor);
        } catch (SQLException | ClassNotFoundException | IOException ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

NOTE FINALI

Questo articolo è stato pesantemente rivisto in quanto era abbastanza osboleto.

Se e dovessi trovare altri farò la stessa cosa!!


Condividi

Commentami!