Friday, March 28, 2014

Character counter using Java Swing and String api

A simple swing application that is used to count the characters, words and sentences.
User interface is developed by using Java swing api and characters, words and sentences count logic is done by using the String api using various methods like:
  • lenght()                     Returns the length of this string.
  • Split(String regex)   Splits this string around matches of the given regular expression.
  • charAt(int index)     Returns the char value at the specified index.
 Output : 
























GUI Code : 
 import javax.swing.*;
 public class CharacterCalculateJFrame extends JFrame {
    public CharacterCalculateJFrame() {
        this.setTitle("Character Counter");
        initComponents();
    }
    @SuppressWarnings("unchecked")
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        characterTextArea = new javax.swing.JTextArea();
        jLabel2 = new javax.swing.JLabel();
        calculateButton = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        charCounterLabel = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        wordLabel = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        sentenceLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 51, 255));
        jLabel1.setText("Character Counter");

        characterTextArea.setColumns(20);
        characterTextArea.setRows(5);
        jScrollPane1.setViewportView(characterTextArea);

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Enter Paragraph");

        calculateButton.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        calculateButton.setText("Calculate");
        calculateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calculateButtonActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel3.setText("Characters are :");

        charCounterLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        charCounterLabel.setForeground(new java.awt.Color(51, 51, 255));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel4.setText("Words are :");

        wordLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        wordLabel.setForeground(new java.awt.Color(51, 51, 255));

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Sentences are :");

        sentenceLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        sentenceLabel.setForeground(new java.awt.Color(51, 51, 255));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(43, 43, 43)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(calculateButton)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel2)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 272, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(sentenceLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                        .addGap(36, 36, 36)
                                        .addComponent(wordLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(38, 38, 38)
                        .addComponent(charCounterLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(charCounterLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(wordLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(15, 15, 15)
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(sentenceLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(calculateButton, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(57, Short.MAX_VALUE))
        );

        pack();
    }
    private void calculateButtonActionPerformed(java.awt.event.ActionEvent evt) {
        String charString = this.characterTextArea.getText().trim();
        this.charCounterLabel.setText(""+charString.length());
        String words[] = charString.split("\\s");
        this.wordLabel.setText(""+words.length);
        int sentenceCounter = 0;
        for(int i=0; i<charString.length(); i++) {
            if(charString.charAt(i)=='.') {
                sentenceCounter++;
            }
        }
        this.sentenceLabel.setText(""+sentenceCounter);    
    }
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CharacterCalculateJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CharacterCalculateJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CharacterCalculateJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CharacterCalculateJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new CharacterCalculateJFrame().setVisible(true);
            }
        });
    }
    private javax.swing.JButton calculateButton;
    private javax.swing.JLabel charCounterLabel;
    private javax.swing.JTextArea characterTextArea;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel sentenceLabel;
    private javax.swing.JLabel wordLabel;
 }

Thursday, March 27, 2014

A simple game using multi threading and swing api

In this application I have created the 4 thread
each thread has its own motion speed, when the moving thread getting closer to the 
bottom slide so the Y of moving thread and x of bottom slide is matching then bottom slide eats the moving thread.

Output :

























Root structure:
Create a folder in any drive and rename it as FruitGame as in below diagram











GUI code:
import java.awt.Color;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
/**
 *
 * @author rasool.bux
 */
public final class FruitGameJFrame extends javax.swing.JFrame implements MouseMotionListener {  
    int scoreVal;
    int counter = 4;
    int x;  
    ImageIcon icon1 = new ImageIcon("images/strawbary.PNG");
    ImageIcon icon2 = new ImageIcon("images/khopra.PNG");
    ImageIcon icon3 = new ImageIcon("images/apple1.PNG");
    ImageIcon icon4 = new ImageIcon("images/banana.PNG");
         
    /**
     * Creates consturctor FruitGameJFrame()
     */
    public FruitGameJFrame() {
        initComponents();
        addMouseMotionListener(this);
        this.setSize(600, 600);
        this.oneLabel.setIcon(icon1);
        this.twoLabel.setIcon(icon2);
        this.threeLabel.setIcon(icon3);
        this.fourLabel.setIcon(icon4);
        this.getContentPane().setBackground(Color.white);
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
    }
 
    @Override
    public void mouseDragged(MouseEvent e) {
     System.out.println("Mouse Dragged");
    }

    @Override
    public void mouseMoved(MouseEvent e) {      
        x = e.getX();    
        if(x<=486) {
            moveButton.setLocation(x,500);  
        }

    }
 
    Thread thread1 = new Thread(){
        int value=120;
        public void run() {
            for(int i=0; i<600; i++) {
                oneLabel.setLocation(value, i);
                try {
                     Thread.sleep(25);
                } catch (InterruptedException ex) {
                      Logger.getLogger(FruitGameJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(i==560) {
                    i=0;
                }    
             
               int valofY = oneLabel.getY();
               int valofX = moveButton.getX();
     
               if(valofY==458 ) {
                   if(valofX>=34 && valofX<=180) {
                       counter--;
                       scoreVal+=10;
                       oneLabel.setVisible(false);
                       values();
  thread1.stop();
                   }
               }
                moveButton.setLocation(x,500);
            }//end of loop
        }
    };

    Thread thread2 = new Thread(){
        public void run() {
            for(int i=0; i<600; i++) {
                twoLabel.setLocation(320, i);
                try {
                     Thread.sleep(20);
                } catch (InterruptedException ex) {
                      Logger.getLogger(FruitGameJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(i==560) {
                    i=0;
                }          
             
               int valofY = twoLabel.getY();
               int valofX = moveButton.getX();
     
               if(valofY==448) {
                   if(valofX>=232 && valofX<=382) {
                       counter--;
                       scoreVal+=10;
                       twoLabel.setVisible(false);
                       values();
  thread2.stop();
                   }
               }  
               moveButton.setLocation(x,500);
            }//end of loop        
        }    
    };
 
    Thread thread3 = new Thread(){
         @Override
        public void run() {
            for(int i=0; i<600; i++) {
                threeLabel.setLocation(410, i);
                try {
                     Thread.sleep(10);
                } catch (InterruptedException ex) {
                      Logger.getLogger(FruitGameJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(i==560) {
                    i=0;
                }          
             
               int valofY = threeLabel.getY();
               int valofX = moveButton.getX();
     
               if(valofY==420) {
                   if(valofX>=333 && valofX<=485) {
                       counter--;
                       scoreVal+=10;
                       threeLabel.setVisible(false);
                       values();
                       thread3.stop();
                   }
               }       moveButton.setLocation(x,500);        
            }//end of loop
        }      
    };
    Thread thread4 = new Thread(){
         @Override
        public void run() {
            for(int i=0; i<600; i++) {
                fourLabel.setLocation(6, i);
                try {
                     Thread.sleep(15);
                } catch (InterruptedException ex) {
                      Logger.getLogger(FruitGameJFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                if(i==560) {
                    i=0;
                }          
             
               int valofY = fourLabel.getY();
               int valofX = moveButton.getX();
     
               if(valofY==460) {
                   if(valofX>=8 && valofX<=50) {
                       counter--;
                       scoreVal+=10;
                       fourLabel.setVisible(false);
                       values();
                       thread4.stop();
                   }
               }       moveButton.setLocation(x,500);        
            }//end of loop
        }      
    };
    public void values() {
        this.setTitle("Score : "+scoreVal);
        if(counter==0) {
            this.getContentPane().setBackground(Color.red);
            this.gameOverLabel.setText("Total Score : "+scoreVal);
             moveButton.setLocation(x,500);
        }
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    private void initComponents() {
moveButton = new javax.swing.JButton();
        oneLabel = new javax.swing.JLabel();
        twoLabel = new javax.swing.JLabel();
        threeLabel = new javax.swing.JLabel();
        gameOverLabel = new javax.swing.JLabel();
        fourLabel = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        newGameMenuItem = new javax.swing.JMenuItem();
        StopMenuItem = new javax.swing.JMenuItem();
        resumeMenuItem = new javax.swing.JMenuItem();
        exitMenuItem = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Fruit Game");
        setBackground(new java.awt.Color(255, 255, 255));

        gameOverLabel.setFont(new java.awt.Font("Times New Roman", 1, 48)); // NOI18N
        gameOverLabel.setForeground(new java.awt.Color(255, 255, 255));

        fourLabel.setText("jLabel1");

        jMenu1.setText("File");

        newGameMenuItem.setText("New Game");
        newGameMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newGameMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(newGameMenuItem);

        StopMenuItem.setText("Stop");
        StopMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                StopMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(StopMenuItem);

        resumeMenuItem.setText("Resume");
        resumeMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resumeMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(resumeMenuItem);

        exitMenuItem.setText("Exit");
        exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitMenuItemActionPerformed(evt);
            }
        });
        jMenu1.add(exitMenuItem);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(299, 299, 299)
                        .addComponent(twoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 89, Short.MAX_VALUE)
                        .addComponent(threeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(moveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(120, 120, 120)
                                .addComponent(oneLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(108, 108, 108))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(gameOverLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 472, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(fourLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(oneLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(40, 40, 40)
                        .addComponent(twoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(threeLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(2, 2, 2)
                .addComponent(fourLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
                .addComponent(gameOverLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 142, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(106, 106, 106)
                .addComponent(moveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }                      

    private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                          
        JOptionPane.showConfirmDialog(null, "Do You want to Exit");
        System.exit(0);
    }                                          

    private void newGameMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                              
        this.setVisible(false);
        FruitGameJFrame fruitGameJFrame = new FruitGameJFrame();
        fruitGameJFrame.setVisible(true);
    }                                            

    private void StopMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                          
        thread1.suspend();
        thread2.suspend();
        thread3.suspend();
        thread4.suspend();
    }                                          
    private void resumeMenuItemActionPerformed(java.awt.event.ActionEvent evt) {                                            
         thread1.resume();
         thread2.resume();
         thread3.resume();
         thread4.resume();
    }                                            
    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FruitGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FruitGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FruitGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FruitGameJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new FruitGameJFrame().setVisible(true);
            }
        });
    }
    private javax.swing.JMenuItem StopMenuItem;
    private javax.swing.JMenuItem exitMenuItem;
    private javax.swing.JLabel fourLabel;
    private javax.swing.JLabel gameOverLabel;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JButton moveButton;
    private javax.swing.JMenuItem newGameMenuItem;
    private javax.swing.JLabel oneLabel;
    private javax.swing.JMenuItem resumeMenuItem;
    private javax.swing.JLabel threeLabel;
    private javax.swing.JLabel twoLabel;
 }


Download these images and place in the folder images inside the FruitGame folder. 

Wednesday, March 19, 2014

Execute a command at runtime using Java program

At the runtime  give a command as input, the Java program interprets that command and execute it. Such commands are: notepad, msword, calc, mspaint, word etc.

GUI based executing command program:



GUI version Code: 
 import javax.swing.*;
 import java.awt.*;
 import java.awt.event.*;
 class RobotFrame extends JFrame implements ActionListener,ItemListener  {

    String commandName;
    List cmdList = new List();
    JButton executeButton = new JButton("Execute");
    JButton exitButton = new JButton("Exit");
    JLabel jLabel1 = new JLabel("Cmd Executer");
    JScrollPane jScrollPane1 = new JScrollPane(cmdList);
    Font f = new Font("Verdana", Font.BOLD, 30);

    public RobotFrame() {
        initComponents();
    }  

    public void initComponents() {
this.setSize(350,450);
this.setTitle("Command Executer");
this.getContentPane().setBackground(Color.cyan);
this.getContentPane().setLayout(null);
this.getContentPane().add(executeButton);
this.getContentPane().add(exitButton);
this.getContentPane().add(jLabel1);
this.getContentPane().add(jScrollPane1);
jLabel1.setFont(f);
jLabel1.setForeground(Color.red);
jLabel1.setBounds(50,10,300,30);
jScrollPane1.setBounds(60,60,200,300);
executeButton.setBounds(60,365,80,35);
exitButton.setBounds(180,365,80,35);
cmdList.add("Notepad");
cmdList.add("calc");
cmdList.add("mspaint");
cmdList.add("word");
executeButton.addActionListener(this);
exitButton.addActionListener(this);
cmdList.addItemListener(this);
   }

   public void itemStateChanged(ItemEvent e){
        commandName = (String)cmdList.getSelectedItem();
   }

   public void actionPerformed(ActionEvent e) {
if(e.getSource()==executeButton) {
try {
Runtime runtime = Runtime.getRuntime();
runtime.exec(commandName.toLowerCase());
}catch(Exception ex){}
}
if(e.getSource()==exitButton) {
System.exit(0);
}
}

   public static void main(String args[]) {
RobotFrame robotFrame = new RobotFrame();
robotFrame.setVisible(true);    
   }

 }


Console version Code:
  import java.util.*;
  class ExecuteCommandRuntime {
 public static void main(String args[])throws Exception {
   Scanner scanner = new Scanner(System.in);
    System.out.println("Enter the Command : ");
  String commandName = scanner.next();
  Runtime runtime = Runtime.getRuntime();
  runtime.exec(commandName);
 }
  }

Description:

This Program takes the input at the runtime and executes the command that given at runtime. Object of the Scanner class is created to take the input, System.in is the argument that is passed from the constructor which means we are taking the input from keyboard.
Runtime is a class that extends Object class. The object of Runtime class is created by calling the getRuntime() method by its class name that returns the runtime object associated with current Java application:

Runtime runtime = Runtime.getRuntime();

getRuntime() method is called directly by its class name because it is static method, so it is called without creating the object of the Runtime class.


Tuesday, March 11, 2014

Create a image slider sample using JavaScript and HTML5

An image slider is used to slide the images after every few seconds, now a days mostly used  in web designing and development, to attract the user of the website.
In JavaScript, create a simple array and then stores the path of image in that array. By using getElementById("") method we simply change the image using JavaScript.

Code:
 <html>
 <head>
 <script>
 var images = ["images/1.jpg", "images/2.jpg", "images/3.jpg"];
 var imgNum = 0;
 var imgLength = images.length - 1;
 function changeImage(direction) {
     imgNum = imgNum + direction;
     if (imgNum > imgLength) {
         imgNum = 0;
     }
     if (imgNum < 0) {
         imgNum = imgLength;
     }
     document.getElementById('slideshow').src = images[imgNum];
     return false; // prevent default link
 }
 window.setInterval(function() {
     changeImage(1);
 }, 3000);
 </script>
 <style>
img {
width: 800px;
height: 350px;
border-style:solid;
border-width:5px;
border-color:#5695C2;
}
 </style>
 </head>
 <body>
 <center>
 <img src="images/1.jpg" id="slideshow"><br/>
 <a href="#" onclick="return changeImage(-1);">Previous</a><br/>
 <a href="#" onclick="return changeImage(1);">Next</a>
 </center>
 </body>
 </html>

Create a folder and name it and put this .html file inside that and now create a folder inside this and name it images, put all images inside this folder and then rename the image name as defined in the JavaScript code 1.jpg, 2.jpg and 3.jgp.

Friday, March 7, 2014

HTML5 form submit and auto validation

Inside the form we have text input type and for auto validation we use the required attribute inside the input tag as:

<input type="text" name="user" required>

Code:
 <!DOCTYPE html>
 <html>
<head>
<title>HTML5 form submit</title>
</head>
<body bgcolor="pink">
<H1>HTML5 form submission</H1>
<form name="userRegForm">
<table>
<tr>
<td>Name</td>
<td><input type="text" name="user" required></td>
</tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fname" required></td>
</tr>
<tr>
<td>Email</td>
<td><input type="email" name="email" required></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pass" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
</form>
</body>
 </html>


required attribute works inside the form tag.

Thursday, March 6, 2014

Google maps using JavaScript

Here we are using the external JavaScript source that is provided by the google.
Now custom function initialize() that sets the google map to the div, the custom method have latitude and longitude values.

Code:
<!DOCTYPE html>
<html>
  <head>
    <style>
      #map_canvas {
        width: 100%;
        height: 600px;
      }
    </style>
    <script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script>
      function initialize() {
        var map_canvas = document.getElementById('map_canvas');
        var map_options = {
          center: new google.maps.LatLng(29.4000, 69.1833),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(map_canvas, map_options)
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map_canvas"></div>
  </body>
</html>

Wednesday, March 5, 2014

Get current date and time using JavaScript

To get the current date and time using JavaScript we have to use

new Date(); //this creates the date object

Assign this object value to the a string and show the value on HTML page.

Code:
 <!DOCTYPE html>
 <html>
<head>
<script>
function fetchDate() {
var val = new Date();
document.getElementById("dateVal").innerHTML=val;
}
</script>
</head>
<body>
<p id="dateVal">
<input type="button" value="Date" onClick="fetchDate()">
</body>
 </html>

Simple Calculator using JavaScript

Here we creating a simple calculator that add, subtract, multiply, divide the number and also find remainder. First of all we have to parse the string into integer value because the data on the html page is in string value so we have to cast it into integer value.

Use parseInt() method and pass the value of element by id as:

var v1 = parseInt(document.getElementById("textVal1").value);













Here we are using the external javascript file and use it into the html code by using the <script> tag and its attributes as
<script type="text/javascript" src="myscript.js"></script>

code of myscript.js file:

 function adding() {
var v1 = parseInt(document.getElementById("textVal1").value);
var v2 = parseInt(document.getElementById('textVal2').value);
document.getElementById("result").value = v1+v2;
 }

 function subtraction() {
var v1 = parseInt(document.getElementById("textVal1").value);
var v2 = parseInt(document.getElementById('textVal2').value);
document.getElementById("result").value = v1-v2;
 }

 function multiplication() {
var v1 = parseInt(document.getElementById("textVal1").value);
var v2 = parseInt(document.getElementById('textVal2').value);
document.getElementById("result").value = v1*v2;
}

 function division() {
var v1 = parseInt(document.getElementById("textVal1").value);
var v2 = parseInt(document.getElementById('textVal2').value);
document.getElementById("result").value = v1/v2;
 }

 function remainder() {
var v1 = parseInt(document.getElementById("textVal1").value);
var v2 = parseInt(document.getElementById('textVal2').value);
document.getElementById("result").value = v1%v2;
 }


 Code of Calculator.html file


 <!DOCTYPE html>
 <html>
<head>
<title>Calculator</title>
<script type="text/javascript" src="myscript.js"></script>
</head>
<body bgColor="cyan">
<h1 align="center">Simple Calculator using JS</h1>
<hr/>
<center>
<table border="0">
<tr>
<td align="right" colspan="5">Enter 1st value : <input type="text" size="20" value="" id="textVal1">                                        </td>
</tr>
<tr>
<td align="right" colspan="5">Enter 2nd value : <input type="text" size="20" value="" id="textVal2">                                            </td>
</tr>
<tr>
<td align="right" colspan="5">Result : <input type="text" size="20" id="result" value=""></td>
</tr>
<tr>
<td align="right"><input type="submit" style="height: 30px; width: 50px"  onClick="adding()" value="+"></td>
<td align="right"><input type="submit" style="height: 30px; width: 50px" onClick="subtraction()" value="-"></td>
<td align="right"><input type="submit" style="height: 30px; width: 50px" onClick="multiplication()" value="*"></td>
<td align="right"><input type="submit" style="height: 30px; width: 50px" onClick="division()" value="/"></td>
<td align="right"><input type="submit" style="height: 30px; width: 50px" onClick="remainder()" value="%"></td>
</tr>
</table>
<hr/>
</center>
</body>
 </html>

JavaScript If..... Else statements

The if statement is executed only when the specified condition is the true, if the first if condition is false then control is shifted to else if and execute it, if the else if condition is false then control is shifted to the else condition and execute it.

Syntax:

if(condition){//start of if body
      statement 1... executed if the condition is true
}//end of if body
else if(condition) {//start of if body
      statement 1... executed if the condition is true
}//start of if body
else {//start of else body
       statement 1... executed if the condition is true
}//start of else body

Demo:
Enter Day Name:

Code:
<!DOCTYPE html>
<head>
<script>
function WorkTime(){
var dayVal = document.getElementById("dayName").value;
if(dayVal.toUpperCase()=="MONDAY") {
alert("OOps! first day at office...");
}
else if(dayVal.toUpperCase()=="TUESDAY") {
alert("OOps! 2nd day at office...");
}
else if(dayVal.toUpperCase()=="WEDNESDAY") {
alert("OOps! 3rd day at office...");
}
else if(dayVal.toUpperCase()=="THURSDAY") {
alert("OOps! 4th day at office...");
}
else if(dayVal.toUpperCase()=="FRIDAY") {
alert("OOps! Tomorrow holiday enjoying in office");
}
else if(dayVal.toUpperCase()=="SATURDAY") {
alert("Enjoying Saturday at Home");
}
else if(dayVal.toUpperCase()=="SUNDAY") {
alert("Sleep time");
}
else {
alert("This is not a valid day...");
}
}
</script>
</head>
<body>
<table>
<tr>
<td>Enter Day Name:</td>
<td><input type="text" id="dayName"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Hit" onClick="WorkTime()"><td>
</tr>
</table>
</body>
</html>

Loop in Javascript

Types of loop in Javascript

for loop: The for loop repeats itself for the fixed number of time and it is used when you know that how many times the loop repeats itself.

Syntax:

for(initialization; condition; iteration){//start of loop body
          statement 1 ...
          statement 2 ...
          statement 3 ...
}//end of loop body

Code :
 <!DOCTYPE html>
<head>
<script>
function iterate(){
for(var i=0; i<5; i++) {
counter++;
document.write(counter+"<br/>");
}
</script>
</head>
<body>
<input type="submit" value="Hit" onClick="iterate()">
</body>
 </html>

while loop: A while loop will always evaluates the condition first. While the condition is true it repeats the block.

Syntax:

while(condition) {
        statement 1 ...
        ...
}

Code:
 <!DOCTYPE html>
<head>
<script>
var counter = 0;
function iterate(){
while(counter<5) {
document.write(counter+"<BR>");
counter++;
}
}
</script>
</head>
<body>
<input type="submit" value="Hit" onClick="iterate()">
</body>
 </html>

do while loop: do while loop also iterate itself on the condition but either condition is false it repeats itself at least once, it is also called as post-test loop because condition is tested when the block is executed.

Syntax

do {
    statement 1...
    ...
}while(condition)

Code:
 <!DOCTYPE html>
<head>
<script>
var counter = 0;
function iterate(){
do {
counter++;
document.write(counter+"<br/>");
}while(counter<6);
}
</script>
</head>
<body>
<input type="submit" value="Hit" onClick="iterate()">
</body>
 </html>



Javascript Events

The interaction of javascript with HTML is carried out through events, an event occurs when the user interacts with browser page.
List of javascript events:

Examples : onClick Event and here I am using internal javascript(embedded with HTML).

Demo 1


UserName :
Password :

Code for above demo 1:
 <!DOCTYPE html>
<head>
<script>
function Validate() {
var nameVal = document.getElementById("nameText").value;
var passVal = document.getElementById("passText").value;
if(nameVal=="" || passVal=="") {
alert("Name or password can't be Emplty");
}
else {
alert("Name : "+nameVal+"\nPassword : "+passVal);
}
}
</script>
</head>
<body>
<table>
<tbody>
<tr>
<td>UserName :</td>
<td><input id="nameText" type="text" /></td>
</tr>
<tr>
<td>Password :</td>
<td><input id="passText" type="password" /></td>
</tr>
<tr>
<td></td>
<td><input onclick="Validate()" type="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</body>
 </html>

Example: onKeypress Event.

Demo 2



Code for above demo 2:
 <!DOCTYPE html>
<head>
<script>
function hit() {
alert("key is pressed in side the textArea");
}
</script>
</head>
<body>
<textarea onkeypress="hit()"></textarea>
</body>
 </html>


List of JavaScript events:

Event Value Description
onchange script Script runs when the element changes
onsubmit script Script runs when the form is submitted
onreset script Script runs when the form is reset
onselect script Script runs when the element is selected
onblur script Script runs when the element loses focus
onfocus script Script runs when the element gets focus
onkeydown script Script runs when key is pressed
onkeypress script Script runs when key is pressed and released
onkeyup script Script runs when key is released
onClick script Script runs when a mouse click
ondblclick script Script runs when a mouse double-click
onmousedown script Script runs when mouse button is pressed
onmousemove script Script runs when mouse pointer moves
onmouseout script Script runs when mouse pointer moves out of an element
onmouseover script Script runs when mouse pointer moves over an element
onmouseup script Script runs when mouse button is released