Search code examples
javaswinguser-interfacejpaneljtextfield

Refreshing JPanel and Switching JTabbedPane in ActionPerfmored


 private void buttonAddJobActionPerformed(java.awt.event.ActionEvent evt) {                                             

   try {  

       retrieveID();
       String sqlStm = "INSERT INTO Job (employerID,title,description,type,salary,benefits,vacancies,closing,requirement,placement,applyTo,status,posted,location) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)"; 


       pst = conn.prepareStatement(sqlStm);
       pst.setInt(1,id);
       pst.setString(2,txtTitle.getText());
       pst.setString(3,areaDescription.getText());
       pst.setString(4,comboType.getSelectedItem().toString());
       pst.setString(5,txtSalary.getText());
       pst.setString(6,areaBenefits.getText());
       pst.setString(7,txtVac.getText());
       Date close; 
       close = txtDate.getDate();
       pst.setString(8,sdf.format(close));
       pst.setString(9,areaReq.getText());
       pst.setString(10,comboPlace.getSelectedItem().toString());
       pst.setString(11,txtWeb.getText());
       pst.setString(12,comboStatus.getSelectedItem().toString());
       Date now = new Date();   
       pst.setString(13,sdf.format(now));
       pst.setString(14,txtLoc.getText());
       pst.executeUpdate();
       JOptionPane.showMessageDialog(null,"You have successfully added a job");
       //empty all JTextfields
       //switch to another 

I am trying to empty the set of JTextFields in the JPanel, but instead of emptying them one by one, can I just refresh the panel? if so, how do you do this. i tried repaint(), revalidate() these dont work. perhaps I am wrong here. I would also like to switch the JTabbedPane to another Pane, but this doesnt work when I try with this...

JTabbedPane sourceTabbedPane = (JTabbedPane) evt.getSource();
       sourceTabbedPane.setSelectedIndex(0);

can someone show an example code how to do this.


Solution

  • You could loop through all components that are contained in the panel, and if they are text components, clear their value. The code would be something like this:

    private void clearTextFields(Container container)
    {
        int count = container.getComponentCount();
        for (int i = 0; i < count; i++)
        {
            Component component = container.getComponent(i);
            if (component instanceof Container) {
                clearTextFields((Container) component);
            }
            else if (component instanceof JTextComponent) {
                ((JTextComponent) component).setText("");
            }
        }
    }
    

    This method works recursively and takes care of the case when your panel contains another panel which contains the text fields.