There would be no Swing based Java Application that doesn’t make use of THE Database to store data. Hence we’ll directly jump @ an JDBC based JComboBox example which demonstrates how an Element can be added into JCombobox from the Database Table (This will help you to learn about JComboBoxes and JDBC a bit) and How you can refresh the JComboBox (Without closing and re-opening the JFrame) to show the updated list of elements .


Here’s the Java code that demonstrates how you can add and remove an element from the Database and JComboBoxes simultaneously?


/**
*
* @Copyright : Pramod Choudhari | http://TechwayZ.com
*/
package jcb;
import java.awt.HeadlessException;
import java.sql.*;
import javax.swing.JOptionPane;
public class JCBExample extends javax.swing.JFrame {
String link = “jdbc:mysql://127.0.0.1:3306/testDB”;
String uname = “root”;
String passwd = “”;
public JCBExample() {
initComponents();
loadComboBoxData();
}
@SuppressWarnings(“unchecked”)
//
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jComboBox1 = new javax.swing.JComboBox();
jLabel2 = new javax.swing.JLabel();
jTextField1 = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(“JComboBox Example”);
setResizable(false);
jLabel1.setText(“Elements in JComboBox”);
jComboBox1.setToolTipText(“”);
jLabel2.setText(“Element to be Added”);
jTextField1.setText(“jTextField1″);
jButton1.setText(“Add Element”);
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jButton2.setText(“Remove Element”);
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel2)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jComboBox1, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 238, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(20, 20, 20)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton1)
.addComponent(jButton2))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}//
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
addElement();
}
private void removeItem() {
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(link, uname, passwd);
Statement st = con.createStatement();
String query = “delete from jcombobox where element_name=’” + jTextField1.getText() + “‘”;
int status = st.executeUpdate(query);
st.close();
con.close();
jComboBox1.removeAllItems();
loadComboBoxData();
if (status == 1) {
JOptionPane.showMessageDialog(null, “Element ” + jTextField1.getText() + ” was deleted successfully”);
}
} catch (ClassNotFoundException | SQLException | HeadlessException x) {
JOptionPane.showMessageDialog(null, x.getMessage());
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
removeItem();
}
private void loadComboBoxData() {
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(link, uname, passwd);
Statement st = con.createStatement();
String query = “select * from jcombobox”;
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
jComboBox1.addItem(rs.getString(1));
}
rs.close();
st.close();
con.close();
} catch (ClassNotFoundException | SQLException x) {
JOptionPane.showMessageDialog(null, x.getMessage());
}
}
private void addElement() {
try {
Connection con = null;
try {
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(link, uname, passwd);
String query = “insert into jcombobox values(?)”;
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, jTextField1.getText());
int status = ps.executeUpdate();
ps.close();
con.close();
jComboBox1.removeAllItems();
loadComboBoxData();
jComboBox1.setSelectedItem(jTextField1.getText());
if (status == 1) {
JOptionPane.showMessageDialog(null, “Element ” + jTextField1.getText() + ” was added successfully”);
}
} catch (ClassNotFoundException | SQLException | HeadlessException x) {
JOptionPane.showMessageDialog(null, x.getMessage());
}
} catch (Exception x) {
JOptionPane.showMessageDialog(null, x.getMessage());
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JCBExample().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextField jTextField1;
// End of variables declaration
}

Note:-

  • You should save the above code in a file named JCBExample and add the MYSQL JDBC Connetor (MYSQL JDBC Driver) to your application’s classpath (You may get ClassNotFoundException if you don’t add MYSQL JDBC Connector Jar files to your applications classpath ) or you can directly add the classpath to the MYSQL JDBC Driver files while running the above code through the command line

Here is the code to create a table named jcombobox in our testDB database:-

CREATE TABLE `testDB`.`jcombobox` (
`element_name` VARCHAR( 200 ) NOT NULL
) ENGINE = MYISAM ;

Here is the code to insert a test element in our jcombobox table:-
INSERT INTO `testDB`.`jcombobox` (
`element_name`
)
VALUES (
‘Pramod’
);



Now let’s understand our Java Code :-
Below is our constructor :

public JCBExample() {
initComponents();
loadComboBoxData();
}
On Application’s startup (After you compile and execute the JCBExample class), the initComponents method would initialize and add the necessary actionListeners to all the components in the JFrame and we’ll get a window (as shown in the below screenshot) once every line in the initComponents() method has been executed .
As you see in the above screenshot , the JComboBox already has some elements in it … those elements are fetched from the Database by our loadComboBoxData() method .On pressing the Add Element Button actionPerformed event would be fired in which addElement() method is called .The addElement() mehod has the code to insert the user inputted text from the JTextField into our jcombobox table . The executeUpdate() method of the PreparedStatement class returns an integer (1 or 0) . executeUpdate() method returns 1 if insert operation is successful else it returns 0 .

jComboBox1.removeAllItems();
loadComboBoxData();
The above two lines of code in the AddElement() method performs an Ajax like update to our JComboBox . i.e The element inserted in the database was updated in the JComboBox without having the JFrame to be closed and reopened .

jComboBox1.setSelectedItem(jTextField1.getText());
The above line of code would set the selected Item to the newly inserted item .
On Pressing the Remove Element button … actionPerformedevent would be fired in which removeremoveItem() method would be called .The removeItem() method has the code to delete the user inputted text i.e the element (text entered by the user in the JTextField) from or jcombobox table .
the author

I am a post graduate in computer sciences .I have 1+ year experience of working as a Java/J2EE developer in a top notch IT company. I love developing applications and writing technology related articles .