Wednesday, December 31, 2008


Disable Keyboard Editing in JSpinner

A simple example on JSpinner. In the example, the editing mode is disabled using setEditable() method. So it will not be possible to insert numbers with the help of keyboard :


import javax.swing.*;
import java.awt.*;

public class Disablekeyboard{
public static void main(String[] args){
JFrame frm = new JFrame("Disable Keyboard Editing Example");
JSpinner spinner = new JSpinner();
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor())
.getTextField();
tf.setEditable(false);
spinner.setValue(new Integer(100));
JPanel panel = new JPanel();
panel.add(spinner);
frm.add(panel, BorderLayout.NORTH);
frm.setSize(350, 350);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Thursday, October 16, 2008


Java sort() Method Example

If you want to sort string characters then this example is the best for you. The sort() method sort words in ascending order. Look a simple example of sort() method given below :

import java.util.*;
import java.io.*;
import java.lang.String;

public class sortstr{
public static void main(String args[]){
String str = "Java String Example";
char[] content = str.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
System.out.println(content);
}
}

Result : EJSaaegilmnprtvx


Friday, September 26, 2008


Show Icon on The Button

With the help of java swing, you can add images, icons in the application to make your GUI application interface more attractive. With the help of this example, you can learn how to add image on the button or other control. This example expain you add image file. The code is given below :

import javax.swing.*;
import java.awt.*;

public class IconButton{
public static void main(String[] args){
JFrame frame = new JFrame("Swing Icon Example");
JButton button = new JButton("My Button");
Icon imgicon = new ImageIcon("smiley_icon.gif");
JPanel panel = new JPanel();
button.setIcon(imgicon);
panel.add(button);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(380, 380);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Saturday, September 13, 2008


Swing Input Dialog Box

Input dialog box in java is the good example of user input example in GUI environment. A user can input value at run time in small window. The input box also contains "OK" and "Cancel" button. The code below is the example to create an input box where user enter either text or numeric value at run time :

import javax.swing.*;
import java.awt.event.*;

public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Example");
JButton button = new JButton("Click for Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String txt = JOptionPane.showInputDialog(null, "Enter Your Text : ",
"Input Box", 1);
if(txt != null)
JOptionPane.showMessageDialog(null, "The text you have entered : " + txt,
"Input Box", 1);
else
JOptionPane.showMessageDialog(null, "You clicked on cancel button.",
"Input Box", 1);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Tuesday, September 2, 2008


Comparing Two Strings Using equals()

The given example show you how to compare two strings with the help of equals() method in java. The equals() method is used to compare the contents of objects. The method returns value in either "true" or "false". The code give below compare two strings whether both are equal or not. If both are same then it returns true else not :

import java.lang.*;
import java.io.*;

public class equalstrings{
public static void main(String[] args) throws IOException{
System.out.println("String Compares Example Using Equals() Method");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter First String:");
String str1 = bf.readLine();
System.out.println("Enter Second String to Compare :");
String str2 = bf.readLine();
if (str1.equals(str2)){
System.out.println("Both the Strings are Equal!");
}
else{
System.out.println("Both the Strings are not Equal!");
}
}
}


Saturday, August 23, 2008


Java String Length Example

If you want to count the lenght of the string in java then use lenght() method that returns integer value of a string entered by the user. Below is the example that calculate the length of the string :

import java.lang.*;
import java.io.*;

public class Strlen{
public static void main(String[] args) throws IOException{
System.out.println("Count the Lenght of String");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String str = bf.readLine();
int len = str.length();
System.out.println("Length of Text : " + len);
}
}


Tuesday, July 1, 2008


Java Prime Number Example

What is Prime Number?

Definition : A prime number is a natural number that has only two divisor. Either it is divisible by 1 or itself and it is greater than 1. So we can say it has only one divisor means it can only divided by itself.

Here is the example of prime number in Java. It display all the prime numbers between 1 and the limit entered by user. Get the source code of prime number example here :

import java.io.*;
class Primenumberexample {
public static void main(String[] args) throws Exception{
BufferedReader bf = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter Limit to Print Prime Number :");
int k = Integer.parseInt(bf.readLine());
System.out.println("Prime Numbers Are : ");
for (int i=1; i < k; i++ ){
for (int j=2; j < i; j++){
int a = i%j;
if (a==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
}
}


Monday, June 30, 2008


How to Calculate Area of Rectangle?

This example explain you how to calculate area of a rectangle using java code. For calculating area of rectangle, we need three variables. One for length, one for breadth and one variable calculate the area of rectangle. We have already read and know how to calculate area of rectangle using formula a=lXb. Here is the source code to find the area of rectangle :

class Rectangleexample
{
public static void main(String[] args)
{
int len=5, breadth=7, area=1;
area = len*breadth;
System.out.println("Area if Rectangle :" + area);
}
}


Saturday, June 21, 2008


Count Vowels Example in Java

This example show you how to check and calculate how many vowel are in the string entered by user. With the help of for loop, we calculate how many vowels a user entered in the string. Here is the source code :

import java.lang.String;
import java.io.*;
import java.util.*;

public class vowels{

public static void main(String args[])throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter New String to Check :");
String text = bf.readLine();
int cnt = 0;
for (int a = 0; a < text.length(); a++) {
char b = text.charAt(a);
if (b=='a' || b=='e' || b=='i' || b=='o' || b=='u') {
cnt++;
}
}
System.out.println("Total Vowels are" + " : " + cnt);
}
}


Tuesday, June 17, 2008


How to Create Checkbox in Java Swing?

What is Check Box?

A check box or tick box is a graphical user interface element that allow or permits user to make selections from the options. User can select more than one item or element.

The given example will explain you how to create check box in java swing. It is created in java by creating the instance of JCheckBo class. Here is the check box program :


public class CreateCheckBox{
public static void main(String[] args){
JFrame frame = new JFrame("The Check Box Example");
JCheckBox chk = new JCheckBox("Check Box 1");
JCheckBox chk = new JCheckBox("Check Box 2");
JCheckBox chk = new JCheckBox("Check Box 3");
frame.add(chk);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Tuesday, May 27, 2008


Java String Trim Example

The string trim() method remove the blank spaces from the left and right in the given string.

Here is the example how to remove blank spaces :

import java.lang.*;
public class StringTrim{
public static void main(String[] args) {
System.out.println("Source code of String Trim Method");
String str = " blankspaces ";
System.out.println("Entered String :" + str);
System.out.println("Output of the Program :" +str.trim());
}
}


Friday, April 18, 2008


Display Time in JSpinner : Swing Examples

Spinner allow user to select and type the value from a range of values. It has no drop-down list and this reason it is different to combo box. Here is the example to display time in JSpinner and also edit the time :

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class ShowTimeJSpinner{
public static void main(String[] args) {
ShowTimeJSpinner h = new ShowTimeJSpinner();
}

public ShowTimeJSpinner(){
JFrame frame = new JFrame("JSpinner Time Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
JSpinner spinner = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm");
spinner.setEditor(de);
frame.add(spinner,BorderLayout.NORTH);
frame.setSize(100,100);
frame.setVisible(true);
}
}


Saturday, March 29, 2008


How to Create Combo Box : Java Swing Example

You will learn how to insert combo-box using Swing in Java. Combox box is used display item in drop down list. It provides option to select an item from the drop down. The basic difference between combo box and list box is that user cannot select multiple item from combo-box but it can be possible in list box.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}

public ComboBox(){
String course[] = {"India","Germany","America","Russia"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}


Thursday, March 20, 2008


Maximize a Frame using Swing

In this program, you will learn how to maximize a frame using setMaximizedBounds() to set the bounds for a maximized frame. Here is the source code :

import java.awt.*;
import javax.swing.*;

public class SwingSetBounds{
public static void main(String[] args){
JFrame frame = new JFrame();
Rectangle bounds = new Rectangle(0, 0, 500, 500);
frame.setMaximizedBounds(bounds);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Monday, March 3, 2008


Print Triangle using "*"

This example is for the beginners. If you want to draw a traingle using "*" then use the code given below to print star in triangle shape :

import java.io.*;

class startriangle{
public static void main(String[] args) {
try{
BufferedReader object = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the number");
int a= Integer.parseInt(object.readLine());
for (int i=1; i<'a;i++ ){
for (int j=1; j<=i;j++ ){
System.out.print("*");
}
System.out.println("");
}
}
catch(Exception e){}
}
}


Wednesday, February 27, 2008


Swing Tutorials : Swing Toolbar Example

Have you see some small icons on top in Microsoft Word, Excel or other application. It is known as shortcut toolbar. Here is the example how to create toolbar using Java Swing :

import javax.swing.*;
import java.awt.*;

public class ToolbarExample{
public static void main(String[] args) {
JFrame frame = new JFrame("Toolbar Example Using Java Swing");
JToolBar toolbar = new JToolBar("toolBar", JToolBar.HORIZONTAL);
JButton cutbutton = new JButton(new ImageIcon("cut.gif"));
toolbar.add(cutbutton);
JButton copybutton = new JButton(new ImageIcon("copy.gif"));
toolbar.add(copybutton);
JButton pastebutton = new JButton(new ImageIcon("paste.gif"));
toolbar.add(pastebutton);
frame.getContentPane().add(toolbar,BorderLayout.NORTH);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,400);
frame.setVisible(true);
}
}


Monday, February 25, 2008


Java Example : Sum of Two Numbers

A very simple example to add 2 numbers. Use Integer.parseInt to convert the value in integer. By default it will consider the value as string.

public class AddNumbers{
public static void main(String[] args) {
System.out.println("Addition of two numbers!");
int a = Integer.parseInt(args[0]);
int b = Integer.parseInt(args[1]);
int sum = a + b;
System.out.println("Sum: " + sum);
}
}


Friday, February 22, 2008


Remove Title Bar : Java Swing Code

This java swing example explain you how to remove title bar from the frame. Here is the example code :

import
javax.swing.*;
public class RemoveTitleFrame{
public static void main(String[] args) {
JFrame frame = new JFrame(Frame With No Title Bar);
frame.setUndecorated(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}


Monday, February 18, 2008


Java : List Prime Numbers between 1 to Given Number

This program find the even numbers between 1 to the number enter by user :

import java.io.*;
class AllEvenNum{
public static void main(String[] args) {

try{

BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a Number : ");
int num = Integer.parseInt(br1.readLine());
System.out.println("Even Numbers are:");
for (int i=1;i <=num ; i++){
if(i%2==0 ){
System.out.print(i+",");
}
}
}
catch(Exception e){}
}
}


Monday, February 11, 2008


Table of a Given Number : Java Example

This example explain how to print table of a given number. This is useful example of a java program for the beginners using while loop. We can also use for loop to print table :

Tableexample{
public static void main(String[] args) {
int a=5, b=1;
System.out.println("table of "+a+"= ");
while(b<=10){
int c = a*b;
System.out.println(c);
b = b+1;
}
}
}


Thursday, February 7, 2008


Check a Number : Even or Odd?

A very simple program to find whether a number is odd or even. As we have taken 4 to check whether it is even or not. It is even because when we divide it by 2 then the reminder will be 0.

class Evenodd
{
public static void main(String args[])
{
int a = 4;
if((a % 2) == 0)
System.out.print("Number is even");
else
System.out.println("Number is odd");

}
}


Tuesday, January 15, 2008


Java Swing Example

A part of Sun Microsystems Java Foundation classes (JFC) is a widget toolkit for providing a graphical user interface. It consists of many tools including boxes, combo box, list box, buttons, dialog boxes, tables etc.

It is very interesting part of Java programming. It is the favorite topic of all the java programmers. We can customize the components and use it according to our requirements. Lets start with first program :

This program explain you how to create text area using Java swing. Here we are using javax.swing package to create GUI component. The text area will be created on panel in the frame :

import javax.swing.*;
public class TextAreaCode {
public static void main(String[] args){
JFrame frame= new JFrame("TextArea-Frame Program");
JPanel panel=new JPanel();
JTextArea jt= new JTextArea("TextArea Example",4,20);
frame.add(panel);
panel.add(jt);
frame.setSize(250,250);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Click Here for More example on Java Swing


Tuesday, January 8, 2008


Popup Menu in Java

It is very interesting java program using java awt. Here is the program code to create popup menu when your press right mouse button.

import javax.swing.*;

import java.awt.event.*;

public class PopUpMenu{

JPopupMenu Pmenu;
JMenuItem menuItem;

public static void main(String[] args) {

PopUpMenu p = new PopUpMenu();


}



public PopUpMenu(){

JFrame frame = new JFrame("Popup Menu Example");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Pmenu = new JPopupMenu();

menuItem = new JMenuItem("New");

Pmenu.add(menuItem);

menuItem = new JMenuItem("Open");

Pmenu.add(menuItem);

menuItem = new JMenuItem("Save");

Pmenu.add(menuItem);

menuItem = new JMenuItem("Cut");

Pmenu.add(menuItem);

menuItem = new JMenuItem("Paste");

Pmenu.add(menuItem);

menuItem.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e){}

});


frame.addMouseListener(new MouseAdapter(){

public void mouseReleased(MouseEvent Me){

if(Me.isPopupTrigger()){


Pmenu.show(Me.getComponent(), Me.getX(), Me.getY());

}

}

});


frame.setSize(400,400);

frame.setVisible(true);

}