Thursday, December 19, 2013

Essence of Debugging

Past five years I was using good old mobile model (Nokia's first color version), a very sturdy and stable phone.  Though it had very minimal feature, it served my purpose. Now the world is flooded with smartphone variants, every day we hear about one or the other releases. But (still) I adored my phone and heisted to buy a new phone, in-spite of co-worker’s and friend’s mocking.

One fine day, it started to send SMS to very first contact in my address book till pre-paid amount was depleted, thank god I did not subscribe for post-paid plan. With lots of reluctance, I bought latest smartphone from top branded company. I qualify tablets yet it took a day to recognize basic functionalities, sounds funny right!

Next day with pride I showcased my smartphone to my team. Many well-wishers gave lot of suggestions to bash new-fangled stuffs. Indeed I was busy, exploring apps for 2 weeks and did not notice any glitches. My father gifted a flip mobile cover; it further thrilled my mobile experience.

Happy days does not last long, suddenly battery life went for a toss. Immediately like any other software engineer, I googled to figure out reason. Even if I did not touch my phone, battery was draining at rate of 5% per 15 minutes. Tried every tips and tricks that was suggested on internet; no use. At last seeked nearby service center help, here is the twist. Help desk employee clearly said they attend only software issues and pointed another center where hardware issues are figured out. (She did not touch my mobile and figured out it is a hardware issue!!)

Ringed service center-II and stated my problem. “I think your phone battery needs a replacement, but still we cannot assure the new battery will resolve your issue…Thanks for calling XXX service center, have a nice day” this is the reply I got from them.

Climax
           Went home with lots of frustration, removed mobile cover and throwed it on ground. Then suddenly a thought flashed on my mind, will this beautiful cover ruin batter life? Immediately did an analysis, and answer was “yes”. It was a pure leather cover and it heated up lithium battery to the core; hence battery drained continuously.

Debugging is a skill that many testers pay less attention, but it is a key trait expected from a testing expert. Always trace back (Reverse engineering) to figure out the root cause. Take one component for analysis and hit the culprit. Happy debugging!!


Tuesday, November 12, 2013

Error Guessing – Bug counting out game.


My favorite month is October, a month jam-packed with festivals and rains. Aroma from sweets, flower’s fragrance, and essence from new dresses and of course holidays; like this I can quote many more reasons to justify my likeliness  towards last month.  In many IT companies, mid-year appraisal is conducted on October, to track how employee has performed on par with goals/tasks assigned to them. Each company follow different strategy to rate testers, but I wish “Error Guessing” should also be tagged as a trait to benchmark testers.

Ever heard about Error Guessing?  No? Then please read on. Given an application to test, based upon previous experience and testing knowledge; a tester can figure out areas which are likely to be error prone. Remember this is not confined to manual testing; it is applicable for all types of software testing that exist on earth. Do you call yourself “Testing Expert”? Then better ensure you have boundless error guessing capabilities

N+ ways are there to improvise “Error guessing” ability, but these are few which I do on every day. Here are they…

Test as many applications as possible –Have you ever observed pattern in bugs, among products having similar anatomy? Well, it’s because of underlying technologies, usage scenarios and common coder’s mistakes. The more applications we test, more we learn about bug patterns.  So next time when you encounter similar application to test, you can easily correlate & spot areas which are error prone.

Reading other’s bug report – Everyday I read bug reports logged by my colleagues. It not only improves my knowledge about product but also to understand different flows, tools, techniques to unveil a valid defect. Infact after lunch, this is my first assignment. Trust me this would be a stress-free yet significant duty to resume your routine.

Consider History – Search for defects from related products or search by developers in your defect management tool, to get hold of zones to concentrate upon. Ensure you focus on products which serve same purpose, for instance to qualify Notepad++ you can make use of Notepad test results.

You have filed ample number of exceptional user flow defects, does it means you are good in error guessing? May not be, any tester can spot defect with the help of requirements doc/plan artifacts. The technique/heuristics which you use to uncover defects determines whether you have applied error guessing or not. To illustrate: A tester well versed with web application may use case like this one, key- in “<Script>alert (Alert message);</Script>”  in any text area in website & check what it does.

Have comments? Please share it; I am eager to hear your valuable suggestions


Monday, September 23, 2013

Let others do your testing

Whenever I sign off releases first question that strikes my mind is "Have I done adequate testing?” We all assent exhaustive testing is impossible. But when a customer points a bug, can you predict who will be in spot-light? – Yes, QA team who shipped the product.

Inspite of executing N cycles of functional/non-functional, regression, and automation testing till the deadline, limited defects may not be dotted until production. And one possible reason for this could be when testers test same product/component over a period of time they gain confidence over product & tend to miss defects. Here am not blaming fellow testers but that is human tendency.

steps to open a word document
So what we need is a fresh eye, I mean personasThat is, more scenarios can be covered by additional personas. To elaborate further, think of a simple user scenario “open a saved MS-Word document”.

Here I have listed few predominately used flows, still different persona can open same document contrarily. 

Again the point I would like to emphasis is need for more actors. Let’s see how to achieve it
  • Pair testing – As it name implies, two members per team is necessary that is have a secondary owner for each component. Pairing with an expert or beginner enriches each tester’s capability. 
  • Bug Bash – You may know this program/process with different name (other widely used captions include Bughunt, TestBash, PlayDay).  Once product is stable invite internal & external team members to play with it. Folks working in same product family can unfold many cyclic defects. 
  • Betatesting – Exposing product to wider audience for validation. Here again audience refer to noteworthy stakeholders/potential customers. At times, beta version products mandates user to sign non-disclosure agreements. Tip:  Enroll yourself as beta tester, then probability of getting hired is pretty high 
  • Crowdtesting – Do not confuse crowdsourcing with outsourcing.

Who watches the watchmen? 

So next time when you are ready to sign-off, ensure you use any of the above process to gain confidence about product’s quality & of-course about your test coverage. Guess I forgot to emphasize a pointer, only after enough testing these techniques adds value else it is similar to outsourcing :) :). Please share your comments, if any.

Friday, August 30, 2013

Compatibility Testing in a Nutshell

Few weeks back I went to Shridi (pretty near to Pune, India) by train. Supposed to be two days (to & fro) trip which extended to three most awful days. Train service in India needs to be improved, a lot. “Quality & customer service” are verses which must be implanted in Indian Railway service motto. Do not want brief about my bad experience, since it is of no use. Neither people nor government is ready for transformations. L

Now to the post, let’s start by defining compatibility testing – “A Non-functional testing which often boils down to functional testing, targeted to confirm potential configurations; where software under test functions harmoniously”. To enhance,
  • Compatibility Testing ~ Configuration Testing
  • Certification Testing “part of” Compatibility Testing (not mandatory)
Hope I have defined it acceptably (at-least better than testing text books!). Not convinced with above definition? Click here to read Wikipedia’s version

Exploring Envisioned Ecosystem
So foremost step is to identify environment or platforms in which AUT (Application under Test) has to be operated. Then come up with parameter-list (a list of elements/parameters) that constitutes typical customer environment. And these governing elements, hinge on type (web, mobile, desktop etc...) of AUT being developed.
Few hints to derive parameter- list
  • Ideally possible environmental parameter has to be cited in requirements documents, which won’t happen in many organizations!
  • Customers – if not widely distributed, then get their inputs as well. For products with huge customer base usually this task is leveraged to marketing team, sometimes outsourced.Not that easy, so better be aware.
  • Software release notes – Software used for developing AUT (For Instance: Java, .Net for web based applications) can co-exist with like-minded applications, to figure out offbeat ones refer corresponding release notes. Also do remember these keywords while constructing parameter-list: “Version”, “Patches”.
  • If AUT is a scratch new product then probe for products with similar characteristics. I would highly recommend competitor products for such analysis.
  • Finally, apply your(tester’s) heuristics
Focus On
It may not be possible to validate AUT in all configurations you have identified. Prioritize elements on hand, by following any technique (like House of Quality) which suits you. By this time, you should have essential parameters and its corresponding elements. Now figure out the combinations or basic configuration matrix that will cover up all items in parameter list. (Hint: Try orthogonal array testing/pair-wise testing while coming up with test domains). Share your configuration matrix with stakeholders and proceed with execution.

The Next Step
There are many tools in market to aid compatibility testing. To list few
  •  Browser – Free online tools to check layouts & rendering
  •  PC – Virtual machines
  • Emulators & Simulators for mobiles, hardware, carriers/networks
Ensure Beta users are part of compatibility testing. Backward & Forward compatibility issues are likely to be unearthed mostly by beta users. Report your observations and modify AUT as required. Remember AUT may not excel in all environments at given time, so be ready for another version :)

Points to summon up
  • Compatibility testing is not limited to soft wares, applicable even for human blood
  • Certification/Standard compliance – get experts help to identify which ones are applicable for AUT (waive this pointer if you are an expert!!)
  • Opt for crowd testing. If your configuration matrix then is huge consider outsourcing.
  • One round of testing has to be done on real environment without using any tools/simulators
Have any feedback? Please comment it.

Tuesday, July 9, 2013

Progress card for software - Qualitatively analyzing software traits

During school days, most of the kids are forced to get their progress report/Grading report or rank card signed by his/her parents. As far as I know, this practice is still mandatory in Indian education system. I still relish those moments, my parents all the time started with an appreciation but never dis-remembered to highlight subjects, I need to improve upon.  I am sure many Indians would have adored related scenes in cinemas, as well.

Story behind this post - While I was thinking about next blog topic, I saw a neighborhood boy getting appreciation from his parents for great grades. Immediately I asked myself how good it would be if we have report card for software product or components as well. Such rank cards will assist all the stakeholders of a project!  Very next day, I enquired about the same with my friends. One person chattered about “Qualitative Analysis”.  Let’s see what it is.

To quickly get a hold of Qualitative Analysis, I used W5H (Different from W5HH principle) mechanism

 WHAT is Qualitative analysis? - Collect all essential parameters that are required to qualify the component or product being tested. Ensure parameter list is crisp yet covering major aspects of the product. Now define legends for the grade. Once the stakeholder agrees upon parameters and grading scale, proceed with evaluation. That’s it; now write down your observation in presentable format (most important step) and post it to all stake holders. This analysis should help any stakeholder to get a picture about the health of the product. A classic report shall look like this

Parameters
Grades
Comments
Error handling
 <you can use color codes to mark the status>
10

Internalization
RED
2

Accessibility
YELLOW
5

Security

3
Privacy information are logged in code

WHY should we do this? – Qualitative analysis often turns as an alarm, it highlights the area to dive deep and mend upon. At one point of time, when you have series of cumulative analysis reports product team can recognize characteristics that needs more consideration. Benefits list goes on

WHERE can I embed? – Instead of furnishing analysis as a separate entity, QA team can imbibe it as part of test report. Hence all stakeholders will informed about product progress and also appreciate the reputation of such analysis

WHO should perform Qualitative analysis? - Obviously it is testers, who symbolize customers. I understand in much software company, testers would not have such authority but still my vote is for TESTERS ( In many Indian based MNCs still testers are not part of test planning, for the product they are going to validate!!; sounds miraculous?? still true)

WHEN shall I start this activity? – Whenever a test report is shared to stakeholders. I mean, when one complete round/cycle of testing is done with the product.

HOW will analysis be done technically and managerially? In a project comprising multiple teams, this tasks mandates cooperation from every individual. Each team can share their corresponding results to Global QA team for furnishing. So ensure strategy for analysis is laid out during project planning.

To end with, I recommend only one note to keep in mind while preparing any artifact remember “Easy on the eye, Easy on the brain”; so keep it simple. Do you perform similar analysis? If so please share your experience and comments. As always your feed-backs are awaited.

Friday, June 7, 2013

Swing Application - Imports contents to JTable from opted Excel sheet/tab

This feed shows how to import excel contents to JTable. To start, this application has a provision for users to select excel workbook (JFileChooser). Once selected excel file is imported, all available worksheets are listed to user(JOptionPane). Now based upon the opted excel sheet corresponding contents are loaded in Tabular format (JTable)

To Note,
  • Accepts only .xls format
  • Only one excel sheet can be imported at a time
  • Empty cells are respected.
  • Very first row of excel sheet is considered as header for the JTable
  • HSSF is used to access excel workbook through Java
excelToJTable.java 

import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class excelTojTable extends JFrame {

    static JTable table;
    static JScrollPane scroll;
    // header is Vector contains table Column
    static Vector headers = new Vector();
    static Vector data = new Vector();
    // Model is used to construct
    DefaultTableModel model = null;
    // data is Vector contains Data from Excel File 
    static Vector data = new Vector();
    static JButton jbClick;
    static JFileChooser jChooser;
    static int tableWidth = 0;
    static int tableHeight = 0;
 
public excelTojTable()
 {
      super("Import Excel To JTable");
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel buttonPanel = new JPanel();
      buttonPanel.setBackground(Color.white);
      jChooser = new JFileChooser();
      jbClick = new JButton("Select Excel File");
      buttonPanel.add(jbClick, BorderLayout.CENTER);

        // Show Button Click Event
          jbClick.addActionListener(new ActionListener()
            {
                     @Override public void actionPerformed(ActionEvent arg0)
                              {
                                     jChooser.showOpenDialog(null);
                                     jChooser.setDialogTitle("Select only Excel workbooks");
                                     File file = jChooser.getSelectedFile();
                                    if(file==null)
                                      {
                                          JOptionPane.showMessageDialog(
                                          null, "Please select any Excel file",
                                          "Help",
                                          JOptionPane.INFORMATION_MESSAGE);
                                          return;
                                        }
                                    else if(!file.getName().endsWith("xls"))
                                       {
                                             JOptionPane.showMessageDialog(
                                             null, "Please select only Excel file.",
                                            "Error",JOptionPane.ERROR_MESSAGE);
                                       }
                                    else
                                      {
                                            fillData(file);
                                            model = new DefaultTableModel(data, headers);
                                            tableWidth = model.getColumnCount() * 150;
                                            tableHeight = model.getRowCount() * 25;
                                            table.setPreferredSize(new Dimension( tableWidth, tableHeight));
                                             table.setModel(model);
                                         }
                              }
            });
         table = new JTable();
         table.setAutoCreateRowSorter(true);
         model = new DefaultTableModel(data, headers);
         table.setModel(model);
         table.setBackground(Color.pink);
         table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
         table.setEnabled(false);
         table.setRowHeight(25);
         table.setRowMargin(4);
         tableWidth = model.getColumnCount() * 150;
         tableHeight = model.getRowCount() * 25;
         table.setPreferredSize(new Dimension( tableWidth, tableHeight));
         scroll = new JScrollPane(table);
         scroll.setBackground(Color.pink);
         scroll.setPreferredSize(new Dimension(300, 300));
         scroll.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scroll.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
         getContentPane().add(buttonPanel, BorderLayout.NORTH);
         getContentPane().add(scroll, BorderLayout.CENTER);
         setSize(600, 600);
         setResizable(true);
         setVisible(true);
 }

// Fill JTable with Excel file data. * * @param file * file :contains xls file to display in jTable 

  void fillData(File file)
      {
         int index=-1;
         HSSFWorkbook workbook = null;
        try {
               try {
                       FileInputStream inputStream = new FileInputStream (file);
                        workbook = new HSSFWorkbook(inputStream);
                    }
               catch (IOException ex)
                    {
                         Logger.getLogger(excelTojTable.class. getName()).log(Level.SEVERE, null, ex);
                     }

                       String[] strs=new String[workbook.getNumberOfSheets()];
                      //get all sheet names from selected workbook
                        for (int i = 0; i < strs.length; i++) {
                             strs[i]= workbook.getSheetName(i); }
                        JFrame frame = new JFrame("Input Dialog");
                     
                        String selectedsheet = (String) JOptionPane.showInputDialog(
                           frame, "Which worksheet you want to import ?", "Select Worksheet",
                          JOptionPane.QUESTION_MESSAGE, null, strs, strs[0]);
               
                       if (selectedsheet!=null) {
                            for (int i = 0; i < strs.length; i++)
                              {
                                 if (workbook.getSheetName(i).equalsIgnoreCase(selectedsheet))
                                 index=i; }
                            HSSFSheet sheet = workbook.getSheetAt(index);
                            HSSFRow row=sheet.getRow(0);
                       
                           headers.clear();
                           for (int i = 0; i < row.getLastCellNum(); i++)
                          {
                             HSSFCell cell1 = row.getCell(i);
                             headers.add(cell1.toString());
                          }
                       
                          data.clear();
                          for (int j = 1; j < sheet.getLastRowNum() + 1; j++)
                          {
                             Vector d = new Vector();
                             row=sheet.getRow(j);
                             int noofrows=row.getLastCellNum();
                             for (int i = 0; i < noofrows; i++)
                             {    //To handle empty excel cells 
                                   HSSFCell cell=row.getCell(i,
                                   org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK );
                                   d.add(cell.toString());
                             }
                            d.add("\n");
                            data.add(d);
                          }
                     }
                    else { return; }
        }
      catch (Exception e) { e.printStackTrace(); } }
     public static void main(String[] args)
       { new excelTojTable(); }
   }

Here is the flow
Select Excel file(.xls) Select any available sheet
probing tester_select Excel file probing_tester_select excel sheet
Imported contents from selected Excel sheet

probing_tester_Imported content from excel

Want to download above code ?? click this link excelToJTable. Below cited, is used/sample excel data.

probing_tester_input
Preview of the excel sheet used as input

Let me know if you encounter any issues with above code. As usual, share your comments any time!!

Saturday, May 11, 2013

Art of Requirement Elucidation – Learn by Game


This game was shared by my friend, Shibaji Ganguly.  He is well known for clear and flawless testing artifacts. I do not have any name for this exercise. But I am certain many of us would have played the variants & equivalents of this game. Believe me this game is worth a try in your leisure time with your team member, as it heightens your interpretation skill.

To start, let’s assume you are the organizer, take a white paper and draw an object of your wish. Ensure object drawn, can be designed with the help of ONLY geometrical figures (Square, Rectangle, Rhombus, Triangle & many more).

Now form teams with at-least three members. Each team should have Presenter, Drawer and Observer.  Hand over the sheet with object, only to Presenter.
  • Presenter - Provide hints to “Drawer” for depicting the object. Presenter should not face the board until “Drawer”  finish sketching the object.
  • Drawer - Sketches the object on board based upon hints provided by presenter.
  • Observer - As name insist just a observer. Identifies the object as penciled by Drawer.
Remember "Presenter" hints should always stick to geo-metrical figures and violating this rule, appeals for team elimination. Team which pinpoints intended object more rapidly is the champion.

To explain further, here is an illustration: A conical flask (Erlenmeyer flask to be perfect) closed with cork and also an apple within flask.

Actual (as drawn in paper)
Object to be identified
Image source:http://teachers.egfi-k12.org/master-stem-teachers/
Hints that shall be provided by the presenter for this diagram
  •  Draw an equilateral triangle.
  •  Erase tip of the triangle, at the top. Do not erase the base.
  • Expected (To be drawn by drawer) Expected(To be penciled by drawer)
  • Draw pipe connecting open end of triangle, at the top.
  • Pipe should be like two parallel lines of equal length.
  • One end of the pipe should connect the erased end of the triangle.
  • Do close the other end of the pipe with an ellipse
  • Focus on ellipse
  • Draw an inverted cone within ellipse
  • Base of the inverted code should be above ellipse
  • Tip of the inverted code should be flat
  • Tip of Inverted cone should not touch base of the triangle
  • Height of inverted cone should be equivalent to pipe length.
  • Above the base of the triangle, say 1 centimeter
  • Draw a circle or sphere
  • Draw a line of 1 centimeter at one edge of circle
  • The other end of line should point to open end of triangle
  • Line drawn from circle should not touch the tip of inverted cone.
At the end of this workout, each team will realize the importance of clear and distinctive requirements. That is, as small teams with single object on hand; amount of confusion is manageable upto a magnitude. Then visualize a typical software project where geographical distributed teams would work on multiple features, aggregate of misunderstanding will grow exponentially with unclear requirements.

For those who ponder how this exercise is linked to requirement collection, in software industry many tester treat requirements document (esp with single liners) as ONLY reference/guide for verification either because they are forced to do or trained in that way. So why do not we(testers) cultivate clear, comprehensive & complete communication within our-self and try to dive deep with information on hand. Quality can be easily assured if a tester understands product being shipped.

Avatar. 1 Avatar. 2 Avatar. 3 Avatar. 4
probingtester_Avatar1 probingtester_Avatar2 probingtester_Avatar3 probingtester_Avatar4

Above snapshots are few of the avatars which was spawned from my team :).
Do try this game and share your comments. I am definite you will like the revolution.

Thursday, April 4, 2013

Unknown’s Unidentified – Implicit Requirements

"Why this case was not covered in your test plan? Have not you done test coverage sign off? Probably you should take our organization process training (so called) to extemporize your analytic skills! From henceforth work with “Mr. Smart” (most likely pet of manager) to certain no false-steps are seen in future."

Ever faced whichever of these questions in your testing life path, Well I have faced a few, to be straightforward. The moment these queries hit our cochlea, stimulus ensures to point our finger towards business analyst or project manager, to outline all requirements. Yes, you are right but it is also the liability of a blameless tester to serve his stakeholder, better

There could be voluminous technical or non-technical documents spawned in a project, but it is predominantly the tester artifacts which catch customer’s responsiveness. Because each tester’s artifact reveals readiness & quality of the project/product, which customers want to utilize & of course pay for, correspondingly. So why can’t testers utilize this prospect to retain customers in page with project’s status.

Let’s start with Test Plan attributes
  • Scope - Defining scope is vital part of planning. I have seen test plans where scope is defined within 500 characters!. Make sure to present the range of testing, unmistakably.
  • What won’t be tested? - Identify boundaries and potential environment variables. Call out which will NOT be covered in your test execution. This section will bring out hidden requirements from any dependent team or even customers.

  • Assumptions – Whenever you author any shared document, explicitly insist on assumptions you did while drafting that doc. Having said that do not quote negative cases or uncertain conceptions under assumption section. Ensure this section is precise and informative.
    • Scenario: Let’s say you are validating “Font Styles” for Microsoft Word
    • Valid: Font style is supported for both Horizontal and Vertical<Japanese> Contents
    • Invalid: Font style is not applicable for superscript and subscript.[Negative case]
    • Invalid: Font style rendering are respected only for ASCII and UTF-8 encoded formats.[Uncertain about encoding formats, this can be added as an open question]
  • Unanswered Questions/ Open items - Here capture all confusions lingering in your mind. You can even append the point of contact for each item, for better tracking.
    Test Case Categorization - Use either breadth <user story> or depth <Feature/Component> wise approach to tag test cases. Remember each has their own pros and cons, so stick to one that fits you. Gaps can be spotted in ease if suitable test case classification is in place, by any reviewer.

    Test Data - Numerous software failures arise due to improper handling of data, misleading information and unexpected inputs. If possible get data from customer field or ensure to share format of likely inputs with real time users/stakeholders. Real time data are often unpredictable!

    Test Result - Test results should be logically complete, quantifiable and measurable. In short, any stakeholder should visualize quality from our test results. Recently I stumbled upon a test result document from a start-up organization, which had user stories and its corresponding status (Pass or Fail), making it more informative.

    Reviews - Voluminous after-effects arise due to the mis-communication or synchronization among project stakeholders. So review all your artifacts with possible stakeholders. Try to involve actual customer once in a while. Reviews will elude dis-satisfiers, who forgot to explicitly mention about a requirement or assumed it as a basic provision in equivalent application. Reviews also aids in avoidance of non-delighted stakeholders, who may not be aware of actual technology, standards or domain updates

    Questioning is a strategic skill for any passionate tester so do cultivate it. Before closing any artifact, ask yourself “Have I asked questions”? This will encourage in perceiving unknown/hidden requirements. As always, want to share your comments?? Please feel free. 

    Tuesday, March 19, 2013

    Swing Application - Searches DB & display results through JTable in JTabbedPane

    This feed narrates how to search for a record in a JTabbedPane. The search results are displayed in tabular form using JTable. To download these java files, please click on corresponding filename. Lets drill down, to the code.
    • OrderView - Main class, which calls out layout design. (i.e UI)
    • ItemTabelModel - An abstract table model, to display search results in tabular form
    • OrderDAO - Takes care of DB interaction, I have used MySQL
    • OrderInfo - A class to demonstrate order object
    OrderView.java
    • Creates JTabbedPane with four panels - Create, Edit, Delete & Search
    • Searches for record in DB using OrderDAO class
    • Search is invoked by "Enter" key as well as "Search" button
    • Zero & Empty search results are handled
    • Search result-set size need not be one.
    • Implements listeners for KeyTyped, KeyPressed and KeyReleased events
    • Display search results in tabular form using JTable
    • Snippet shared here is confined to "Search" tab, other tabs are not designed

      public class OrderView implements ActionListener {

    ArrayList orderList;
    OrderDAO oDAO; <- For DB interaction
    JFrame appFrame;
        JLabel jlbName, jlbItem;
        JTextField jtfName,jtfDate;
        JTabbedPane appPane;
        JButton jbbSave, jbnDelete, jbnClear, jbnUpdate, jbnSearch;
        JTable jtbOrder;
        JScrollPane sp;
        JPanel jPaneCreate,jPaneEdit,jPaneDelete,jPaneSearch;
       
        String name, address, email;
        int recordNumber;
        String nameStr;   
        private ItemTableModel ItemTabModel;
       
        public static void main(String args[]){
            new OrderView(); 
         }
        
        public OrderView()
        {       
          createGUI();    
          orderList = new ArrayList();
          oDAO=new OrderDAO();
        }
        
        public void createGUI(){

        /*Create a frame, get its contentpane and set layout*/
        appFrame = new JFrame("View your order status");
        appPane=new JTabbedPane();
        jPaneCreate=new JPanel(new GridLayout(5,2));
        jPaneEdit=new JPanel(new GridLayout(5,2));
        jPaneDelete=new JPanel(new GridLayout(5,2));
        jPaneSearch=new JPanel(new GridLayout(5,2));   
       
        appPane.setTabPlacement(JTabbedPane.LEFT);   
        appFrame.getContentPane().add(appPane);
        appPane.add("Create New",jPaneCreate);
        appPane.add("Edit/Update",jPaneEdit);
        appPane.add("Delete",jPaneDelete);
        appPane.add("Search",jPaneSearch);
       
        //set shortcuts for each tab
          appPane.setMnemonicAt(0 , KeyEvent.VK_C);
        appPane.setMnemonicAt(1 , KeyEvent.VK_E);
        appPane.setMnemonicAt(2 , KeyEvent.VK_D);
        appPane.setMnemonicAt(3 , KeyEvent.VK_S);   
        //Arrange components on contentPane and set Action Listeners to each JButton
        arrangeComponentsCreate();
         arrangeComponentsEdit();
        arrangeComponentsDelete();
        arrangeComponentsSearch(); 
               
        appFrame.pack();
        appFrame.setVisible(true);
        appFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
       
        private void arrangeComponentsSearch() {
         jlbName = new JLabel("Customer Name");
         jlbItem = new JLabel("Item Ordered");  
         jtfName=new JTextField(20);
         jtfDate=new JTextField(20);
         //listeners ensure typed search strings are converted to uppercase, as & when key typed
         jtfName.addKeyListener(new KeyAdapter(){
         public void keyReleased(KeyEvent e) {
                    JTextField textField = (JTextField) e.getSource();
                    String text = textField.getText();
                    textField.setText(text.toUpperCase());
                }

                public void keyTyped(KeyEvent e) {
                    // TODO: Do something for the keyTyped event
                 JTextField textField = (JTextField) e.getSource();
                    String text = textField.getText();
                    textField.setText(text.toUpperCase());
                }
              //Invoke search person on "Enter" button event
                public void keyPressed(KeyEvent e) {
                    // TODO: Do something for the keyPressed event
                 JTextField textField = (JTextField) e.getSource();
                    String text = textField.getText();
                    textField.setText(text.toUpperCase());
                    if (e.getKeyCode()== KeyEvent.VK_ENTER )
                    {
                     searchPerson();
                    }
                }
         });
        
           GridBagConstraints c = new GridBagConstraints();
            setMyConstraints(c,0,0,GridBagConstraints.CENTER);
            jPaneSearch.add(getFieldPanel(),c);
            setMyConstraints(c,0,1,GridBagConstraints.CENTER);
            jPaneSearch.add(getButtonPanelSearch(),c);         
            jtbOrder=new JTable();
    ItemTabModel=new ItemTableModel();
    jtbOrder.setModel(ItemTabModel); 
     sp=new JScrollPane(jtbOrder); 
            jbnSearch.addActionListener(this);
    }  
        
        public void actionPerformed (ActionEvent e){  
         if (e.getSource() == jbnSearch)
          searchPerson();//clicking search button should invoke searchPerson() function   
        }

    private JPanel getButtonPanelSearch() {
    //Search Button
    JPanel p = new JPanel(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        setMyConstraints(c,0,0,GridBagConstraints.CENTER);
         p.add(jbnSearch,c);
    return p;
    }

         private JPanel getFieldPanel() {
           JPanel p = new JPanel(new GridBagLayout());
           p.setBorder(BorderFactory.createTitledBorder("Details"));
           GridBagConstraints c = new GridBagConstraints();
           setMyConstraints(c,0,0,GridBagConstraints.EAST);
           p.add(jlbName,c);
           setMyConstraints(c,1,0,GridBagConstraints.WEST);
           p.add(jtfName,c);
           setMyConstraints(c,0,1,GridBagConstraints.EAST);
           p.add(jlbItem,c);
           setMyConstraints(c,1,1,GridBagConstraints.WEST);
           p.add(jtfDate,c);
           return p;
         }

        private static void setMyConstraints(GridBagConstraints c, 
               int gridx, int gridy, int anchor) {
               c.gridx = gridx;//manages the layout of controls
               c.gridy = gridy;
               c.anchor = anchor;
            }
        
    public void searchPerson() {        
         name = jtfName.getText();    
        /*clear contents of arraylist if there are any from previous search*/    
        orderList.clear();
        recordNumber = 0;

        if(name.equals("")){
        JOptionPane.showMessageDialog(null,"Please enter person name to search.");
                             //when a empty string is searched
        clear();
        }
        else{
        /*get an array list of searched persons using PersonDAO*/
        orderList = oDAO.searchPerson(name);
        if(orderList.size() == 0){
        JOptionPane.showMessageDialog(null, "No records found.");
        //Perform a clear if no records are found.-Refer screenshot
        clear();
        }
        else
        {    
        //Erasing previous history
        recordNumber=orderList.size();
        ItemTabModel.removeall();
        jPaneSearch.remove(jtbOrder);
        jPaneSearch.remove(sp);
        jPaneSearch.repaint();    
        //If there are more search results, display all in tabular form
        while(recordNumber>0)
        {
        /*downcast the object from array list to OrderInfo*/
        OrderInfo person = (OrderInfo) orderList.get(recordNumber-1); 
                      ItemTabModel.addOrderInfo(person);
                       recordNumber--;
        }    
        //Redraws the table
        jPaneSearch.add(sp);
        jPaneSearch.revalidate();   
        }    
        clear();        
        }
    }
    private void clear() {
    //Clears the textbox and sets focus
    jtfName.setText("");
    jtfName.requestFocusInWindow();
    }
     }

    Here are the snapshots of OrderView Application
    Search Results Zero Results Empty Search string
    Search Results Empty search string Zero search results
    I have not briefed other java files since they are trivial in function. Modify these code to your needs and let me know if you face any errors. To note, ensure you have MySQL connector jar in java build path to access database. Kindly share your comments, if any