java application

Adding and Removing Components Dynamically from JPanel with MySQL Database

During one of my PHP projects last year, I had to add and remove some components dynamically. Since it was on PHP, I had used jQuery for that purpose. I’m currently working on bringing that project over to Java. The first thing that I looked up on Google was creating dynamic variable names because I need it specifically for that purpose. The answer is a big NO. So, here’s a simple way of adding and removing components dynamically from JPanel in Java.

There is a function called HashMap which brings the same effect to Java but it was more complicated. The component that I needed was two JComboboxes and a Jtextfield. The user would have the option of adding as well as deleting rows. They would also have the option of resetting the frame. As per user requirements, the options in the two JComboBoxes would be retrieved from a MySQL database and the user would put a value in the JTextField. Submitting it will the send the data to another table in the same database.

I actually built two versions of the JFrame – one with MySQL database and the other one simply demonstrates the working of the GUI.

Working of the GUI

The GUI is actually very simple. You have the provision of adding new rows as well as remove rows one by one. A Reset button is also there which will bring back the JFrame to it’s original form. Validation wise you cannot leave any JTextField empty.

Basically, what I have used is array. I have used array of JComboBoxes and JTextField (similar to array of pointers in C). The only disadvantage of using this method is the no. of components that can be added during runtime depends on the size of array. However, if you know the maximum requirement that you need, this is the most easiest approach.

add_remove_java1

I have also added a maximum row feature. For this one I have added the 10 row limitation (variable max_row). The user will be able to add only 10 additional rows.

So, here’s the code.

import java.awt.GridLayout;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class addremove_no_db extends javax.swing.JFrame{
    private javax.swing.JComboBox[] combo1; //array of JComboBoxes
    private javax.swing.JComboBox[] combo2; //array of JComboBoxes
    private javax.swing.JTextField[] text1; //array of JTextFields
    private int count = -1; 
    private int max_row = 10;
    private int empty_count = 0;    
    public addremove_no_db() {
        initComponents(); // Netbeans defined function non-editable    
        setTitle("Adding and Removing Components Dynamically From a JPanel in Java");
        combo1_combo2_text1_array(); // declaring array for new row addition
    }

    private void combo1_combo2_text1_array(){
        combo1 = new JComboBox[10];
        combo2 = new JComboBox[10];
        text1 = new JTextField[10];        
    }
    
    private void addrowActionPerformed(java.awt.event.ActionEvent evt) {  // Add one row at a time                                     
        if(count == max_row-1){
            JOptionPane.showMessageDialog(null, "Maximum of 10 rows can be added","Failed!!",JOptionPane.ERROR_MESSAGE);
            return;
        }
        count++;        
        combo1[count] = new javax.swing.JComboBox(); 
        for(int i=1;i<=5;i++){
            combo1[count].addItem("Item " + i);
        }       
        combo2[count] = new javax.swing.JComboBox(); 
        for(int i=1;i<=5;i++){
            combo2[count].addItem("Item " + i);
        }   
        text1[count] = new javax.swing.JTextField();        
        jPanel2.setLayout(new GridLayout(0,3,20,20));
        jPanel2.add(combo1[count]);
        jPanel2.add(combo2[count]);
        jPanel2.add(text1[count]);
        jPanel2.revalidate();
        jPanel2.repaint();
    }

    private void removerowActionPerformed(java.awt.event.ActionEvent evt) {   // Remove Row Action                                       
        if(count > -1){ // Deleting one row at a time
            jPanel2.remove(combo1[count]);
            jPanel2.remove(combo2[count]);
            jPanel2.remove(text1[count]);
            count--;
            jPanel2.revalidate();
            jPanel2.repaint();
        }
    }

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {   // Cancel Button Action                                     
        System.exit(0);
    }

    private void resetActionPerformed(java.awt.event.ActionEvent evt) { //Reset Button Action                                     
        jTextField1.setText("");
        for(int i=count;i>-1;i--){
            jPanel2.remove(combo1[i]);
            jPanel2.remove(combo2[i]);
            jPanel2.remove(text1[i]);
            jPanel2.revalidate();
            jPanel2.repaint();
        }
        count = -1;
    }                                   

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        if(jTextField1.getText().length()==0)  // Submit button for the register form
            JOptionPane.showMessageDialog(null, "Empty fields detected ! Please fill up all fields","Failed!!",JOptionPane.ERROR_MESSAGE);      
        else if(count > -1){            
            for(int i=0;i<=count;i++){
                if(text1[count].getText().length()==0)  
                    empty_count++;                
            }
            if(empty_count > 0){
                JOptionPane.showMessageDialog(null, "Empty fields detected ! Please fill up all fields","Failed!!",JOptionPane.ERROR_MESSAGE); 
                empty_count = 0; // resetting the count
            }
            else
                JOptionPane.showMessageDialog(null, "No database connection for this application","Failed!!",JOptionPane.ERROR_MESSAGE);
        }
        else
            JOptionPane.showMessageDialog(null, "No database connection for this application","Failed!!",JOptionPane.ERROR_MESSAGE);        
    }
                                      
    public static void main(String args[]) {
      java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new addremove_no_db().setVisible(true);
            }
        });
    }
     // Variables declaration - do not modify                     
    private javax.swing.JButton addrow;
    private javax.swing.JButton cancel;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton removerow;
    private javax.swing.JButton reset;
    private javax.swing.JButton submit;
    // End of variables declaration                   
}

Working of GUI with MySQL Database

Since you have news rows being added during runtime, you need to access all of them to submit them to the database. This is where the array really comes into work.

add_remove_java2

So, here’s the code.

import java.awt.GridLayout;
import java.sql.*;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class addremove extends javax.swing.JFrame {

    private javax.swing.JComboBox[] combo1; //array of JComboBoxes
    private javax.swing.JComboBox[] combo2; //array of JComboBoxes
    private javax.swing.JTextField[] text1; //array of JTextField
    private int count = -1;
    private int max_row = 10;
    private int empty_count = 0;
    
    public addremove() {
        initComponents(); // Netbeans defined function non-editable        
        combo1_combo2_db_connection(); // retrieving options for the comboboxes from the db
        combo1_combo2_text1_array(); // declaring array for new row addition
    }

    private void combo1_combo2_db_connection(){ 
       try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo?" + "user=root&password=");
            PreparedStatement pst = conn.prepareStatement("Select items from combo1");
            ResultSet rs = pst.executeQuery();             
            while(rs.next())                   
                jComboBox1.addItem(rs.getString(1));           
            PreparedStatement pst2 = conn.prepareStatement("Select items from combo1");
            ResultSet rs2 = pst2.executeQuery();          
            while(rs2.next())           
                jComboBox2.addItem(rs2.getString(1));                        
        }
        catch(Exception e){
            e.printStackTrace();
        } 
    }
    
    private void combo1_combo2_text1_array(){
        combo1 = new JComboBox[10];
        combo2 = new JComboBox[10];
        text1 = new JTextField[10];        
    }
    
    private void reset(){
        jTextField1.setText("");
        for(int i=count;i>-1;i--){
            jPanel2.remove(combo1[i]);
            jPanel2.remove(combo2[i]);
            jPanel2.remove(text1[i]);
            jPanel2.revalidate();
            jPanel2.repaint();            
        }
        count = -1;
    }

    private void addrowActionPerformed(java.awt.event.ActionEvent evt) {                                       
        if(count == max_row-1){  // maximum of 10 rows can be added
            JOptionPane.showMessageDialog(null, "Maximum of 10 rows can be added","Failed!!",JOptionPane.ERROR_MESSAGE);
            return;
        }        
        count++;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo?" + "user=root&password=");
            PreparedStatement pst = conn.prepareStatement("Select items from combo1");
            ResultSet rs = pst.executeQuery(); 
            combo1[count] = new javax.swing.JComboBox();
            while(rs.next())                   
                combo1[count].addItem(rs.getString(1));            
            combo2[count] = new javax.swing.JComboBox();
            PreparedStatement pst2 = conn.prepareStatement("Select items from combo1");
            ResultSet rs2 = pst2.executeQuery();          
            while(rs2.next())           
                combo2[count].addItem(rs2.getString(1));                        
        }
        catch(Exception e){
            e.printStackTrace();
        }                
        text1[count] = new javax.swing.JTextField();      
        jPanel2.setLayout(new GridLayout(0,3,20,20));    
        jPanel2.add(combo1[count]);
        jPanel2.add(combo2[count]);
        jPanel2.add(text1[count]);     
        jPanel2.revalidate();
        jPanel2.repaint();
    }                                      

    private void removerowActionPerformed(java.awt.event.ActionEvent evt) {                                          
        if(count > -1){            
            jPanel2.remove(combo1[count]);
            jPanel2.remove(combo2[count]);
            jPanel2.remove(text1[count]);
            count--;
            jPanel2.revalidate();
            jPanel2.repaint();
        }
    }                                         

    private void submitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        if(jTextField1.getText().length()==0)  // checking if the first textfield is empty
            JOptionPane.showMessageDialog(null, "Empty fields detected ! Please fill up all fields","Failed!!",JOptionPane.ERROR_MESSAGE);      
        else if(count > -1){        // if additional rows are there    
            for(int i=0;i<=count;i++){
                if(text1[count].getText().length()==0)  
                    empty_count++;                
            }
            if(empty_count > 0){
                JOptionPane.showMessageDialog(null, "Empty fields detected ! Please fill up all fields","Failed!!",JOptionPane.ERROR_MESSAGE); 
                empty_count = 0; // resetting the count
                return;
            }
            else{
                try{
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo?" + "user=root&password=");
                    PreparedStatement pst = conn.prepareStatement("Insert into results1(combo1,combo2,text1) values(?,?,?)");
                    pst.setString(1,(String)jComboBox1.getSelectedItem());
                    pst.setString(2,(String)jComboBox2.getSelectedItem());
                    pst.setString(3,jTextField1.getText());
                    int rows_affected = pst.executeUpdate();
                    for(int i=0;i<=count;i++){                       
                        pst.setString(1,(String)combo1[i].getSelectedItem());
                        pst.setString(2,(String)combo2[i].getSelectedItem());
                        pst.setString(3,text1[i].getText());
                        rows_affected = rows_affected + pst.executeUpdate();                        
                    }                    
                    if(rows_affected > 0){
                        JOptionPane.showMessageDialog(null,"Data Submitted successfully");
                        reset();
                    }
                }
                catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
        else{       //if no additional rows are presemt
            try{
                Class.forName("com.mysql.jdbc.Driver");
                Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo?" + "user=root&password=");
                PreparedStatement pst = conn.prepareStatement("Insert into results1(combo1,combo2,text1) values(?,?,?)");
                pst.setString(1,(String)jComboBox1.getSelectedItem());
                pst.setString(2,(String)jComboBox2.getSelectedItem());
                pst.setString(3,jTextField1.getText());
                int rows_affected = pst.executeUpdate();
                if(rows_affected > 0){
                    JOptionPane.showMessageDialog(null,"Data Submitted successfully");
                    reset();
                }
            }
            catch(Exception e){
                e.printStackTrace();
            }
        }
    }                                      

    private void resetActionPerformed(java.awt.event.ActionEvent evt) { // Reset Button Action                                     
        jTextField1.setText("");
        for(int i=count;i>-1;i--){
            jPanel2.remove(combo1[i]);
            jPanel2.remove(combo2[i]);
            jPanel2.remove(text1[i]);
            jPanel2.revalidate();
            jPanel2.repaint();            
        }
        count = -1;
    }                                     

    private void cancelActionPerformed(java.awt.event.ActionEvent evt) { //Cancel Button Action                                   
        System.exit(0);
    }                                      
        
    public static void main(String args[]) {
         java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new addremove().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton addrow;
    private javax.swing.JButton cancel;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JButton removerow;
    private javax.swing.JButton reset;
    private javax.swing.JButton submit;
    // End of variables declaration                   
}

For the components, I have used a JPanel with GridLayout. The Grid Layout is the easiest. With each new row addition as well as removal of rows, the GridLayout JPanel is automatically resized.

You can download the JAR File for the application for a demo of how it works. Download JAR File.

To learn about how you can connect MySQL Database to Java, read this post.

 

Default image
Lahaul Seth
A programmer and a web developer, he is the founder of Lion Blogger. His main hobbies are web design & development and providing writing services to clients.