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.

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.

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.

 

Author: 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.

Share This Post On
468 ad

Pin It on Pinterest

Share This
More in Application Development, Featured, Java
java application
Connecting Java Application to MySQL Database in NetBeans

Close