• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 295
  • Last Modified:

JButton takes long time to get data

hello there,

i have a jbutton which when clicked opens a JDialog box and fills the combo box with data from the db.now my problem is sometimes when i click on the jbutton it takes some time to display the jdialog box. this happens  sometimes.i mean in 10 to 4.is there some method i can figure out the cause.

cheers
zolf

address = new JButton("Business... ");
            address.setBounds(25, 155, 100, 20);
            generalPane.add(address);
            address.addActionListener(JButtonActionListener);

==============================

ActionListener JButtonActionListener = new ActionListener()
      {
            public void actionPerformed(ActionEvent e)
            {
                  /*JDialog JPAdd = new AddNewCustomer();
                  JPAdd.setModal(true);
                  JPAdd.show();*/
                  
                  System.out.println("Button Clicked");
                  String str = e.getActionCommand();
                  System.out.println("Button Clicked       "+str);
                  address.setText(str);
                  System.out.println("Button Clicked         after   ");
                  JDialog JPAdd = new FrmAddress(AddNewCustomer.this);
                  JPAdd.setModal(true);
                  JPAdd.setVisible(true);

===================================

public class FrmAddress extends JDialog {

      private JComboBox comboBox;
      private JTextField textField_1;
      private JTextField textField;
      Dimension screen =       Toolkit.getDefaultToolkit().getScreenSize();
      Connection connect = null;
      
      AddNewCustomer addCus;
      /**
       * Create the dialog
       */
      public FrmAddress(AddNewCustomer addNewCus)
      {
            
            super();
            System.out.println("Button Clicked         after  1 ");
            setTitle("Address");
            getContentPane().setLayout(null);
            setBounds(100, 100, 396, 240);
            setResizable(false);
            setLocation((screen.width - 325)/2,((screen.height-383)/2));
            
            addCus = addNewCus;
            connect = MainForm.getDBConnection();
            final JLabel streetLabel = new JLabel();
            streetLabel.setText("Street:");
            streetLabel.setBounds(25, 30, 54, 14);
            getContentPane().add(streetLabel);

            textField = new JTextField();
            textField.setBounds(85, 27, 243, 20);
            getContentPane().add(textField);

            textField_1 = new JTextField();
            textField_1.setBounds(85, 55, 243, 20);
            getContentPane().add(textField_1);

            final JLabel cityLabel = new JLabel();
            cityLabel.setText("City:");
            cityLabel.setBounds(25, 85, 54, 14);
            getContentPane().add(cityLabel);

            System.out.println("Button Clicked         after  2 ");
            String tQuery = "select CityName_Eng from city order by CityName_Eng";
            
            comboBox = mdlFunctions.fillCombo(tQuery,connect,"CityName_Eng");
            
            System.out.println("Button Clicked         after  3 ");
            
=============================================

public static JComboBox fillCombo(String strSQL,Connection sCN,String strFieldName)
      {
             Statement stFC = null;
         ResultSet rsFC = null;
         DefaultComboBoxModel cmbList = new DefaultComboBoxModel();
         try
         {          
               stFC = sCN.createStatement();
             rsFC = stFC.executeQuery(strSQL);
             
              while(rsFC.next())
              {
                        cmbList.addElement(rsFC.getString(strFieldName));
                        System.out.println(rsFC.getString(strFieldName));
              }
         }
         catch(SQLException sqlEx)
         {
              System.out.println("\nError Found in mdlFunctions(fillCombo) 2 :" + sqlEx + "\n");
         }
         finally
         {
              if (rsFC!=null)
              {
                    try
                    {
                          rsFC.close();
                    }
                    catch(SQLException sqlEx)
                  {
                       System.out.println("\nError Found in mdlFunctions(fillCombo) 12 :" + sqlEx + "\n");
                  }
              }
              if (stFC!=null)
              {
                    try
                    {
                          stFC.close();
                    }
                    catch(SQLException sqlEx)
                  {
                       System.out.println("\nError Found in mdlFunctions(fillCombo) 13 :" + sqlEx + "\n");
                  }
                    
              }
         }
         return new JComboBox(cmbList);

      }      
0
zolf
Asked:
zolf
  • 10
  • 5
  • 4
  • +1
3 Solutions
 
objectsCommented:
swing is single threaded, so any long ops such as talking to the database will block the gui
better to use SwingWorker class for long operations
0
 
ellandrdCommented:
is your database locally or on a network?

i would expect for the connect to be very fast regardless.  

when you click the button do you make the DB connect then or when the java application starts.

in the past any slow connecting problems i have had was down to not closing my connection after i open it.

so when your testing your application, each time you click that button, your opening another connection and after a couple of times you will have a couple of connections open that are unnessasary...

can i see your db connection code please...
0
 
zolfAuthor Commented:

but this does not happen everytime.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
zolfAuthor Commented:

this method is in my main class.i call this in its constructor.like this

      public MainForm(){
            //Set the main form title
            super("Enterprise System version 1.0");
            //End set the main form title

            loadSplashScreen();
            //We will dispose now the FormSplash because it is now useless
            FormSplash.dispose();

            //StatusLabel.setBorder(BorderFactory.createTitledBorder(""));
            StatusLabel.setFont(new Font("Dialog", Font.PLAIN, 12));

            initConnection();

=====================================

protected static void initConnection()
      {
            Properties prop = new Properties();
            
            try
            {
                  //FileInputStream fis = new FileInputStream(DEFAULT_PROPERTY_FILE);
                  InputStream fis = MainForm.class.getResourceAsStream("/db.properties");
                  try
                  {
                        prop.load(fis);
                  }
                  finally
                  {
                        fis.close();
                  }
            }
            catch (Exception e)
            {
                  System.err.println("Error loading config file: " + DEFAULT_PROPERTY_FILE);
                  System.exit(1);
            }

            String dbUrl = prop.getProperty("db.connection.protocol") + "//" +
                                    prop.getProperty("db.connection.host") + ":" +
                                    prop.getProperty("db.connection.port")+";";
            
            String dbname = prop.getProperty("db.connection.dbname");
            String dbDriver = prop.getProperty("db.connection.driver");
            String dbUser = prop.getProperty("db.connection.username");
            String dbPassword = prop.getProperty("db.connection.password");
            
             String dbDetail = "databaseName="+prop.getProperty("db.connection.dbname") +";"+
         "user="+prop.getProperty("db.connection.username")+";"+
         "password="+prop.getProperty("db.connection.password");



            System.out.println(dbUrl+" "+ dbDetail);
            try
            {
                  Class.forName(dbDriver).newInstance();
                  connect = DriverManager.getConnection(dbUrl+" "+ dbDetail+" ");
                  
            }
            catch (IllegalAccessException iae)
            {
                  System.err.println(iae.getMessage());
                  System.exit(1);
            }
            catch (InstantiationException ie)
            {
                  System.err.println(ie.getMessage());
                  System.exit(1);
            }
            catch (ClassNotFoundException cnfe)
            {
                  System.err.println(cnfe.getMessage());
                  System.exit(1);
            }
            catch (SQLException sqle)
            {
                  System.err.println(sqle.getMessage());
                  System.exit(1);
            }            
      }
      
      public static Connection getDBConnection()
      {
            return connect;
      }
0
 
zolfAuthor Commented:

my database is local
0
 
ellandrdCommented:
objects has made a very good point above.  have you considered his advise?  I have never used it (actaully i have never heard of it until now) but here is some documentation: https://swingworker.dev.java.net/

Closing JDBC Objects Explicitly: http://www.devx.com/tips/Tip/21601
0
 
zolfAuthor Commented:

whenever i need a connection to the db i call
Connection = null;

class const()
{
connect = MainForm.getDBConnection();
}
0
 
zolfAuthor Commented:

i added this to my fillCombo method.but then when i again clcik on the Jbutton i get Connection is close error.

if (sCN!=null)
              {
                    try
                    {
                          sCN.close();
                    }
                    catch (SQLException sqlEx)
                    {

                          System.out.println("\nError Found in mdlFunctions(fillCombo) 14 :" + sqlEx + "\n");
                    }
              }
0
 
zolfAuthor Commented:

i am doing a simple operation.that is fill a combo box with data when i button is clicked. i have done this many time before but never encountered this problem.
0
 
objectsCommented:
your dialog is not going to get displayed until the db operation is complete.
db ops aren't always going to take the same amount of time
0
 
ellandrdCommented:
>>i get Connection is close error.

is this a nbull pointer exception or SQL exception.

can you hardcode the combobox values into an array and comment out the DB connection part.  test this to see if its any faster.  i guessing it will be as like what objects said above swings are single threaded so it will be slower...
0
 
CEHJCommented:
You would probably be better off caching the connection after having opened it in a background thread at startup. Do the data change often? If not, you could cache data too
0
 
zolfAuthor Commented:

i think objects suggestion makes sense.

can somebody give me what that swing worker do and when is it to be used.
0
 
zolfAuthor Commented:

CEHJ:
can you please give me more details to your suggestion please.
0
 
zolfAuthor Commented:

the combo box gets the city name from the db.there are around 350 cities
0
 
ellandrdCommented:
>>can somebody give me what that swing worker do and when is it to be used.

i posted a link to more information regarding this class above.  here it is again:

https://swingworker.dev.java.net/
0
 
CEHJCommented:
>>can you please give me more details to your suggestion please.

Which part?
0
 
ellandrdCommented:
caching the connection and data i think...
0
 
zolfAuthor Commented:

>>caching the connection and data i think...

yes
0
 
CEHJCommented:
This assumes that getting the connection is the part taking a long time: at the start of the app, open the connection in a separate thread and save the connection in an instance variable. Before any fetch, check that conn != null. Keep it open throughout.
0
 
CEHJCommented:
:-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 10
  • 5
  • 4
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now