Solved

JButton takes long time to get data

Posted on 2007-11-19
21
236 Views
Last Modified: 2010-03-30
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
Comment
Question by:zolf
  • 10
  • 5
  • 4
  • +1
21 Comments
 
LVL 92

Expert Comment

by:objects
ID: 20311026
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
 
LVL 16

Expert Comment

by:ellandrd
ID: 20311027
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
 

Author Comment

by:zolf
ID: 20311035

but this does not happen everytime.
0
 

Author Comment

by:zolf
ID: 20311050

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
 

Author Comment

by:zolf
ID: 20311052

my database is local
0
 
LVL 16

Expert Comment

by:ellandrd
ID: 20311054
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
 

Author Comment

by:zolf
ID: 20311061

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

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

Author Comment

by:zolf
ID: 20311087

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
 

Author Comment

by:zolf
ID: 20311125

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
 
LVL 92

Accepted Solution

by:
objects earned 250 total points
ID: 20311139
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 16

Assisted Solution

by:ellandrd
ellandrd earned 150 total points
ID: 20311142
>>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
 
LVL 86

Expert Comment

by:CEHJ
ID: 20311174
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
 

Author Comment

by:zolf
ID: 20311178

i think objects suggestion makes sense.

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

Author Comment

by:zolf
ID: 20311182

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

Author Comment

by:zolf
ID: 20311184

the combo box gets the city name from the db.there are around 350 cities
0
 
LVL 16

Expert Comment

by:ellandrd
ID: 20311206
>>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
 
LVL 86

Expert Comment

by:CEHJ
ID: 20311215
>>can you please give me more details to your suggestion please.

Which part?
0
 
LVL 16

Expert Comment

by:ellandrd
ID: 20311219
caching the connection and data i think...
0
 

Author Comment

by:zolf
ID: 20311239

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

yes
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 100 total points
ID: 20311259
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
 
LVL 86

Expert Comment

by:CEHJ
ID: 20311408
:-)
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
The viewer will learn how to implement Singleton Design Pattern in Java.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now