Friday, December 12, 2014

How to Validate Image Extension in JavaScript ?



<!DOCTYPE>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Image extension validation in javascript</title>
<script type="text/javascript">
function checkExtension(filename)
{
 var n= filename.lastIndexOf(".");
 if(n != -1) //which means filename has . 
 {
  var st= filename.substring(n);
  if(st==".jpg" || st==".jpeg" || st==".png" || st==".gif")
  { //correct extension
   return true;
  }
   else
   { 
    //incorrect extension
   return false;
   }
 }
 else
 {
  //filname don't contains .
  return false;
 }
}
function check()
{
 var fname=document.frm.filename.value;
 if(fname=='')
 {
 alert('select image')
 return false;
 }
 else if(checkExtension(fname))
 return true;
 else 
 {
  alert('Invalid image file. Should be a image !!!')
 return false;
 }
}
</script>
</head>

<body>
<h1 align="center">Image extension validation in javascript.</h1>
<div align="center">
<form name="frm" onsubmit="return check()" method="post" action="go.html">
Select File: 
<input type="file" name="filename" id="filename" />
<br/> <br/>
<input type="submit" />
</form>
</div>
</body>
</html> 

Thursday, November 27, 2014

simple pagination in php





Below is the code to do a simple pagination in php:

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$rec_limit = 5;

$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydatabase');
/* Get total number of records */
$sql = "SELECT count(prd_code) as count_prd FROM Product_tab";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
$row = mysql_fetch_array($retval );
$rec_count = $row['count_prd'];

if( isset($_GET{'page'} ) )
{
   $page = $_GET{'page'} + 1;
   $offset = $rec_limit * $page ;
}
else
{
   $page = 0;
   $offset = 0;
}
$left_rec = $rec_count - ($page * $rec_limit);

$sql = "SELECT prd_code,prd_name,prd_price from product LIMIT $offset, $rec_limit";

$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval))
{
    echo "Product id :{$row['prd_code']}  <br> ".
      "Product name :{$row['prd_name']}  <br> ".
         "Price : {$row['prd_price']} <br> ".         "--------------------------------<br>";
} 

if( $page > 0 && !($left_rec < $rec_limit) )
{
   $last = $page - 2;
   echo "<a href=\"$_PHP_SELF?page=$last\">Previous 5 Records</a> |";
   echo "<a href=\"$_PHP_SELF?page=$page\">Next 5 Records</a>";
}
else if( $page == 0 )
{
   echo "<a href=\"$_PHP_SELF?page=$page\">Previous 5 Records</a>";
}
else if( $left_rec < $rec_limit )
{
   $last = $page - 2;
   echo "<a href=\"$_PHP_SELF?page=$last\">Previous 5 Records</a>";
}
mysql_close($conn);
?>


See the effect here:

First page:

Middle page:

Last page:


About me




That's me Avnish Alok, the guy behind this blog, a Software Engineer, Blogger, Freelancer and a true technology geek indeed. I believe in the ideology of BENJAMIN FRANKLIN great quote "He that can have patience can have what he will". I retain all such qualities to be a technology geek i:e; spend my much more time with computer, treating my pc as a family member, awake up at every morning with more passion to know about new tools & technologies, dig deeply to know more about each stuff.
                               Apart from my profession i love to write poems and reading novels as well. I write poems of genres like inspirational and romantic.

I hold my PG degree(MCA) in Information Technology and planning to do P.H.D in the same. As I’m a blogger, it is obvious to do blogging so, CS HOT TOPICS is the outcome. With the help of this blog I share my knowledge to my friends, my colleagues and to the entire world.  


ABOUT CS HOT TOPICS: 
 CS HOT TOPICS is a technical blog for open source enthusiasts that always updates with latest tools & technologies. As the name suggest it covers hot topics of computer programming in various languages(java, jsp, servlet, php, mysql, oracle) to name a few with latest tools(ajax, jquery). You can get more to visit here http://cshotopics.blogspot.com/

You can follow me on Google+, Facebook and Twitter, If you’d like to dig more about me.

 If you’ve any Queries about Add. and content Posting, or want to provide me your feedback so that i can improve this blog further, feel free to email me at avnishalok.se@gmail.com

Wednesday, November 26, 2014

how to configure xampp to send mail in php?




In order to send mail, you have to make some changes in your files if you are using XAMPP. Configure two files, first one is C:\xampp\php\php.ini and the second one is c:\xampp\sendmail\sendmail.ini

In C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for mailing sites like gmail for your localhost.

In php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = gmail-id@gmail.com
sendmail_path = "\"C:\xampp\sendmail\sendmail.exe\" -t"


Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
auth_username=gmail-id@gmail.com
auth_password=gmail-password
force_sender=gmail-id@gmail.com

Note: Replace gmail-id and gmail-password in above code with yours.

Note: If you are unable to send mail using your gmail accout then you need to make some changes in your gmail account setting like change Access for less secure apps must be enable. Login into your gmail accout and follow the link Gmail setting for less secure apps to configure your gmail account setting.

Click here to get code to send mail using php

how to send mail in php from localhost?




In previous chapter you got idea to configure your XAMPP. If you've configured then move to code to send mail and if not then configure at first. click here to configure.
Now it's time to write code in order to send mail. Below is the code to send mail using php:

<?php

$to = "your-gmail-id@gmail.com";
$subject = "HTML email using PHP";

$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body>
<p>This is an HTML Email send using php mail function.</p>
<table>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>
<tr>
<td>Avnish</td>
<td>alok</td>
</tr>
</table>
</body>
</html>
";

// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// More headers
$headers .= 'From: <your-gmail-id@gmail.com>' . "\r\n";

$chk=mail($to,$subject,$message,$headers);
if($chk)
echo "success";
else
echo "fail";
?>
 

Monday, November 24, 2014

Write For Us






CS HOT TOPICS is open for guest posts and blog advertisement now. If you want to write for us on computer programming and its related technologies, kindly contact us at avnishalok.se@gmail.com.
After getting your post we'll review it and if it looks good then we'll publish your post within 2 working days. Below are the list of topics for which you can write for us:

  • Computer languages and its related technologies
  • Mobile technology
  • Technical support

Tuesday, October 28, 2014

how to import database into oracle?




Import schemas(table,view,trigger,cursor etc.) into Oracle:

There are two ways to import shcemas.
 1. Using Directory
 2. Without using Directory

1. Using Directory:-

Step i.
  Create a folder at first in any drive.

Step ii. 
  Open SQL prompt and create a directory using given syntax:
   SQL> create directory directory-name as folder-name
 where directory-name is any name and folder-name must be what you've created in step 1.

Step iii. 
 Exit from sql prompt and write import command at command prompt using given synatx:
 C:\> impdp User/password dumpfile=file-name.dmp directory=directory-name remap_schema=Old User:New User
 where User is user-name with import privilege, password is the password for that user,  file name is exported dump file name with extension .dmp, directory-name is the same name what you created in step ii. and for remap_schema, old user is the user for which  you exported already the schema(table, view, function etc.)  and NewUser the user for which u want to import database.

Friday, October 24, 2014

how to export database in oracle?




Export schemas(table,view,trigger,cursor etc.) from Oracle:

There are two ways to export shcemas.
 1. Using Directory
 2. Without using Directory

1. Using Directory:-
Step i.
  Create a folder at first in any drive.

Step ii. 
  Open SQL prompt and create a directory using given syntax:
   SQL> create directory directory-name as folder-name
 where directory-name is any name and folder-name must be what you've created in step 1.

Step iii. 
 Exit from sql prompt and write export command at command prompt using given synatx:
 c:\> expdp User/password dumpfile=file-name.dmp directory=directory-name schemas=User
 where User is user-name with export priviledge, password is the password for that user, dump file name is any file name with extension .dmp, directory-name is the same name what you created in step ii. and schemas user is for which you want to export schemas(tables, views, function etc.)  

 Example:-

Here is the exported dump file:







2. Without using Directory:

 Remove (directory=directory-name) attribute from step iii above. So, syntax would be like this:
 Syntax:
  C:\>expdp user/password dumpfile=dump-file-name schemas=User
This time the dump file location would be default location of oracle. I'm using 10g express edition so my default file location is 'c:\oraclexe\app\oracle\admin\xe\dpdump\dump-file.dmp'. Default location may vary according to version. On command prompt see the 2nd line from last. This is your default dump-file location.

Example:

Friday, October 17, 2014

how to create dynamic table?



Sometimes ago, when i was developing a Web Application then i'd need to create dynamic table. I did google but nothing found useful for me. Then i decided to develop it by myself. Although it took some great time but yes, the outcome was fabulous.
Here is the code.
 Dyntable.js
function getVal()
{
var val=document.frm.txt1.value
var str="<table border='2'><tr> 
<th nowrap='nowrap'><font color='blue' size='2'>Item 1</font></th>
<th><font color='blue' size='2'>Item 2</font></th>
<th><font color='blue' size='2'>Item 3</font></th> 
</tr>" 
//validation logic for each table's cell 
var b=0;
while(val>0)
{
str=str+"<tr><td>
<input type='text' name='jtext"+ ++b 
+"' onBlur='if(isNaN(this.value)){ 
alert(\"value must be numeric !!!\") 
} 
else if(this.value<=0) 
{ alert(\"Value must be greater than zero !!!\") 
} '/></td><td><input type='text' name='jtext"+ ++b 
+"' onBlur='if(isNaN(this.value)){ 
alert(\"value must be numeric !!!\") } 
else if(this.value<=0) { 
alert(\"Value must be greater than zero !!!\") 
} '/></td><td>
<input type='text' name='jtext"+ ++b +"' 
onBlur='if(isNaN(this.value)){ 
alert(\"value must be numeric !!!\") } 
else if(this.value<=0) { 
alert(\"Value must be greater than zero !!!\") } '/>
</td></tr>";
val--;
} 
str=str+"</table>"; 

document.getElementById("spn").innerHTML=str;
} 

Htmlcode.html

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Dynamic table</title>
</head>
<script language="javascript" src="Dyntable.js"> </script>
<body>
<center>
<h1>Dynamic table</h1>
<form name="frm">
<input type="text" size="20" name="txt1">
</br></br>
<input type="button" value="ok" name="okbtn" onclick='getVal()'>
</form>
<p>
<span id="spn"></span>
</center>

</body>
</html>



Here is Output:


Saturday, October 11, 2014

what is php?



ABOUT PHP:

PHP (recursive acronym for PHP: Hypertext Preprocessor) is a widely-used open source server-side scripting language that is especially suited for web development and can be embedded directly into HTML. Much of its syntax is borrowed from C, Java and Perl with a couple of unique PHP-specific features. The goal of the language is to allow web developers to write dynamically generated pages quickly.
            As of January 2013, PHP was installed on more than 2.1 million web servers. PHP was Originally developed by Rasmus Lerdorf in 1994. PHP code can be simply mixed with HTML code, or it can be used in combination with various templating engines and web frameworks.

PHP VERSION:

VERSION RELEASED DATE
1.0 8 June 1995
2.0 1 November 1997
3.0 6 June 1998
1.7 July 19, 2011
2.5 January 24, 2012
3.0 September 27, 2012
4.0 22 May 2000
4.1 10 December 2001
4.2 22 April 2002
4.3 27 December 2002
4.4 11 July 2005
5.0 13 July 2004
5.2 2 November 2006
5.3 30 June 2009
5.4 1 March 2012
5.5 20 June 2013

SYNTAX:

The following Hello world program is written in PHP code embedded in an HTML document:
 
<!DOCTYPE html>
<html>
    <head>
        <title>PHP Test</title>
    </head>
    <body>
        <?php echo '<p>Hello World</p>'; ?>
    </body>
</html>

Friday, October 10, 2014

how to install joomla?

Installing Joomla!

Download the Joomla! 3.0.x full package at http://www.joomla.org/download.html
Create a new folder entitled “Joomla30” in folder “htdocs” in XAMPP folder. Normally it will be located at “C:\xampp\htdocs”
Unpack the downloaded package file into the folder “Joomla30”
Go to the URL “http://localhost/Joomla30”
Follow all steps in Joomla! installation:

Step 1. Main Configuration

  • Select Language: Choose your own language in the drop-down menu, for example, “English (United States)”
  • Site Name: Enter the name of your site
  • Description: Enter the description of your site
  • Site Offline: Choose status for your website when you access to your site: Click “Yes” for “offline” and “No” for “online”
  • Admin Email: Enter your valid email address you want to use for your site
  • Admin Username: Enter “admin” as default
  • Admin Password: Enter your own password
  • Confirm Admin Password: Re-type your password
  • Click “Next” to continue Step 2


Step 2. Database Configuration

  • Database Type: Select MySQLi
  • Host Name: Enter “localhost”
  • Username: Enter “root”
  • Password: let it blank
  • Database Name: enter the name of the database you created “Joomla30”
  • Table Prefix: let it generate automatically
  • Old Database Process: Click “Backup” to backup tables from former Joomla! installation, or “Remove” to delete these tables
  • Click “Next” to continue Step 3


Step 3. Overview 

  • Finalization: You can choose installing sample data or not, by clicking on corresponding selection.
  • Overview: This step is to review all information you configured in step 1. After checking, you click “Install”.
  • When installation finishes, you just need to click the button “Remove installation folder” button to complete the installation process. After that, you can either click on “Site” to see your newly created or “Administrator” to access the administration area.


Now you have installed your Joomla! site successfully! 

Sunday, October 5, 2014

what is joomla?





ABOUT  JOOMLA: 

Joomla was released on September 22, 2005. It is one of the most popular free content management systems (CMS) in the world that allows you to easily create and manage a dynamic website. It has an interface to control all the features and functionality this powerful CMS possesses. Furthermore, there are hundreds of free extensions written for Joomla that allows users to extend its functionality and customize it to their own objectives.

It is built on a model–view–controller web application framework that can be used independently of the CMS. Joomla is written in PHP, uses object-oriented programming (OOP) techniques (since version 1.5) and software design patterns. stores data in a MySQL, MS SQL (since version 2.5), or PostgreSQL (since version 3.0) database, and includes features such as page caching, RSS feeds, printable versions of pages, news flashes, blogs, polls, search, and support for language internationalization.

As of 2013, Joomla has been downloaded over 50 million times. Over 7,700 free and commercial extensions are available from the official Joomla! Extension Directory, and more are available from other sources.

JOOMLA VERSION:


VERSION RELEASED DATE
1.0 September 22, 2005
1.5 January 22, 2008
1.6 January 10, 2011
1.7 July 19, 2011
2.5 January 24, 2012
3.0 September 27, 2012
3.1 April 24, 2013
3.2 November 6, 2013
3.3 April 30, 2014
3.4 September 2014


Take a look of joomla 3:

joomla installation

Sunday, September 28, 2014

how to show Order derivation using program in java?


If a Sub Class extends a Super Class then Super class Default constructor would be call first and then Sub class Default constructor will be called.  If sub class calling its own Parameterized constructor and if super keyword is not available (i:e; super(parameter)) in Parameterized constructor of  sub class then Default constructor of Super class call first and then Sub class parameterized constructor will be call.

NOTE:-
To call Super class parameterized constructor from sub class parameterized constructor, must use ‘super(parameter)’ statement in Parameterized constructor of sub class, otherwise it will call super class Default constructor first and then call sub class parameterized constructor.


Ex:
SuperClass.java

public class SuperClass
{
private String s="string of superclass";
publicSuperClass()
 {
System.out.println("Super class Default Constructor");
  }

publicSuperClass(String s)
 {
this.s=s;
System.out.println("Super class parameterized Constructor");
  }
} // Close of class Super class
SubClass.java
class SubClass extends SuperClass
{
 String sub="string of subclass";
SubClass()
 {
System.out.println("Sub class Default Constructor");
  }

SubClass(String sub)
 {
super("Avnish"); 
this.sub=sub;
System.out.println("Sub class parameterized Constructor");
  }

public static void main(String[] arg)
 {
SubClasssubobj=new SubClass();
newSubClass("Avnishalok");
  }



}


Output:
Super class Default Constructor
Sub class Default Constructor
Super class parameterized Constructor
Sub class parameterized Constructor


If the statement super("Avnish"); is omitted then the output:
Super class Default Constructor
Sub class Default Constructor
Super class Default Constructor
Sub class parameterized Constructor

Friday, September 26, 2014

how to create a textfield that holds only upper case characters in java?





 The following piece of code will create a field that holds only upper case characters. It will work even if text is pasted into from the clipboard.


 UpperCaseField.java

import javax.swing.*;

import javax.swing.text.Document;

import javax.swing.text.PlainDocument;

import javax.swing.text.AttributeSet;

import javax.swing.text.BadLocationException;



public class UpperCaseField extends JTextField {



     public UpperCaseField(int cols) {

         super(cols);

     }



     protected Document createDefaultModel() {

         return new UpperCaseDocument();

     }



     static class UpperCaseDocument extends PlainDocument {



         public void insertString(int offs, String str, AttributeSet a)

             throws BadLocationException {



             if (str == null) {

                 return;

             }

             char[] upper = str.toCharArray();

             for (int i = 0; i < upper.length; i++) {

                 upper[i] = Character.toUpperCase(upper[i]);

             }

             super.insertString(offs, new String(upper), a);

         }

     }



 }




main.java


import javax.swing.*;

import java.awt.*;



class main extends JFrame

{

UpperCaseField ucf;

Container c;

main()

{

c=getContentPane();

c.setLayout(null);

setTitle("Text");

setBounds(120,100,500,350);

setVisible(true);

setResizable(false);

JLabel lbl=new JLabel("Upper Case:");

lbl.setBounds(10,10,100,30);

c.add(lbl);

ucf=new UpperCaseField(30);

ucf.setBounds(120,10,350,30);

c.add(ucf);

setContentPane(c);

setDefaultCloseOperation(EXIT_ON_CLOSE);

}

public static void main(String[] arg)

{

 new main();

}



}



OUTPUT:-

Thursday, May 22, 2014

how to use list in java ?





A JList presents the user with a group of items, displayed in one or more columns, to choose from. Lists can have many items, so they are often put in scroll panes.

In addition to lists, the following Swing components present multiple selectable items to the user: combo boxes, menus, tables, and groups of check boxes or radio buttons. To display hierarchical data, use a tree.



ListTest.java

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import javax.swing.ButtonGroup;
import javax.swing.JList;
import javax.swing.JRadioButton;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
/*
 This program demonstrates a simple fixed list of strings.
*/

public class ListTest
{
 public static void main(String[] args)
  {
   JFrame frame = new ListFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setVisible(true);
  }
}

  /**
     This frame contains a word list and a label that shows a
     sentence made up from the chosen words. Note that you can
     select multiple words with Ctrl+click and Shift+click.
  */

class ListFrame extends JFrame
{
 public ListFrame()
  {
   setTitle("ListTest");
   setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
   String[] words =
   {
    "quick","brown","hungry","wild","silent",
    "huge","private","abstract","static","final"
   };
   wordList = new JList(words);     // To create List box.
   /* Alternatively, you can use an anonymous array:
    JList wordList = new JList(new String[] {"quick", "brown", "hungry", "wild","silent","huge","private","abstract","static","final" });
   */
/*
By default, the list component displays eight items; use the setVisibleRowCount method to change that value:
wordList.setVisibleRowCount(4); // display 4 items
You can also restrict the user to a more limited selection mode with the setSelectionMode method:
wordList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// select one item at a time
wordList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
// select one item or one range of items
*/
   wordList.setVisibleRowCount(4);
 //List boxes do not scroll automatically. To make a list box scroll, you must insert it into a scroll pane:
   JScrollPane scrollPane = new JScrollPane(wordList);
   listPanel = new JPanel();
   listPanel.add(scrollPane);
   wordList.addListSelectionListener(new ListSelectionListener()
   {
   public void valueChanged(ListSelectionEvent event)
    {
/*
The getSelectedValues method returns an array of objects containing all selected items. Cast each array element to a string.
Object[] values = list.getSelectedValues(); //returns the selected values or an empty array if the selection is empty.
for (Object value : values)
do something with (String) value;
.......................................................
If your list does not allow multiple selections, you can call the convenience method getSelectedValue. It returns the first selected value (which you know to be the only value if multiple selections are disallowed).
String value = (String) list.getSelectedValue();
*/
   Object[] values = wordList.getSelectedValues();
   StringBuilder text = new StringBuilder(prefix);
   // for (int i = 0; i < values.length; i++)
   for (Object value : values)
   {
    //String word = values[i];
    String word = (String) value;
    text.append(word);
    text.append(" ");
  }
 text.append(suffix);
 label.setText(text.toString());
}
});
 buttonPanel = new JPanel();
 group = new ButtonGroup();
/*
You can set the layout orientation to one of three values:
JList.VERTICAL (the default): arrange all items vertically
JList.VERTICAL_WRAP: start new columns if there are more items than the visible row count
JList.HORIZONTAL_WRAP: start new columns if there are more items than the visible row count, but fill them horizontally.
*/
   makeButton("Vertical", JList.VERTICAL);
   makeButton("Vertical Wrap", JList.VERTICAL_WRAP);
   makeButton("Horizontal Wrap", JList.HORIZONTAL_WRAP);
   add(listPanel, BorderLayout.NORTH);
   label = new JLabel(prefix + suffix);
   add(label, BorderLayout.CENTER);
   add(buttonPanel, BorderLayout.SOUTH);
 }
/**
 Makes a radio button to set the layout orientation.
 @param label the button label
 @param orientation the orientation for the list
*/
 private void makeButton(String label, final int orientation)
 {
  JRadioButton button = new JRadioButton(label);
  buttonPanel.add(button);
  if (group.getButtonCount() == 0) button.setSelected(true);
   group.add(button);
   button.addActionListener(new java.awt.event.ActionListener()
   {
   public void actionPerformed(ActionEvent event)
    {
    wordList.setLayoutOrientation(orientation);
    listPanel.revalidate();
    }
 });
 }
  private static final int DEFAULT_WIDTH = 400;
  private static final int DEFAULT_HEIGHT = 300;
  private JPanel listPanel;
  private JList wordList;
  private JLabel label;
  private JPanel buttonPanel;
  private ButtonGroup group;
  private String prefix = "The ";
  private String suffix = "fox jumps over the lazy dog.";
}

/*
List components do not react to double clicks from a mouse. As envisioned by the designers of Swing, you use a list to select an item, and then you click a button to make something happen. However, some user interfaces allow a user to double-click on a list item as a shortcut for item selection and acceptance of a default action. If you want to implement this behavior, you have to add a mouse listener to the list box, then trap the mouse event as follows:
public void mouseClicked(MouseEvent evt)
{
if (evt.getClickCount() == 2)
 {
  JList source = (JList) evt.getSource();
  Object[] selection = source.getSelectedValues();
  doAction(selection);
 }
}
*/
 OUTPUT:-

how to edit and display combobox item in java?




A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.


comboboxd.java

package packge;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class comboboxd extends JFrame implements ItemListener,ActionListener
{
JComboBox box,box1;
JLabel lbl;
JButton b1,b2,b3;
public comboboxd()
{
Container c=getContentPane();
c.setLayout(new FlowLayout());
c.setBackground(Color.cyan);
box=new JComboBox();
box1=new JComboBox();
lbl=new JLabel();
lbl.setFont(new Font("Arial black",Font.BOLD,12));
b1=new JButton("Set");
b2=new JButton("Show Index");
b3=new JButton("Item at Index");
box.addItem("India");
box.addItem("America");
box.addItem("Germany");
box.addItem("Japan");
box.addItem("France");
box.setEditable(true);      // To edit in ComboBox
box1.addItem("Africa");
box1.addItem("America");
box.addItemListener(this);
box1.addItemListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add(box);
c.add(box1);
c.add(b1);
c.add(b2);
c.add(b3);
c.add(lbl);
}

public void itemStateChanged(ItemEvent ie)
{
/*
itemStateChanged method called twice because it runs when item is selected or deselected.
above problem is resolved using getStateChange() method.
getStateChange() method returns 1 for selected item and 2 for
*/
//deselected item.
int select=ie.getStateChange();
if(select==1)
{
//if box1 item is clicked then perform the logic
if(ie.getSource()==box)
{
String str=String.valueOf(box.getSelectedItem());
lbl.setText("You selected:" +str+" of ComboBox1");
}
//if box2 item is clicked then perform the logic
if(ie.getSource()==box1)
{
/*hello will print twice because itemStateChanged() method
called twice. one for item selected and second for item
deselected.
*/
System.out.println("hello");
String str=String.valueOf(box.getSelectedItem());
lbl.setText("You selected:" +str+" of ComboBox2");
}
}//close of if(select==1)
}//close of itemStateChanged(ItemEvent ie)

public void actionPerformed(ActionEvent ae)
{ 
if(ae.getSource()==b1)
 box.addItem(box.getSelectedItem());
if(ae.getSource()==b2)
 lbl.setText("Your selected Item  index: " +String.valueOf(box.getSelectedIndex()));
if(ae.getSource()==b3)
 lbl.setText("Item at Index: " +String.valueOf(box.getSelectedIndex()) +" is "+String.valueOf(box.getItemAt(box.getSelectedIndex())));
}

public static void main(String args[])
{
comboboxd demo=new comboboxd();
demo.setTitle("combo Box");
demo.setSize(850,300);
demo.setVisible(true);
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

OUTPUT:-

how to use combobox in java?





A component that combines a button or editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, then the combo box includes an editable field into which the user can type a value.

combotest1.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class combotest1 extends JFrame implements ComponentListener

{

JComboBox box;

combotest1()

{

Container c=this.getContentPane();

c.setLayout(new FlowLayout());

box=new JComboBox();

box.setToolTipText("Combo Box");

box.addItem("Apple");

box.addItem("Mango");

box.addItem("Orange");

box.addItem("Banana");

box.addItem("Guava");

box.setBounds(60,20,80,20);

this.addComponentListener(this);

c.add(box);

setResizable(false); //not resizable

setLocation(400,250);

} //close of default constructor

public void componentResized(ComponentEvent e) { }

public void componentMoved(ComponentEvent e)

            {

                        this.setLocation(400,250);

            }

public void componentShown(ComponentEvent e)   { }

public void componentHidden(ComponentEvent e)              { }

public static void main(String args[]){

combotest1 obj=new combotest1();

obj.setVisible(true);

obj.setSize(200,150);

obj.setTitle("Combo Box");

obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}


OUTPUT:-

 

how to use checkbox in java?





A check box provides a way to make a single on/off choice. It consists of a tiny box and a label. The box typically holds a little “x” (or some other indication that it is set) or is empty, depending on whether that item was selected.   You’ll normally create a JCheckBox using a constructor that takes the label as an argument. You can get and set the state, and also get and set the label if you want to read or change it after the JCheckBox has been created.  Whenever a JCheckBox is set or cleared, an event occurs, which you can capture the same way you do a button by using an ActionListener.

                      The following example uses a JTextArea to enumerate all the check boxes that have been checked. The trace( ) method sends the name of the selected JCheckBox and its current state to the JTextArea using append( ), so you’ll see a cumulative list of the checkboxes that were selected and what their state is.



CheckBoxes.java
 
import javax.swing.*;

import java.awt.event.*;

import java.awt.*;



public class CheckBoxes extends JFrame {

private JTextArea t = new JTextArea(6, 15);

private JCheckBox

cb1 = new JCheckBox("Check Box 1"),

cb2 = new JCheckBox("Check Box 2"),

cb3 = new JCheckBox("Check Box 3");

CheckBoxes() {

super("CheckBox Demo");

cb1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

trace("1", cb1);

}

});

cb2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

trace("2", cb2);

}

});

cb3.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

trace("3", cb3);

}

});

Container cp = getContentPane();

cp.setLayout(new FlowLayout());

cp.add(new JScrollPane(t));

cp.add(cb1);

cp.add(cb2);

cp.add(cb3);

}

private void trace(String b, JCheckBox cb) {

if(cb.isSelected())

t.append("Box " + b + " Set\n");

else

t.append("Box " + b + " Cleared\n");

}

public static void main(String[] args) {

CheckBoxes chkbox= new CheckBoxes();

//chkbox.setSize(300,300);

chkbox.pack();

chkbox.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

chkbox.setVisible(true);



}

}


OUTPUT:-


Wednesday, May 21, 2014

how to change the width of a textfield dynamically in java?





JTextField textField = new JTextField("Default input", 10);
textField.setColumns(20);
panel.validate();

 After changing the size of a text box with the setColumns method, you need to call the validate method of the surrounding container. The validate method recomputes the size and layout of all components in a container. After you use the validate method, the layout manager repaints the container, and the changed size of the text field will be visible.

In general, you want to let the user add text (or edit the existing text) in a text field. Quite often these text fields start out blank. To make a blank text field, just leave out the string as a parameter for the JTextField constructor:

JTextField textField = new JTextField(20);

You can change the contents of the text field at any time by using the setText method from the TextComponent parent class. For example:

textField.setText("Hello!");

You can find out what the user typed by calling the getText method. This method returns the exact text that the user typed. To trim any extraneous leading and trailing spaces from the data in a text field, apply the trim method to the return value of getText:

String text = textField.getText().trim();

To change the font in which the user text appears, use the setFont method.



Jtextfld.java

import java.awt.BorderLayout;

import java.awt.EventQueue;



import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.border.EmptyBorder;

import javax.swing.JLabel;

import javax.swing.JTextField;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;





public class Jtextfld extends JFrame {



            private JPanel contentPane;

            private JTextField textField;



            /**

             * Launch the application.

             */

            public static void main(String[] args) {

                        EventQueue.invokeLater(new Runnable() {

                                    public void run() {

                                                try {

                                                            Jtextfld frame = new Jtextfld();

                                                            frame.setVisible(true);

                                                } catch (Exception e) {

                                                            e.printStackTrace();

                                                }

                                    }

                        });

            }



            /**

             * Create the frame.

             */

            public Jtextfld() {

                        setAlwaysOnTop(true);

                        setResizable(false);

                        setTitle("TextFiled ");

                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

                        setBounds(100, 100, 425, 256);

                        contentPane = new JPanel();

                        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));

                        setContentPane(contentPane);

                        contentPane.setLayout(null);

                      

                        JLabel lblNewLabel = new JLabel("            Change TextFiled width");

                        lblNewLabel.setBounds(94, 11, 197, 38);

                        contentPane.add(lblNewLabel);

                      

                        textField = new JTextField(); //new JTextField(10); or textField.setColumns(10); or textField.setSize(int width,int height);

                      

                        textField.setBounds(144, 86, 86, 20);

                        contentPane.add(textField);

                        textField.setColumns(10);

                      

                        JButton btnNewButton = new JButton("Original width");

                        btnNewButton.addActionListener(new ActionListener() {

                                    public void actionPerformed(ActionEvent arg0) {

                                                textField.setSize(86, 20);

                                    }

                        });

                        btnNewButton.setBounds(70, 171, 117, 23);

                        contentPane.add(btnNewButton);

                      

                        JButton btnChangeWidth = new JButton("Change width");

                        btnChangeWidth.addActionListener(new ActionListener() {

                                    public void actionPerformed(ActionEvent arg0) {

                                                textField.setSize(140, 20);

                                              

                                    }

                        });

                        btnChangeWidth.setBounds(246, 171, 117, 23);

                        contentPane.add(btnChangeWidth);

            }

}



OUTPUT:-