Input box in java

Complete source code below will show you, how to create simple input box that will prompt some input from user. We will use predefined java class, JOptionPane to create simple input box. If you want your input box appear in a container, you can change null in source code below to target container.You can see example by click here.

*************************************************************************
COMPLETE SOURCE CODE FOR : JavaInputDialog.java
*************************************************************************


import javax.swing.JOptionPane;

public class JavaInputDialog
{
public static void main(String[]args)
{
//Pop up an input box with text ( What is your name ? )
String a=JOptionPane.showInputDialog(null,"What is your name ?");

//Print into command prompt what you put into input dialog box
System.out.println("My name is : "+a);
}
}


*************************************************************************
JUST COMPILE AND EXECUTE IT
*************************************************************************

Message box appear in JFrame

Complete source code below will show you, how to make message box appear in a container.

**********************************************************************
COMPLETE SOURCE CODE FOR : MessageBoxAppearInJFrame.java
**********************************************************************


import javax.swing.JOptionPane;

import javax.swing.JFrame;

public class MessageBoxAppearInJFrame
{
public static void main(String[]args)
{
//Create a window using JFrame with title ( Message box appear in JFrame )
JFrame frame=new JFrame("Message box appear in JFrame");

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(400,400);

//Make JFrame locate at center on screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);


//Pop up a message box with text ( I am a message dialog ) in created JFrame
JOptionPane.showMessageDialog(frame,"I am a message dialog");
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

Create message box in java

Complete source code below will show you, how to create message box in java. We will use JOptionPane class to create message box. If you want your message box appear in a container, you can change null in source code below to target container.You can see example by click here.

************************************************************************
COMPLETE SOURCE CODE FOR : JavaMessageDialog.java
************************************************************************


import javax.swing.JOptionPane;

public class JavaMessageDialog
{
public static void main(String[]args)
{
//Pop up a message box with text ( I am a message dialog )
JOptionPane.showMessageDialog(null,"I am a message dialog");
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************

Read floating point number user input in java

Complete source code below, will show you how to wait and read floating point number user input in command prompt.

********************************************************************
COMPLETE SOURCE CODE FOR : ReadFloatingPointNumberUserInput.java
********************************************************************


import java.util.Scanner;

public class ReadFloatingPointNumberUserInput
{
public static void main(String[]args)
{
try
{
//Create a scanner object
//Scanner is a predefined class in java that will be use to scan text
//System.in is mean, we will receive input from standard input stream
Scanner readUserInput=new Scanner(System.in);

//Print into command prompt(Put a floating point number : )
System.out.print("Put a floating point number : ");

//Wait and READ FLOATING POINT NUMBER from user input after user hit 'Enter'
float myPointNumber=readUserInput.nextFloat();

//Print what store in myPointNumber
System.out.println("My floating point number is : "+myPointNumber);
}
catch(Exception exception)
{
//Error that will be print if user put other than floating point number
System.out.println("Hey !!! Don't put other than floating point number");
}
}
}


********************************************************************
JUST COMPILE AND EXECUTE IT
********************************************************************

Read integer user input in java

Complete source code below, will show you how to wait and read integer user input in command prompt.

**********************************************************************
COMPLETE SOURCE CODE FOR : ReadIntegerUserInput.java
**********************************************************************


import java.util.Scanner;

public class ReadIntegerUserInput
{
public static void main(String[]args)
{
try
{
//Create a scanner object
//Scanner is a predefined class in java that will be use to scan text
//System.in is mean, we will receive input from standard input stream
Scanner readUserInput=new Scanner(System.in);

//Print into command prompt(What is your age ?)
System.out.println("What is your age ?");

//Wait and READ INTEGER INPUT from user after user hit 'Enter'
int myAge=readUserInput.nextInt();

//Print what store in myAge
System.out.println("Your age is : "+myAge);
}
catch(Exception exception)
{
//Error that will be print if user put other than number include
//point number
System.out.println("Hey !!! Don't put other than number");
}
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

Read a word user input in java

Complete source code below, will show you how to wait and read only a word from user input in command prompt.

*****************************************************************
COMPLETE SOURCE CODE FOR : ReadOneWordUserInput.java
*****************************************************************


import java.util.Scanner;

public class ReadOneWordUserInput
{
public static void main(String[]args)
{
//Create a scanner object
//Scanner is a predefined class in java that will be use to scan text
//System.in is mean, we will receive input from standard input stream
Scanner readUserInput=new Scanner(System.in);

//Print into command prompt(What is your gender ?)
//Print into command prompt(Female/Male)
System.out.println("What is your gender ?\nFemale/Male");

//Wait and READ A WORD from user input after user hit 'Enter'
//Method next() in class scanner will read only first word in user input
//So, second word that seperate by space will be ignore.
String myGender=readUserInput.next();

//Print what store in myGender
System.out.println(myGender);
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************

Read text user input in java

Complete source code below, will show you how to wait and read text user input in command prompt.

********************************************************************
COMPLETE SOURCE CODE FOR : ReadTextUserInput.java
********************************************************************


import java.util.Scanner;

public class ReadTextUserInput
{
public static void main(String[]args)
{
//Create a scanner object
//Scanner is a predefined class in java that will be use to scan text
//System.in is mean, we will receive input from standard input stream
Scanner readUserInput=new Scanner(System.in);

//Print into command prompt(What is your name ?)
System.out.println("What is your name ?");

//Wait and READ TEXT INPUT from user after user hit 'Enter'
String myName=readUserInput.nextLine();

//Print what store in myName
System.out.println(myName);
}
}


********************************************************************
JUST COMPILE AND EXECUTE IT
********************************************************************

Wait user input in java

Complete source code below will show you, how to wait for user input in command prompt.
Input is a line of text.

**********************************************************************
COMPLETE SOURCE CODE FOR : WaitUserInput.java
**********************************************************************


import java.util.Scanner;

public class WaitUserInput
{
public static void main(String[]args)
{
//Create a scanner object
//Scanner is a predefined class in java that will be use to scan text
//System.in is mean, we will receive input from standard input stream
Scanner readUserInput=new Scanner(System.in);

//Print into command prompt(What is your name ?)
System.out.println("What is your name ?");

//WAIT FOR USER INPUT
//After user put it's name, he or she must press 'Enter'
//After user press 'Enter', all the input contents will read into 'myName'
String myName=readUserInput.nextLine();

//Print what it store in myName
System.out.println(myName);
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

User input in java

Ok, now i share with you how you can handle user input in java.

>>Receive user input from command line


>>Receive user input from input box


>>Receive user input from text field

>>Receive user input from text area

Tip for BoxLayout

BoxLayout enable we arrange components into two direction. Firstly is horizontal and secondly is vertical.

Example source code for set layout using BoxLayout

Set JPanel layout using BoxLayout

Complete source code below will show you how to set JPanel layout using BoxLayout

*******************************************************************
COMPLETE SOURCE CODE FOR : SetJPanelLayoutUsingBoxLayout.java
*******************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJPanelLayoutUsingBoxLayout
{
public static void main(String[]args)
{
//Create a window using JFrame with title ( Set JPanel layout using BoxLayout )
JFrame frame=new JFrame("Set JPanel layout using BoxLayout");

//Create a panel using JPanel
JPanel panel=new JPanel();

//Set JPanel layout using BoxLayout with vertical lay out
//You can try change to BoxLayout.X_AXIS to make components lay out in horizontal
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));

//Create a button with text ( First button )
JButton button=new JButton("First button");

//Create a button with text ( Second button )
JButton button2=new JButton("Second button");

//Create a button with text ( Third button )
JButton button3=new JButton("Third button");

//Create a dimension with :
//Width : 10 pixels
//Height : 10 pixels
Dimension dim=new Dimension(10,10);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//Add button into panel
panel.add(button);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//Add button2 into panel
panel.add(button2);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//Add button3 into panel
panel.add(button3);

//Create an invisible box with dimension size and add into created panel
//You can try eliminate this and see what happen
panel.add(Box.createRigidArea(dim));

//add panel into created JFrame
frame.add(panel);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(500,200);

//Make JFrame locate at center of screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************

Set JPanel layout using GridBagLayout

Source code below will show you, how to set JPanel layout using GridBagLayout.

**************************************************************
COMPLETE SOURCE CODE FOR : SetJPanelLayoutToGridBagLayout.java
**************************************************************


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

public class SetJPanelLayoutToGridBagLayout extends JPanel
{
/**Note**
*When it say, "It will take 4 grid for it's width"
*it mean it will use 4 box in grid and it's direction is to right
*
*When it say, "It will take 4 grid for it's height"
*it mean it will use 4 box in grid and it's direction is to bottom
*/

//Create GridBigLayout object
GridBagLayout gbl=new GridBagLayout();

//Create GridBagConstraints object
GridBagConstraints gbc=new GridBagConstraints();

//Create a label using JLabel with text ( Name : )
JLabel label=new JLabel("Name :");

//Create a label using JLabel with text ( Age : )
JLabel label2=new JLabel("Age :");

//Create a text field using JTextField with numbers of column equal to 12
JTextField textField=new JTextField(12);

//Create a text field using JTextField with numbers of column equal to 3
JTextField textField2=new JTextField(3);

//Create a button with text ( OK )
JButton button=new JButton("OK");

//Create a button with text ( Cancel )
JButton button2=new JButton("Cancel");

//Create a box with vertical layout
Box box1=new Box(BoxLayout.Y_AXIS);

//Create a box with horizontal layout
Box box2=new Box(BoxLayout.X_AXIS);

//Create a box with horizontal layout
Box box3=new Box(BoxLayout.X_AXIS);

//Create a box with vertical layout
Box box4=new Box(BoxLayout.Y_AXIS);

//Create a window using JFrame with title ( Set JPanel layout using GridBagLayout )
JFrame frame=new JFrame("Set JPanel layout using GridBagLayout");

//Constructor
public SetJPanelLayoutToGridBagLayout()
{
//Make text in label allign to right
label.setHorizontalAlignment(SwingConstants.RIGHT);
label2.setHorizontalAlignment(SwingConstants.RIGHT);

//Set panel layout to GridBagLayout
setLayout(gbl);

//Field that will be use when display area is larger than component size.
//It mean when it has some space between component, component will
//enlarge to horizontal direction
gbc.fill=GridBagConstraints.HORIZONTAL;

/*
*Add label into panel with top left corner of the label at crossing between
*first horizontal and first vertical line.
*It will take 4 grid for it's width
*It will take 1 grid for it's height
*/
addComponent(label,1,1,4,1);

/*
*Add label2 into panel with top left corner of the
*label at crossing between
*third horizontal and first vertical line.
*It will take 4 grid for it's width
*It will take 1 grid for it's height
*/
addComponent(label2,3,1,4,1);

/*
*Add textField into panel with top left corner of the text field at
*crossing between first horizontal and sixth vertical line
*It will take 12 grid for it's width
*It will take 1 grid for it's height
*/
addComponent(textField,1,6,12,1);

/*
*Add textField2 into panel with top left corner of the text field at
*crossing between third horizontal and sixth vertical line
*It will take 3 grid for it's width
*It will take 1 grid for it's height
*/
addComponent(textField2,3,6,3,1);

/*
*Add button into panel with top left corner of the button at
*crossing between fifth horizontal and fifth vertical line
*It will take 5 grid for it's width
*It will take 2 grid for it's height
*/
addComponent(button,5,5,5,2);

/*
*Add button2 into panel with top left corner of the button at
*crossing between fifth horizontal and eleventh vertical line
*It will take 5 grid for it's width
*It will take 2 grid for it's height
*/
addComponent(button2,5,11,5,2);

/*
*Add a component that is invisible with 10 pixels width
*and 10 pixels height into box1
*/
box1.add(Box.createRigidArea(new Dimension(10,10)));

/*
*Add box1 into panel with top left corner of the box at
*crossing between first horizontal and fifth vertical line
*It will take 1 grid for it's width
*It will take 3 grid for it's height
*/
addComponent(box1,1,5,1,3);

/*
*Add a component that is invisible with 30 pixels width
*and 10 pixels height into box2
*/
box2.add(Box.createRigidArea(new Dimension(30,10)));

/*
*Add box2 into panel with top left corner of the box at
*crossing between second horizontal and first vertical line
*It will take 17 grid for it's width
*It will take 1 grid for it's height
*/
addComponent(box2,2,1,17,1);

/*
*Add a component that is invisible with 30 pixels width
*and 10 pixels height into box3
*/
box3.add(Box.createRigidArea(new Dimension(30,10)));

/*
*Add box3 into panel with top left corner of the box at
*crossing between fourth horizontal and first vertical line
*It will take 17 grid for it's width
*It will take 1 grid for it's height
*/
addComponent(box3,4,1,17,1);

/*
*Add a component that is invisible with 10 pixels width
*and 10 pixels height into box4
*/
box4.add(Box.createRigidArea(new Dimension(10,10)));

/*
*Add box4 into panel with top left corner of the box at
*crossing between fifth horizontal and tenth vertical line
*It will take 1 grid for it's width
*It will take 2 grid for it's height
*/
addComponent(box4,5,10,1,2);

//Add panel into JFrame
frame.add(this);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//SetJFrame size
frame.setSize(500,400);

//Make JFrame center on the screen
frame.setLocationRelativeTo(null);

//Disble JFrame from resizable
frame.setResizable(false);
frame.setVisible(true);
}

//Method addComponent
public void addComponent(Component component, int row, int column, int width, int height)
{
gbc.gridx=column;
gbc.gridy=row;
gbc.gridwidth=width;
gbc.gridheight=height;
gbl.setConstraints(component,gbc);
add(component);
}

//Main method
public static void main(String[]args)
{
SetJPanelLayoutToGridBagLayout sjpltgbl=new SetJPanelLayoutToGridBagLayout();
}
}


**************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************

Tip for GridBagLayout

GridBagLayout enable you to arrange component in more flexible way. What you need is only a piece of paper. After that, you draw grid and sketch your graphical user interface on the paper like image below.



Click here for it's source code

Tip for GridLayout

GridLayout will arrange components into container from left to right like FlowLayout do. But what make it different to FlowLayout ? The answer is, it will arrange components in grid. See the image below. It represent a grid with 3 rows and 2 columns. First component will be put into first row and first column. Second component will be put into first row and second column. Third component will be put into second row and first column. Fourth component will be put into second row and second column. Fifth component will be put into third row and first column and last component will be put into third row and second column.




Example source code for GridLayout

Tip for BorderLayout

BorderLayout is also a layout manager like FlowLayout. But, it not arrange components in container from left to right like FlowLayout do. It will arrange component in five part.


NORTH
SOUTH
CENTER
EAST
WEST

Example source code for BorderLayout

Tip for FlowLayout

FlowLayout is use to arrange components in a container from left to right. If it reached at the end of the container, but there are still left other component, it will go to the next line in the container and start again arrange component from left to right.

Example of container : JFrame, JPanel, JWindow, JInternalFrame
(Use to hold other component)

Example of component : JPanel, JButton, JTextField, JCheckBox, JRadioButton

Example source code for FlowLayout

Set JTextField background image

Complete source code below will show you, how to set image background in a JTextField. You can download image (textFieldBackgroundImage.jpg) that use in source code at below.

*******************************************************************
COMPLETE SOURCE CODE FOR : SetJTextFieldBackgroundImage.java
*******************************************************************


import javax.swing.*;

import java.awt.*;

public class SetJTextFieldBackgroundImage extends JTextField
{
public SetJTextFieldBackgroundImage()
{
JFrame frame=new JFrame("Set JTextField background image");
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,65);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}

public void paint(Graphics g)
{
setOpaque(false);

//Image that will be set as JTextField background
//I suggest, image that will be use is blur...
//If image is locate at other location, you must put it's full location address.
//For example : C:\\Documents and Settings\\evergreen\\Desktop\\textFieldBackgroundImage.jpg
ImageIcon ii=new ImageIcon("textFieldBackgroundImage.jpg");
Image i=ii.getImage();
g.drawImage(i,0,0,this);
super.paint(g);
}

public static void main(String[]args)
{
SetJTextFieldBackgroundImage sjtfbi=new SetJTextFieldBackgroundImage();
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************



textFieldBackgroundImage.jpg

Set JButton background color on click

Click here

Determine character is whitespace

Complete source code below will show you, how to determine character is whitespace or not in java.

*******************************************************************
COMPLETE SOURCE CODE FOR : DetermineCharacterIsSpace.java
*******************************************************************


public class DetermineCharacterIsSpace
{
public static void main(String[]args)
{
//Create a space character using char by press spacebar once between single quote(' ')
//You can try change it's value by change it to a letter 'A' for example.
char a=' ';

//Determine created character is space or not
//using method isWhitespace from class Character.
//isWhitespace is a static method, so we don't need to create object when
//we want to use it.
if(Character.isWhitespace(a))
{
//Print (It is a whitespace) if character is a whitespace
System.out.println("It is a whitespace");
}
else
{
//Print (It is not a whitespace) if character is not a whitespace
System.out.println("It is not a whitespace");
}
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************

Determine character is uppercase

Complete source code below will show you, how to determine character is uppercase or not in java.

******************************************************************
COMPLETE SOURCE CODE FOR : DetermineCharacterIsUppercase.java
******************************************************************


public class DetermineCharacterIsUppercase
{
public static void main(String[]args)
{
//Create a uppercase character using char with value(B)
//You can try change it's value to letter(b)
char a='B';

//Determine created character is uppercase or not
//using method isUpperCase from class Character.
//isUpperCase is a static method, so we don't need to create object when
//we want to use it.
if(Character.isUpperCase(a))
{
//Print (It is an uppercase) if character is an uppercase
System.out.println("It is an uppercase");
}
else
{
//Print (It is not an uppercase) if character is not an uppercase
System.out.println("It is not an uppercase");
}
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Determine character is lowercase

Complete source code below will show you, how to determine character is lowercase or not in java.

**********************************************************************
COMPLETE SOURCE CODE FOR : DetermineCharacterIsLowercase.java
**********************************************************************


public class DetermineCharacterIsLowercase
{
public static void main(String[]args)
{
//Create a lowercase character using char with value(b)
//You can try change it's value to letter(B)
char a='b';

//Determine created character is lowercase or not
//using method isLowerCase from class Character.
//isLowerCase is a static method, so we don't need to create object when
//we want to use it.
if(Character.isLowerCase(a))
{
//Print (It is a lowercase) if character is a lowercase
System.out.println("It is a lowercase");
}
else
{
//Print (It is not a lowercase) if character is not a lowercase
System.out.println("It is not a lowercase");
}
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

Determine character is letter or digit

Complete source code below will show you, how to determine character is letter or digit in java.

*****************************************************************
COMPLETE SOURCE CODE FOR : DetermineCharacterIsLetterOrDigit.java
*****************************************************************


public class DetermineCharacterIsLetterOrDigit
{
public static void main(String[]args)
{
//Create a character using char with value(3)
//You can try change it's value to letter(k)
char a='3';

//Determine created character is letter or digit
//using method isLetterOrDigit from class Character.
//isLetterOrDigit is a static method, so we don't need to create object when
//we want to use it.
if(Character.isLetterOrDigit(a))
{
//Print (It is a letter or a digit) if character is a letter or digit
System.out.println("It is a letter or a digit");
}
else
{
//Print (It is not a letter or digit) if character is not a letter or digit
System.out.println("It is not a letter or digit");
}
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************

Determine character is letter or not

Complete source code below will show you, how to determine character is letter or not in java.

************************************************************
COMPLETE SOURCE CODE FOR : DetermineCharacterIsLetter.java
************************************************************


public class DetermineCharacterIsLetter
{
public static void main(String[]args)
{
//Create a character using char with value(m)
char a='m';

//Determine created character is letter or not
//using method isLetter from class Character.
//isLetter is a static method, so we don't need to create object when
//we want to use it.
if(Character.isLetter(a))
{
//Print (It is a letter) if character is a letter
System.out.println("It is a letter");
}
else
{
//Print (It is not a letter) if character is not a letter
System.out.println("It is not a letter");
}
}
}


************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************

Determine character is digit or not

Complete source code below will show you, how to determine character is digit or not in java.

*********************************************************************
COMPLETE SOURCE CODE FOR : DetermineCharacterIsDigit.java
*********************************************************************


public class DetermineCharacterIsDigit
{
public static void main(String[]args)
{
//Create a character using char with value(4)
char a='4';

//Determine created character is digit or not
//using method isDigit from class Character.
//isDigit is a static method, so we don't need to create object when
//we want to use it.
if(Character.isDigit(a))
{
//Print (It is a digit) if character is a digit
System.out.println("It is a digit");
}
else
{
//Print (It is not a digit) if character is not a digit
System.out.println("It is not a digit");
}
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************

Set JButton gradient color

Complete source code below will show you, how to change JButton default gradient color.



******************************************************************
COMPLETE SOURCE CODE FOR : SetJButtonGradientColor.java
******************************************************************


import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.UIManager;

import javax.swing.plaf.ColorUIResource;

public class SetJButtonGradientColor
{
public static void main(String[]args)
{
//Create UIManager object
UIManager manager=new UIManager();


//IMPORTANT : Key to know : "Button.gradient"

//Set color base on RGB
//You can get RGB value for your color at "Color picker" at above

//******************************************************
//Create linked list that will store all gradient information
//You can try to understand it by change it's value
LinkedList<Object> a=new LinkedList<Object>();
a.add(0.3);
a.add(0.3);

//First colour : R=2,G=208,B=206
a.add(new ColorUIResource(2,208,206));

//Second colour : R=136,G=255,B=254
a.add(new ColorUIResource(136,255,254));

//Third colour : R=0,G=142,B=140
a.add(new ColorUIResource(0,142,140));
//******************************************************

//Set Button.gradient key with new value
manager.put("Button.gradient",a);

//Create a button using JButton with text ( BUTTON )
JButton button=new JButton("BUTTON");

//Create a window using JFrame with title ( JButton gradient color )
JFrame frame=new JFrame("JButton gradient color");

//Add created button into JFrame
frame.add(button);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(330,80);

//Make JFrame visible. So we can see it.
frame.setVisible(true);
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Set JTextArea background image

Complete source code below will show you, how to set image background in a JTextArea. You can download image (textAreaBackground.jpg) that use in source code at below.

***********************************************************************
COMPLETE SOURCE CODE FOR : AddImageBackgroundInJTextArea.java
***********************************************************************


/**
*AddImageBackgroundInJTextArea will extends JTextArea class.
*So it also inherit all method from JTextArea
*It mean, we can use it directly.For example, setOpaque(false)..
**/
import javax.swing.*;

import java.awt.*;

public class AddImageBackgroundInJTextArea extends JTextArea
{
public AddImageBackgroundInJTextArea()
{
//Create a window using JFrame with title ( Add image background in JTextArea )
JFrame frame=new JFrame("Add image background in JTextArea");

//Add JTextArea into JFrame
frame.add(this);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(500,500);

//Make JFrame center
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}

//Override JTextArea paint method
//It enable us to paint JTextArea background image
public void paint(Graphics g)
{
//Make JTextArea transparent
setOpaque(false);

//Make JTextArea line wrap
setLineWrap(true);

//Make JTextArea word wrap
setWrapStyleWord(true);

//Get image that we use as JTextArea background
ImageIcon ii=new ImageIcon("textAreaBackground.jpg");
Image i=ii.getImage();

//Draw JTextArea background image
g.drawImage(i,0,0,null,this);

//Call super.paint. If we don't do this...We can't see JTextArea
super.paint(g);
}

public static void main(String[]args)
{
AddImageBackgroundInJTextArea aibijta=new AddImageBackgroundInJTextArea();
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************



textAreaBackground.jpg

Set JButton pressed icon

Complete source code below will show you, how to set JButton pressed icon. When someone click the button, icon on that button we will change to pressed icon that we set for the button. You can download icon that we use in this tutorial at below.When you want to compile and execute it, please make sure, icon file locate at same location with this java file.

Note : If you want to create pressed icon, i suggest you make it size and shape same with non-pressed icon.

*****************************************************************
COMPLETE SOURCE CODE FOR : SetJButtonPressedIcon.java
*****************************************************************


import javax.swing.*;

public class SetJButtonPressedIcon
{
public static void main(String[]args)
{
//Create image icon from "notpressedicon.png"
//You can download it at below
//If your icon locate at other location,
//please put it's full address location.For example :
//C:\\Documents and Settings\\evergreen\\Desktop\\notpressedicon.png
ImageIcon notPressIcon=new ImageIcon("notpressedicon.png");

//Create image icon from "pressedicon.png"
//You can download it at below
//If your icon locate at other location,
//please put it's full address location.For example :
//C:\\Documents and Settings\\evergreen\\Desktop\\pressedicon.png
ImageIcon pressIcon=new ImageIcon("pressedicon.png");

//Create a button with text ( GO ) and not press icon ( notpressedicon.png )
JButton button=new JButton("GO",notPressIcon);

//Set presses icon for JButton
button.setPressedIcon(pressIcon);

//Set horizontal text position to center
button.setHorizontalTextPosition(SwingConstants.CENTER);

//Set vertical text position to bottom.
//So, text will locate under icon
button.setVerticalTextPosition(SwingConstants.BOTTOM);

//Create a window using JFrame with title ( Set JButton pressed icon )
JFrame frame=new JFrame("Set JButton pressed icon");

//Add created button into JFrame
frame.add(button);

//Set JFrame's default close operation
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(350,150);

//Make JFrame center on screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************


pressedicon.png




notpressedicon.png

Set JButton icon

Complete source code below will show you, how to set icon on JButton.

************************************************************************
COMPLETE SOURCE CODE FOR : SetJButtonIcon.java
************************************************************************


import javax.swing.*;

public class SetJButtonIcon
{
public static void main(String[]args)
{
//Create an image icon from png file named ( callme.png )
//You can download this image below
//This file is locate at same location with this java file.
//If your file locate at other location,
//you must put it's full location address. For example :
//C:\\Documents and Settings\\evergreen\\Desktop\\callme.png
ImageIcon iconForButton=new ImageIcon("callme.png");

//Create a button from JButton with text ( Call me ) and image icon ( callme.png )
JButton button=new JButton("Call me",iconForButton);

//set button horizontal text position to center
//You can select one of the following SwingConstants:
//SwingConstants.CENTER
//SwingConstants.RIGHT
//SwingConstants.LEFT
//SwingConstants.LEADING
//SwingConstants.TRAILING (the default)
button.setHorizontalTextPosition(SwingConstants.CENTER);

//set vertical text position to bottom
//It make our text button locate under button icon
//You can select one of the following SwingConstants:
//SwingConstants.CENTER (the default)
//SwingConstants.TOP
//SwingConstants.BOTTOM
button.setVerticalTextPosition(SwingConstants.BOTTOM);

//Create a window from JFrame with title ( Set JButton icon )
JFrame frame=new JFrame("Set JButton icon");

//Add created button into JFrame
frame.add(button);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(300,150);

//Make JFrame locate at center on screen
frame.setLocationRelativeTo(null);

//Makr JFrame visible
frame.setVisible(true);
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************



callme.png

Open a text file into JTextArea

Complete source code below will show you, how to open a text file with file extension (.txt) into JTextArea.

**************************************************************
COMPLETE SOURCE CODE FOR : OpenTextFileIntoJTextArea.java
**************************************************************


import javax.swing.*;

import java.util.*;

import java.io.*;

public class OpenTextFileIntoJTextArea
{
public static void main(String[]args)
{
try
{
//Read a text file named MyTextFile.txt
//You can download this text file at the link below
//You also can change to other text file by change it's name
//Don't forget to put .txt
//If your text file locate at other location,
//you must put it full location.
//For example :
//C:\\Documents and Settings\\evergreen\\MyTextFile.txt
FileReader readTextFile=new FileReader("MyTextFile.txt");

//Create a scanner object from FileReader
Scanner fileReaderScan=new Scanner(readTextFile);

//Create a String that will store all text in the text file
String storeAllString="";

//Put all text from text file into created String
while(fileReaderScan.hasNextLine())
{
String temp=fileReaderScan.nextLine()+"\n";

storeAllString=storeAllString+temp;
}

//Set JTextArea text to created String
JTextArea textArea=new JTextArea(storeAllString);

//Set JTextArea to line wrap
textArea.setLineWrap(true);

//Set JTextArea text to word wrap
textArea.setWrapStyleWord(true);

//Create scrollbar for text area
JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

//Create a window using JFrame with title ( Open text file into JTextArea )
JFrame frame=new JFrame("Open text file into JTextArea");

//Add scrollbar into JFrame
frame.add(scrollBarForTextArea);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(500,500);

//Make JFrame locate at center on screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
catch(Exception exception)
{
//Print Error in file processing if it can't process your text file
System.out.println("Error in file processing");
}
}
}


**************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************

CLICK HERE TO DOWNLOAD MyTextFile.txt

Set file type in JFileChooser

Complete source code below will show you, how set file type that should be display in a JFileChooser. Source code below will display all directories and text files only.

***************************************************************************
COMPLETE SOURCE CODE FOR : SetJFileChooserFileType.java
***************************************************************************


import javax.swing.filechooser.FileFilter;

import javax.swing.JFileChooser;

import java.io.File;

public class SetJFileChooserFileType
{
public SetJFileChooserFileType()
{
//Create a file chooser from JFileChooser
JFileChooser fileChooser=new JFileChooser();

//Set file type that should be display by set JFileChooser's file filter
fileChooser.setFileFilter(new TypeOfFile());

//Show JFileChooser
int a=fileChooser.showDialog(null,"Open Text File");
}

//Class TypeOfFile
class TypeOfFile extends FileFilter
{
//Type of file that should be display in JFileChooser will be set here
//We choose to display only directory and text file
public boolean accept(File f)
{
return f.isDirectory()||f.getName().toLowerCase().endsWith(".txt");
}

//Set description for the type of file that should be display
public String getDescription()
{
return ".text files";
}
}

public static void main(String[]args)
{
SetJFileChooserFileType sjfcft=new SetJFileChooserFileType();
}
}


***************************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************************

Set password length for JPasswordField

Complete source code below will show you, how you can set password length in JPasswordField. In source code below, we will enable user to enter only password that contains five characters.After that it will disable password field. User can delete entered password by press 'Backspace' key.

**********************************************************************
COMPLETE SOURCE CODE FOR : SetPasswordLength.java
**********************************************************************


import javax.swing.*;

import javax.swing.event.*;

import java.awt.event.*;

import java.awt.FlowLayout;

public class SetPasswordLength implements CaretListener
{
//Create password field
JPasswordField passwordField=new JPasswordField(12);

JLabel label=new JLabel("Press Backspace to delete password");

JFrame frame;

//Create key listener that will listen when someone press Backspace key
KeyListener kl=new KeyAdapter()
{
public void keyPressed(KeyEvent event)
{
if(event.getKeyCode()==KeyEvent.VK_BACK_SPACE)
{
passwordField.setEditable(true);

label.show(false);

frame.repaint();

frame.validate();
}
}
};

public SetPasswordLength()
{
label.show(false);

passwordField.addCaretListener(this);

passwordField.addKeyListener(kl);

frame=new JFrame("Set password length");

frame.setLayout(new FlowLayout());

frame.add(passwordField);

frame.add(label);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(500,100);

frame.setVisible(true);
}

//Listen for changes in the caret position
public void caretUpdate(CaretEvent event)
{
int passwordLength=passwordField.getText().length();

//If password length equal to five characters, password field will uneditable
//You can change to any password length that you want by change 5 to any other value
if(passwordLength==5)
{
passwordField.setEditable(false);

label.show(true);

frame.repaint();

frame.validate();
}
}

public static void main(String[]args)
{
SetPasswordLength spl=new SetPasswordLength();
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

Add scroll bar to JTextArea

Complete source code below will show you, how to add scroll bar to JTextArea.You can use scroll pane constants like below to set your text area scroll bar.

**************
HORIZONTAL
**************
HORIZONTAL_SCROLLBAR_ALWAYS
HORIZONTAL_SCROLLBAR_AS_NEEDED
HORIZONTAL_SCROLLBAR_NEVER

**************
VERTICAL
**************
VERTICAL_SCROLLBAR_ALWAYS
VERTICAL_SCROLLBAR_AS_NEEDED
VERTICAL_SCROLLBAR_NEVER

****************************************************************************
COMPLETE SOURCE CODE FOR : AddScrollBarToJTextArea.java
****************************************************************************


import javax.swing.*;

public class AddScrollBarToJTextArea
{
public static void main(String[]args)
{
//Create JTextArea
JTextArea textArea=new JTextArea("Put your text here");

//Create JScrollPane that will be use as JTextArea scrollbar from JTextArea object
JScrollPane scrollBar=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

//Create a window using JFrame
JFrame frame=new JFrame("Add scrollbar to JTextArea");

//add created JScrollPane into JFrame
frame.add(scrollBar);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(500,200);

//Make JFrame get to center
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
}


****************************************************************************
JUST COMPILE AND EXECUTE
****************************************************************************

Set word wrap in JTextArea

Complete source code below will show you, how to set word wrap in JTextArea.

***************************************************************************
COMPLETE SOURCE CODE FOR : SetWordWrapInJTextArea.java
***************************************************************************


import javax.swing.*;

public class SetWordWrapInJTextArea
{
public static void main(String[]args)
{
JTextArea textArea=new JTextArea();

//Set word wrap in JTextArea
textArea.setWrapStyleWord(true);

//Set line wrap in JTextArea
textArea.setLineWrap(true);

JFrame frame=new JFrame("Set word wrap in JTextArea");

frame.add(textArea);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setSize(500,500);

frame.setLocationRelativeTo(null);

frame.setVisible(true);
}
}


***************************************************************************
JUST COMPILE AND EXECUTE IT
***************************************************************************

Set JTextArea background color to JFrame default color

Complete source code below will show you, how to set JTextArea background color same to JFrame default color.

**********************************************************************
COMPLETE SOURCE CODE FOR : SetJTextAreaBackgroundColorToJFrameColor.java
**********************************************************************


import javax.swing.*;

import java.awt.Color;

public class SetJTextAreaBackgroundColorToJFrameColor
{
public static void main(String[]args)
{
//Create a window using JFrame with title ( Set JTextArea background color to JFrame color )
JFrame frame=new JFrame("Set JTextArea background color to JFrame color");

//Get JFrame background color
Color jframeColor=frame.getBackground();

//Create a text area with initial text ( Put your text here )
JTextArea textArea=new JTextArea("Put your text here");

//Set text area background color same to JFrame background color
textArea.setBackground(jframeColor);

//Add created text area into JFrame
frame.add(textArea);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(600,500);

//Make JFrame locate at center on screen
frame.setLocationRelativeTo(null);

//Make JFrame visible
frame.setVisible(true);
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

Easiest way to make JFrame center

Complete source code below will show you, the easiest way to make JFrame get to the center of screen by only one line of code. We will use method setLocationRelativeTo(null) to make our JFrame get to the center. Remember, when you want to use this code, you must put it after you set JFrame size.

*****************************************************************
COMPLETE SOURCE CODE FOR : EasiestWayToMakeJFrameCenter.java
*****************************************************************


import javax.swing.JFrame;

public class EasiestWayToMakeJFrameCenter
{
public static void main(String[]args)
{
JFrame frame=new JFrame("Easiest way to make JFrame center");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,400);

//setLocationRelativeTo(null) will make JFrame get to the center
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************

Get default JFrame background color

Complete source code below will show you, how to get default JFrame background color and after that, it will print RED,GREEN,BLUE(RGB) value for the color.

****************************************************************
COMPLETE SOURCE CODE FOR : GetDefaultJFrameBackgroundColor.java
****************************************************************


import javax.swing.JFrame;

import java.awt.Color;

public class GetDefaultJFrameBackgroundColor
{
public static void main(String[]args)
{
//Create a window using JFrame
JFrame frame=new JFrame();

//Get JFrame background color using method getBackground()
Color frameBackgroundColor=frame.getBackground();

//Get RED value from color
int redValue=frameBackgroundColor.getRed();

//Get GREEN value from color
int greenValue=frameBackgroundColor.getGreen();

//Get BLUE value from color
int blueValue=frameBackgroundColor.getBlue();

//Print RGB value that we get
System.out.println("R : "+redValue);
System.out.println("G : "+greenValue);
System.out.println("B : "+blueValue);

//You can check what color that match the RGB value that we get using 'Color picker' at above
}
}


****************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************

Get default JPanel background color

Complete source code below will show you, how to get default JPanel background color and after that, it will print RED,GREEN,BLUE(RGB) value for the color.

******************************************************************
COMPLETE SOURCE CODE FOR : GetDefaultJPanelBackgroundColor.java
******************************************************************


import javax.swing.JPanel;

import java.awt.Color;

public class GetDefaultJPanelBackgroundColor
{
public static void main(String[]args)
{
//Create a panel using JPanel
JPanel panel=new JPanel();

//Get panel background color using method getBackground()
Color panelBackgroundColor=panel.getBackground();

//Get RED value from color
int redValue=panelBackgroundColor.getRed();

//Get GREEN value from color
int greenValue=panelBackgroundColor.getGreen();

//Get BLUE value from color
int blueValue=panelBackgroundColor.getBlue();

//Print RGB value that we get
System.out.println("R : "+redValue);
System.out.println("G : "+greenValue);
System.out.println("B : "+blueValue);

//You can check what color that match the RGB value that we get using 'Color picker' at above
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Get default JLabel background color

Complete source code below will show you, how to get default JLabel background color and after that, it will print RED,GREEN,BLUE(RGB) value for the color.

*****************************************************************
COMPLETE SOURCE CODE FOR : GetDefaultJLabelBackgroundColor.java
*****************************************************************


import javax.swing.JLabel;

import java.awt.Color;

public class GetDefaultJLabelBackgroundColor
{
public static void main(String[]args)
{
//Create a label using JLabel
JLabel label=new JLabel();

//Get label background color using method getBackground()
Color labelBackgroundColor=label.getBackground();

//Get RED value from color
int redValue=labelBackgroundColor.getRed();

//Get GREEN value from color
int greenValue=labelBackgroundColor.getGreen();

//Get BLUE value from color
int blueValue=labelBackgroundColor.getBlue();

//Print RGB value that we get
System.out.println("R : "+redValue);
System.out.println("G : "+greenValue);
System.out.println("B : "+blueValue);

//You can check what color that match the RGB value that we get using 'Color picker' at above
}
}


*****************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************

Put JLabel into list

Complete source code below will show you, how to put JLabel into list. During my try using java i found no way to put JLabel into JList. So i try to create it on my own. I hope you enjoy what i share with you.

************************************************************************
COMPLETE SOURCE CODE FOR : AddJLabelIntoList.java
************************************************************************


import javax.swing.*;

import java.awt.GridLayout;

public class AddJLabelIntoList
{
public static void main(String[]args)
{
//Create label using JLabel that will be put into list
JLabel label1=new JLabel("Duck");
JLabel label2=new JLabel("Sheep");
JLabel label3=new JLabel("Cow");
JLabel label4=new JLabel("Buffalo");
JLabel label5=new JLabel("Horse");
JLabel label6=new JLabel("Goat");

//Create panel that will be use to put all label into it
JPanel panel=new JPanel(new GridLayout(6,1));

//Add all created label into panel
panel.add(label1);
panel.add(label2);
panel.add(label3);
panel.add(label4);
panel.add(label5);
panel.add(label6);

//Create scroll bar for created panel
//Vertical scrollbar always show
//Horizontal scrollbar never show
JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

//Create window using JFrame with title ( Add JLabel into list )
JFrame frame=new JFrame("Add JLabel into list");

//Add created scroll bar into JFrame
frame.add(scrollBar);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(400,100);

//Make JFrame visible
frame.setVisible(true);
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************

Get current cursor location in JTextArea

Complete source code below will show you, how to get current cursor location in JTextArea.

***********************************************************************
COMPLETE SOURCE CODE FOR : GetCurrentCursorLocationInJTextArea.java
***********************************************************************


import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class GetCurrentCursorLocationInJTextArea extends JTextArea implements MouseMotionListener
{
//Create window using JFrame with title ( Get current cursor location in JTextArea )
JFrame frame=new JFrame("Get current cursor location in JTextArea");

//Create text field that will show you, current cursor location
JTextField textFieldX=new JTextField(5);
JTextField textFieldY=new JTextField(5);

//Create label that will use to describe function for each text field
JLabel labelX=new JLabel("Coordinate X : ");
JLabel labelY=new JLabel("Coordinate Y : ");

//Create panel that will use to store text field and label
JPanel panelX=new JPanel();
JPanel panelY=new JPanel();

//Panel that will use to store panelX and panelY
JPanel container=new JPanel();

public GetCurrentCursorLocationInJTextArea()
{
//Add mouse motion listener to JTextArea
addMouseMotionListener(this);

//Set container layout using BorderLayout
container.setLayout(new BorderLayout());

//Set panelX and panelY layout using GridLayout
panelX.setLayout(new GridLayout(1,2));
panelY.setLayout(new GridLayout(1,2));

//Add labelX and textFieldX into panelX
panelX.add(labelX);
panelX.add(textFieldX);

//Add labelY and textFieldY into panelY
panelY.add(labelY);
panelY.add(textFieldY);

//Add panelX and panelY into container
container.add(panelX,BorderLayout.WEST);
container.add(panelY,BorderLayout.EAST);

//Set frame layout using BorderLayout
frame.setLayout(new BorderLayout());

//Add JTextArea into JFrame
frame.add(this,BorderLayout.CENTER);

//Add container into JFrame
frame.add(container,BorderLayout.SOUTH);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}

public void mouseMoved(MouseEvent event)
{
//Get current X-coordinate for cursor
textFieldX.setText("");
textFieldX.setText(Integer.toString(event.getX()));

//Get current Y-coordinate for cursor
textFieldY.setText("");
textFieldY.setText(Integer.toString(event.getY()));
}

public void mouseDragged(MouseEvent event)
{
//Do nothing because our case not handle dragging
}

public static void main(String[]args)
{
GetCurrentCursorLocationInJTextArea gcclijta=new GetCurrentCursorLocationInJTextArea();
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************

Put JRadioButton into list

Complete source code below will show you, how to put JRadioButton into list. During my try using java i found no way to put JRadioButton into JList. So i try to create it on my own. I hope you enjoy what i share with you.

******************************************************************
COMPLETE SOURCE CODE FOR : AddRadioButtonIntoList.java
******************************************************************


import javax.swing.*;

import java.awt.GridLayout;

import java.awt.Color;

public class AddRadioButtonIntoList
{
public static void main(String[]args)
{
//Create radio button using JRadioButton that will be put into list
JRadioButton radioButton1=new JRadioButton("Duck");
JRadioButton radioButton2=new JRadioButton("Sheep");
JRadioButton radioButton3=new JRadioButton("Cow");
JRadioButton radioButton4=new JRadioButton("Buffalo");
JRadioButton radioButton5=new JRadioButton("Horse");
JRadioButton radioButton6=new JRadioButton("Goat");

//Set all radio button background color to white
radioButton1.setBackground(Color.WHITE);
radioButton2.setBackground(Color.WHITE);
radioButton3.setBackground(Color.WHITE);
radioButton4.setBackground(Color.WHITE);
radioButton5.setBackground(Color.WHITE);
radioButton6.setBackground(Color.WHITE);

//Create button group for JRadioButton
ButtonGroup bg=new ButtonGroup();

//Add all created radio button into button group
bg.add(radioButton1);
bg.add(radioButton2);
bg.add(radioButton3);
bg.add(radioButton4);
bg.add(radioButton5);
bg.add(radioButton6);

//Create panel that will be use to put all radio button into it
JPanel panel=new JPanel(new GridLayout(6,1));

//Add all created radio button into panel
panel.add(radioButton1);
panel.add(radioButton2);
panel.add(radioButton3);
panel.add(radioButton4);
panel.add(radioButton5);
panel.add(radioButton6);

//Create scroll bar for created panel
//Vertical scrollbar always show
//Horizontal scrollbar never show
JScrollPane scrollBar=new JScrollPane(panel,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

//Create window using JFrame with title ( Add JRadioButton into list )
JFrame frame=new JFrame("Add JRadioButton into list");

//Add created scroll bar into JFrame
frame.add(scrollBar);

//Set default close operation for JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Set JFrame size
frame.setSize(400,100);

//Make JFrame visible
frame.setVisible(true);
}
}


******************************************************************
JUST COMPILE AND EXECUTE IT
******************************************************************

Get index of character from String

Complete source code below will show you, how to get index of a character from a String.

************************************************************************
COMPLETE SOURCE CODE FOR : GetIndexOfCharacterFromString.java
************************************************************************


public class GetIndexOfCharacterFromString
{
public static void main(String[]args)
{
//Create a String
String a="ABCD";

//Create an int variable that will store index for character C
int index=a.indexOf('C');

//Print index that we get
System.out.println("Index for C is : "+index);
}
}


************************************************************************
JUST COMPILE AND EXECUTE IT
************************************************************************

Get substring from String

Complete source code below will show you, how to get substring from a String.

**********************************************************************
COMPLETE SOURCE CODE FOR : GetSubstringFromString.java
**********************************************************************


public class GetSubstringFromString
{
public static void main(String[]args)
{
//This source code will show you how to get substring from a String
//We will get String "love" from String "I love you"
String a="I love you";

//We will use substring() method
//2=index in "I love you" for 'l'
//6=(index in "I love you" for 'e')+1
String b=a.substring(2,6);

//Print substring that we get
System.out.println(b);
}
}


**********************************************************************
JUST COMPILE AND EXECUTE IT
**********************************************************************

Determine String end with specified word

Complete source code below will show you, how to determine whether a String end with specified word or not.

**************************************************************************
COMPLETE SOURCE CODE FOR : DetermineStringEndWithWord.java
**************************************************************************


public class DetermineStringEndWithWord
{
public static void main(String[]args)
{
//First String
//You can try change it
String a="Hello";

//Second String
//You can try change it
String b="llo";

//Determine if first String end with second String or not
//If yes, program will print YES, otherwise it will print NO
if(a.endsWith(b))
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}


**************************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************************

Determine String start with specified word

Complete source code below will show you, how to determine whether a String start with specified word or not.

***********************************************************************
COMPLETE SOURCE CODE FOR : DetermineStringStartWithWord.java
***********************************************************************


public class DetermineStringStartWithWord
{
public static void main(String[]args)
{
//First String
//You can try change it
String a="Hello";

//Second String
//You can try change it
String b="Hel";

//Determine if first String start with second String or not
//If yes, program will print YES, otherwise it will print NO
if(a.startsWith(b))
{
System.out.println("YES");
}
else
{
System.out.println("NO");
}
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************

All class in java.lang package

All class below is from java.lang package. If you want to use one of the class in the list, you don't need to import it into your program like other class, for example class JFrame from javax.swing package that need import statement in your program ( import javax.swing.JFrame ). This is because it will import implicitly into your program by compiler.

*******************************
Interfaces
*******************************
Appendable
CharSequence
Cloneable
Comparable
Iterable
Readable
Runnable
Thread.UncaughtExceptionHandler


*******************************
Classes
*******************************
Boolean
Byte
Character
Character.Subset
Character.UnicodeBlock
Class
ClassLoader
Compiler
Double
Enum
Float
InheritableThreadLocal
Integer
Long
Math
Number
Object
Package
Process
ProcessBuilder
Runtime
RuntimePermission
SecurityManager
Short
StackTraceElement
StrictMath
String
StringBuffer
StringBuilder
System
Thread
ThreadGroup
ThreadLocal
Throwable
Void


*******************************
Enums
*******************************
Thread.State

*******************************
Exceptions
*******************************
ArithmeticException
ArrayIndexOutOfBoundsException
ArrayStoreException
ClassCastException
ClassNotFoundException
CloneNotSupportedException
EnumConstantNotPresentException
Exception
IllegalAccessException
IllegalArgumentException
IllegalMonitorStateException
IllegalStateException
IllegalThreadStateException
IndexOutOfBoundsException
InstantiationException
InterruptedException
NegativeArraySizeException
NoSuchFieldException
NoSuchMethodException
NullPointerException
NumberFormatException
RuntimeException
SecurityException
StringIndexOutOfBoundsException
TypeNotPresentException
UnsupportedOperationException


*******************************
Errors
*******************************
AbstractMethodError
AssertionError
ClassCircularityError
ClassFormatError
Error
ExceptionInInitializerError
IllegalAccessError
IncompatibleClassChangeError
InstantiationError
InternalError
LinkageError
NoClassDefFoundError
NoSuchFieldError
NoSuchMethodError
OutOfMemoryError
StackOverflowError
ThreadDeath
UnknownError
UnsatisfiedLinkError
UnsupportedClassVersionError
VerifyError
VirtualMachineError


*******************************
Annotation Types
*******************************
Deprecated
Override
SuppressWarnings

Why we don't import String

This is because String is from java.lang ( java.lang.String ) package. All class from java.lang package will import implicitly into your program by java compiler.

Click here to see other class in java.lang package

Combine String

Complete source code below will show you, how to combine two String using + symbol and concat() method from String class.

**************************************************************************
COMPLETE SOURCE CODE FOR : CombineString.java
**************************************************************************


public class CombineString
{
public static void main(String[]args)
{
String a="Hello ";
String b="world";

//First Technique : Using + symbol
String c=a+b;

//Second Technique : Using concat() method from String class
String d=a.concat(b);

//Now we will print result. It should be same.
System.out.println(c);
System.out.println(d);
}
}


**************************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************************

Determine character location in a String

Now, i will share with you, how to determine location of a character in a String. Ok...firstly you must know location of a character in a String is determine using 'index'. Index for first character in a String is equal to 0 and each character include white space after that will add 1.

Note : Character location = index

String a="Hello dude";

Below is a list all character in String above with it's index.

H - 0
e - 1
l - 2
l - 3
o - 4
white space - 5
d - 6
u - 7
d - 8
e - 9

Draw grid on JFrame

Complete source code below will show you, how to draw grid on a JFrame.

****************************************************************************
COMPLETE SOURCE CODE FOR : DrawGridOnJFrame.java
****************************************************************************


import javax.swing.JFrame;

import java.awt.Graphics;

public class DrawGridOnJFrame extends JFrame
{
//Constructor
public DrawGridOnJFrame()
{
//Set JFrame title to ( Draw grid on JFrame )
setTitle("Draw grid on JFrame");

//Set JFrame size to :
//Width : 400 pixels
//Height : 400 pixels
setSize(400,400);

//Set JFrame default close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Make JFrame visible
setVisible(true);
}


/**
*To draw grid line on JFrame we will override it's paint method.
*We will draw grid with size 10 pixels width and 10 pixels height for each grid box
**/
public void paint(Graphics g)
{
//Override paint method in superclass
super.paint(g);

//Get current JFrame width
int frameWidth=getSize().width;

//Get current JFrame height
int frameHeight=getSize().height;

int temp=0;

//Draw vertical grid line with spacing between each line equal to 10 pixels
while(temp<frameWidth)
{
temp=temp+10;
g.drawLine(temp,0,temp,frameHeight);
}

temp=0;

//Draw horizontal grid line with spacing between each line equal to 10 pixels
while(temp<frameHeight)
{
temp=temp+10;
g.drawLine(0,temp,frameWidth,temp);
}
}

//Main method
public static void main(String[]args)
{
DrawGridOnJFrame dgojf=new DrawGridOnJFrame();
}
}


****************************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************************

Convert String to lowercase

Complete source code below will show you, how to convert a String to lowercase.

**************************************************************************
COMPLETE SOURCE CODE FOR : ConvertStringToLowercase.java
**************************************************************************


public class ConvertStringToLowercase
{
public static void main(String[]args)
{
//Create a String
String a="WELCOME TO JAVA2EVERYONE!";

//Convert created String to lowercase
a=a.toLowerCase();

//Print the String
System.out.println(a);
}
}


**************************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************************

Convert String to uppercase

Complete source code below will show you, how to convert a String to uppercase.

****************************************************************************
COMPLETE SOURCE CODE FOR : ConvertStringToUppercase.java
****************************************************************************


public class ConvertStringToUppercase
{
public static void main(String[]args)
{
//Create a String
String a="Hi everybody!";

//Convert created String to uppercase
a=a.toUpperCase();

//Print the String
System.out.println(a);
}
}


****************************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************************

Create mutable String

In java when you create a String, it's mean you create an immutable String. You cannot change it, after you create it. Complete source code below will show you, how to create a mutable String using StringBuffer class.

***********************************************************************
COMPLETE SOURCE CODE FOR : CreateMutableString.java
***********************************************************************


public class CreateMutableString
{
public static void main(String[]args)
{
//Create a mutable String
StringBuffer a=new StringBuffer("Hi everyone");

//Print the created String
System.out.println(a);
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************

String tip from API

Strings are constant, their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared.

Get character from String

Complete source code below will show you, how to get character from a String in java.

*****************************************************************************
COMPLETE SOURCE CODE FOR : GetCharacterFromString.java
*****************************************************************************


public class GetCharacterFromString
{
public static void main(String[]args)
{
//Create a String that will be use to get character from it
String a="Hello!";

/**
*If you want to get character in a String,
*you can use charAt method from String class.
*Just put index of the character in it's argument.
*For your information index in String is start with
*0....so
*index 0 is for H
*index 1 is for e
*index 2 is for l
*index 3 is for l
*index 4 is for o
*index 5 is for !
**/

//Get first character in the String
char characterFirst=a.charAt(0);

//Print the first character that we get
System.out.println(characterFirst);
}
}


*****************************************************************************
JUST COMPILE AND EXECUTE IT
*****************************************************************************

Get char array from String

Complete source code below will show you, how to get char array from a String. This char array we will store all characters in the String include white space.

**************************************************************************
COMPLETE SOURCE CODE FOR : GetCharArrayFromString.java
**************************************************************************


public class GetCharArrayFromString
{
public static void main(String[]args)
{
//Create a String that we want to get character from it
//You can try other String that you want
String a="Get char array from String.........";

//Create an array from type char that will store all characters from String
//Method toCharArray() will get all characters in the String
char[]storeAllStringCharacter=a.toCharArray();

//Print number of characters in char array
System.out.println("Number of characters in char array is : "+storeAllStringCharacter.length+"\n\n");

//Print all character in char array include their index in String
System.out.println("*******************************");
System.out.println("THE CHARACTER IS : ");
System.out.println("*******************************");
System.out.println();

for(int i=0; i<storeAllStringCharacter.length; i++)
{
System.out.println("Character at index "+i+" in the String is : "+storeAllStringCharacter[i]);
}
}
}


**************************************************************************
JUST COMPILE AND EXECUTE IT
**************************************************************************

Get String from char array

Complete source code below will show you, how to get String from char array.

***********************************************************************
COMPLETE SOURCE CODE FOR : GetStringFromCharArray.java
***********************************************************************


public class GetStringFromCharArray
{
public static void main(String[]args)
{
//Create an array from char type that will store all character for a String
char[]allCharacter=new char[12];

//Set all value in created array
allCharacter[0]='H';
allCharacter[1]='e';
allCharacter[2]='l';
allCharacter[3]='l';
allCharacter[4]='o';
allCharacter[5]=' ';
allCharacter[6]='W';
allCharacter[7]='o';
allCharacter[8]='r';
allCharacter[9]='l';
allCharacter[10]='d';
allCharacter[11]='!';

//Get String from created char array
String resultString=new String(allCharacter);

//Print result
System.out.println(resultString);
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************

Omit all white space in String

Complete source code below will show you, how to omit all white space in a String.

*******************************************************************
COMPLETE SOURCE CODE FOR : OmitWhitespaceInString.java
*******************************************************************


public class OmitWhitespaceInString
{
public static void main(String[]args)
{
//Create a String with whitespace
String a=" Eliminate white space in t h i s s t r i ng ";

//Get String length that base on numbers of character include whitespace
int temp=a.length();

//Create an int variable
int numbersOfLetter=0;

//Create loop to count the numbers of Letter
for(int i=0; i<temp; i++)
{
if(Character.isLetter(a.charAt(i)))
{
numbersOfLetter++;
}
}

//Create an array base on numbers of letter that we get
char[]storeAllCharacter=new char[numbersOfLetter];

//Create an int variable
int temp3=0;

//Create loop to set each value in array
for(int i=0; i<temp; i++)
{
if(Character.isLetter(a.charAt(i)))
{
storeAllCharacter[temp3]=a.charAt(i);
temp3++;
}
}

//Get String from created char array
String resultStringAfterOmit=new String(storeAllCharacter);

//Print result
System.out.println(resultStringAfterOmit);
}
}


*******************************************************************
JUST COMPILE AND EXECUTE IT
*******************************************************************

Get numbers of character in a string

Complete source code below will show you, how to get numbers of character that contain in a String. If you compile and execute source code below, you will get numbers of character is equal to 15 not 14. This is because the whitespace in a String also count.

***********************************************************************
COMPLETE SOURCE CODE FOR : GetNumbersOfCharacterInAString.java
***********************************************************************


public class GetNumbersOfCharacterInAString
{
public static void main(String[]args)
{
//Create a String
//You can change to other String that you want
String a="Hello everybody";

//Get numbers of character in created String and store it in int variable
int numbersOfCharacter=a.length();

//Print result
System.out.println("Numbers of character is : "+numbersOfCharacter);
}
}


***********************************************************************
JUST COMPILE AND EXECUTE IT
***********************************************************************

Compare String ignore capital or ordinary letters

Complete source code below will show you, how to compare two string with same characteristic but ignore about capital or ordinary letters. The characteristic that i mean here is, number of characters and sequence of characters. We will use method equalsIgnoreCase().

****************************************************************************
COMPLETE SOURCE CODE FOR : CompareStringIgnoreCapitalOrOrdinaryLetters.java
****************************************************************************


public class CompareStringIgnoreCapitalOrOrdinaryLetters
{
public static void main(String[]args)
{
//Create first String = aaAAA
//You can try other string that you want by change aaAAA
String firstString="aaAAA";

//Create second String = AAaaa
//You can try other string that you want by change AAaaa
String secondString="AAaaa";

//Check if first String is same or not to second String
if(firstString.equalsIgnoreCase(secondString))
{
//If first String equal to second String, it will print ( firstString is same to secondString )
System.out.println("firstString is same to secondString");
}
else
{
//If first String not equal to second String, it will print ( firstString is not same to secondString )
System.out.println("firstString is not same to secondString");
}
}
}


****************************************************************************
JUST COMPILE AND EXECUTE IT
****************************************************************************

RELAXING NATURE VIDEO