Java simple timer

Complete source code below will show you, how to create simple timer using java. Actually it has a problem. The problem that i mean is, it seem more slow than real timer.If you find how to solve it, i hope you can share with me by put a comment.

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


import javax.swing.*;

import java.awt.event.*;

import java.awt.*;

public class JavaSimpleTimer extends JPanel implements ActionListener
{
int miliseconds=0;
int seconds=0;
int minutes=0;

Timer myTimer;

Font timerFont=new Font("Verdana",Font.BOLD,24);

public JavaSimpleTimer()
{
myTimer=new Timer(10,this);

JFrame myFrame=new JFrame("Simple Timer");

myFrame.add(this);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(500,500);
myFrame.setVisible(true);

myTimer.setInitialDelay(0);
myTimer.start();
}

public void paint(Graphics g)
{
super.paint(g);
String mili=Integer.toString(miliseconds);
String sec=Integer.toString(seconds);
String min=Integer.toString(minutes);

if(mili.length()==1)
{
mili="0"+mili;
}
if(sec.length()==1)
{
sec="0"+sec;
}
if(min.length()==1)
{
min="0"+min;
}

g.setFont(timerFont);

g.drawString(min+" :",20,20);
g.drawString(sec+" :",80,20);
g.drawString(mili,140,20);
}

public void actionPerformed(ActionEvent event)
{
miliseconds=miliseconds+1;
if(miliseconds==100)
{
miliseconds=0;
seconds=seconds+1;
}
if(seconds==60)
{
seconds=0;
minutes=minutes+1;
}
repaint();
}

public static void main(String[]args)
{
JavaSimpleTimer myTest=new JavaSimpleTimer();
}
}


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

Set JSlider tick color

Complete source code below will show you, how to set JSlider tick color. I have tried to find method in JSlider class to set JSlider tick color...but, i can't find it. So i tried to create UI Delegate only for SliderUI that change JSlider tick color. You can try to compile both source code below. Make sure both java file below locate at the same location. JSlider's tick color is set in MyNewMetalSliderUI.java.You can try to change it's color follow what color that you want base on RGB value. After you compile SetJSliderTickColor.java and MyNewMetalSliderUI.java, you try execute SetJSliderTickColor.java. This is because, main method contain in this file.Oooo...before i forget, it's only handle horizontal slider. If you want to make it can use for vertical slider, you can try overwrite method paintMajorTickForVertSlider(Graphics g, Rectangle tickBounds, int y) and paintMinorTickForVertSlider(Graphics g, Rectangle tickBounds, int y) in MetalSliderUI class. You can review it in Java SE API for MetalSliderUI class.

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


import javax.swing.*;

import java.awt.*;

import javax.swing.plaf.ColorUIResource;

import javax.swing.plaf.metal.MetalSliderUI;

import javax.swing.plaf.ComponentUI;

public class MyNewMetalSliderUI extends MetalSliderUI
{
// Create our own slider UI
public static ComponentUI createUI(JComponent c )
{
return new MyNewMetalSliderUI();
}

//*******************HORIZONTAL MAJOR TICK*******************
public void paintMajorTickForHorizSlider(Graphics g, Rectangle tickBounds, int x)
{
int coordinateX=x;

if(slider.getOrientation()==JSlider.HORIZONTAL)
{
//Create color using RGB value(RED=255,GREEN=0,BLUE=0)
//You can use Color picker above to get RGB value for color that you want
Color majorTickColor=new Color(255,0,0);

//Set color that will use to draw MAJOR TICK using created color
g.setColor(majorTickColor);

//Draw MAJOR TICK
g.drawLine(coordinateX,0,coordinateX,tickBounds.height);
}
}
//*******************HORIZONTAL MAJOR TICK*******************

//*******************HORIZONTAL MINOR TICK*******************
public void paintMinorTickForHorizSlider(Graphics g, Rectangle tickBounds, int x)
{
int coordinateX=x;

if(slider.getOrientation()==JSlider.HORIZONTAL)
{
//Create color using RGB value(RED=12,GREEN=255,BLUE=0)
//You can use Color picker above to get RGB value for color that you want
Color majorTickColor=new Color(12,255,0);

//Set color that will use to draw MINOR TICK using created color
g.setColor(majorTickColor);

//Draw MINOR TICK
g.drawLine(coordinateX,0,coordinateX,tickBounds.height/2);
}
}
//*******************HORIZONTAL MINOR TICK*******************
}


**********************************************************************
JUST COMPILE
**********************************************************************

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

import javax.swing.*;

import java.awt.*;

public class SetJSliderTickColor
{
public SetJSliderTickColor()
{
//Create slider using JSlider
JSlider mySlider=new JSlider();

//Set major tick spacing to 10
mySlider.setMajorTickSpacing(10);

//Set minor tick spacing to 1
mySlider.setMinorTickSpacing(1);

//Make slider's numbers visible
mySlider.setPaintLabels(true);

//Make slider's ticks visible
mySlider.setPaintTicks(true);

//Create a window using JFrame with title ( Set JSlider tick color )
JFrame frame=new JFrame("Set JSlider tick color");

//Set JFrame layout to FlowLayout
frame.setLayout(new FlowLayout());

//Add created JSlider into JFrame
frame.add(mySlider);

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

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

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

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

public static void main(String[]args)
{
/***********Set our own UI Delegate for Slider*************/
UIManager uim=new UIManager();

//MyNewMetalSliderUI contain settings that use to change tick color
uim.put("SliderUI","MyNewMetalSliderUI");
/***********Set our own UI Delegate for Slider*************/

SetJSliderTickColor sjstc=new SetJSliderTickColor();
}
}


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

Set JOptionPane warning icon

Complete source code below will show you, how to set warning icon in JOptionPane.

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


import javax.swing.*;

public class SetJOptionPaneWarningIcon
{
public static void main(String[]args)
{
//null-Message Box appear in no parent component
//Warning Icon-text in message box
//WARNING-JOptionPane title
//JOptionPane.WARNING_MESSAGE-Set warning icon that will be show in message box
JOptionPane.showMessageDialog(null,"Warning Icon","WARNING",JOptionPane.WARNING_MESSAGE);
}
}


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

Set JOptionPane error icon

Complete source code below will show you, how to set error icon in JOptionPane.

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


import javax.swing.*;

public class SetJOptionPaneErrorIcon
{
public static void main(String[]args)
{
//null-Message Box appear in no parent component
//Error Icon-text in message box
//ERROR-JOptionPane title
//JOptionPane.ERROR_MESSAGE-Set error icon that will be show in message box
JOptionPane.showMessageDialog(null,"Error Icon","ERROR",JOptionPane.ERROR_MESSAGE);
}
}


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

Set JOptionPane information icon

Complete source code below will show you, how to set information icon in JOptionPane.

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


import javax.swing.*;

public class SetJOptionPaneInformationIcon
{
public static void main(String[]args)
{
//null-Message Box appear in no parent component
//Information Icon-text in message box
//INFORMATION-JOptionPane title
//JOptionPane.INFORMATION_MESSAGE-Set information icon that will be show in message box
JOptionPane.showMessageDialog(null,"Information Icon","INFORMATION",JOptionPane.INFORMATION_MESSAGE);
}
}


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

Set JOptionPane question icon

Complete source code below will show you, how to set question icon in JOptionPane.

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


import javax.swing.*;

public class SetJOptionPaneQuestionIcon
{
public static void main(String[]args)
{
//null-Message Box appear in no parent component
//Question Icon-text in message box
//QUESTION-JOptionPane title
//JOptionPane.QUESTION_MESSAGE-Set question icon that will be show in message box
JOptionPane.showMessageDialog(null,"Question Icon","QUESTION",JOptionPane.QUESTION_MESSAGE);
}
}


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

Create simple digital clock in java

Complete source code below, will show you, how to create simple digital clock in java.

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


import javax.swing.*;

import java.awt.*;

import java.util.Date;

public class SimpleDigitalClock extends JPanel
{
JFrame frame;

int currentHour;
int currentMinute;
int currentSecond;

//Font that will be use to show digital clock
Font myFont=new Font("Tahoma",Font.BOLD+Font.ITALIC,20);

//Color that will be use to show digital clock
Color myColor=new Color(255,0,0);

//Font metrics that will use to store font informations
//For example, width of a character
FontMetrics fm;

public SimpleDigitalClock()
{
//Create a window using JFrame with title ( Simple Digital Clock )
frame=new JFrame("Simple Digital Clock");

//add(this) mean add created panel into JFrame
//Which panel ?
//See line 81 and 7 (I hope you understand it)
frame.add(this);

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

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

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

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

/*
*Loop that will make sure panel show current time
*like current second, current minute and current hour.
*/
while(true)
{
//It will do all code in method paint(See line 67)
repaint();

try
{
Thread.sleep(900);
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}

public void paint(Graphics g)
{
super.paint(g);

/*
*Create current Date object. It means it store information
*about current hour, minute and second.
*/
Date myDate=new Date();

currentHour=myDate.getHours();
currentMinute=myDate.getMinutes();
currentSecond=myDate.getSeconds();

//Set font that will use to draw digital number
g.setFont(myFont);

//Information about distance between number in digital clock
fm=g.getFontMetrics();
int hourXCoordinate=20;
int minuteXCoordinate=hourXCoordinate+(fm.getMaxAdvance()*2);
int secondXCoordinate=hourXCoordinate+(fm.getMaxAdvance()*4);

//Set color that will use to draw digital number
g.setColor(myColor);

//Draw hour, draw (:) between number, draw minute and draw second.
g.drawString(Integer.toString(currentHour),hourXCoordinate,20);
g.drawString(":",(hourXCoordinate+minuteXCoordinate)/2,20);
g.drawString(Integer.toString(currentMinute),minuteXCoordinate,20);
g.drawString(":",(secondXCoordinate+minuteXCoordinate)/2,20);
g.drawString(Integer.toString(currentSecond),secondXCoordinate,20);
}

public static void main(String[]args)
{
SimpleDigitalClock sdc=new SimpleDigitalClock();
}
}


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

Get current second

Complete source code below, will show you how to get current computer second and print the value. The second value that it get is second value at program executing time.

>>Get current minute
>>Get current hour
>>Get current computer time in java

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


import java.util.Date;

public class GetCurrentSecond
{
public static void main(String[]args)
{
Date myDate=new Date();

//Get current second
int currentSecond=myDate.getSeconds();

//Print current second that we get
System.out.println("Current second is : "+currentSecond);
}
}


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

Get current minute

Complete source code below will print current computer minute.

>>Get current second
>>Get current hour
>>Get current computer time in java

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


import java.util.Date;

public class GetCurrentMinute
{
public static void main(String[]args)
{
Date myDate=new Date();

//Get current minute
int currentMinute=myDate.getMinutes();

//Print current minute that we get
System.out.println("Current minute is : "+currentMinute);
}
}


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

Get current hour

Complete source code below will print current computer hour in soldier time format.Soldier time format is 24 hour format.

>>Get current minute
>>Get current second
>>Get current computer time in java

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


import java.util.Date;

public class GetCurrentHour
{
public static void main(String[]args)
{
Date myDate=new Date();

//Get current hour in soldier time format
int currentHour=myDate.getHours();

//Print current hour that we get
System.out.println("Current hour is : "+currentHour);
}
}


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

Get current computer time in java

Complete source code below will show you, how to get current computer time in java.

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


import java.util.Date;

public class GetCurrentTime
{
public static void main(String[]args)
{
Date myDate=new Date();

System.out.println(myDate.getHours()+":"+myDate.getMinutes()+":"+myDate.getSeconds());
}
}


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

Set ToolTipText background color

Complete source code below, will show you how to set ToolTipText background color.

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


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

import java.awt.FlowLayout;
import java.awt.Color;

public class SetToolTipTextBackgroundColor
{
/**
*Create a button with text ( Put your cursor on me )
*/
JButton button=new JButton("Put your cursor on me");

//Create a window using JFrame with text ( Set ToolTipText background color )
JFrame frame=new JFrame("Set ToolTipText background color");

public SetToolTipTextBackgroundColor()
{
//Create a color base on RGB value
//You can get your color value base on RGB using Color picker at above
//R=204 G=0 B=153
Color backgroundColor=new Color(204,0,153);

//Create UIManager
UIManager uim=new UIManager();

//Set tooltiptext background color using created Color
uim.put("ToolTip.background",backgroundColor);

//Set tooltiptext for created button
button.setToolTipText("I am a button");

frame.setLayout(new FlowLayout());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[]args)
{
SetToolTipTextBackgroundColor stttbc=new SetToolTipTextBackgroundColor();
}
}


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

Set ToolTipText text font

Complete source code below, will show you how to set ToolTipText text font.

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


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

import java.awt.FlowLayout;
import java.awt.Font;

public class SetToolTipTextFont
{
/**
*Create a button with text ( Put your cursor on me )
*/
JButton button=new JButton("Put your cursor on me");

//Create a window using JFrame with text ( Set ToolTipText text font )
JFrame frame=new JFrame("Set ToolTipText text font");

public SetToolTipTextFont()
{
//Create a font :
//Name : Verdana
//Style : Bold
//Size : 20
Font textFont=new Font("Verdana",Font.BOLD,20);

//Create UIManager
UIManager uim=new UIManager();

//Set tooltiptext text font using created Font
uim.put("ToolTip.font",textFont);

//Set tooltiptext for created button
button.setToolTipText("I am a button");

frame.setLayout(new FlowLayout());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[]args)
{
SetToolTipTextFont stttf=new SetToolTipTextFont();
}
}


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

Set ToolTipText text color

Complete source code below, will show you how to set ToolTipText text color.

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


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

import java.awt.FlowLayout;
import java.awt.Color;

public class SetToolTipTextColor
{
/**
*Create a button with text ( Put your cursor on me )
*/
JButton button=new JButton("Put your cursor on me");

//Create a window using JFrame with title ( Set ToolTipText text color )
JFrame frame=new JFrame("Set ToolTipText text color");

public SetToolTipTextColor()
{
//Create a color base on RGB value
//You can get your color value base on RGB using Color picker at above
//R=255 G=255 B=255 is RGB value for white
Color textColor=new Color(255,255,255);

//Create UIManager
UIManager uim=new UIManager();

//Set tooltiptext text color using created Color
uim.put("ToolTip.foreground",textColor);

//Set tooltiptext for created button
//So, it's tooltiptext text color will be WHITE
button.setToolTipText("I am a button");

frame.setLayout(new FlowLayout());
frame.add(button);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[]args)
{
SetToolTipTextColor stttc=new SetToolTipTextColor();
}
}


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

Set JOptionPane icons



Complete source code below will show you, how to set JOptionPane icons using any GIF image. Before you compile and execute complete source code below, you need to download all images below and place them with your java file that contain source code below.You also can use any GIF image that you want, but make sure it's location is right. This is because i suggest you place all GIF image at same location with source code file. So you don't need to put any file path in your source code. If you still want to use GIF image at other location, you can try step by step below.

For example, your GIF image with name MyImage.gif locate at C:\Documents and Settings...like below :

C:\Documents and Settings\MyImage.gif

So, you must put in your source code like this :
"C:\\Documents and Settings\\MyImage.gif"


WARNING.gif



QUESTION.gif



INFORMATION.gif



ERROR.gif


Click here for how to create all icons above

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


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

import java.awt.GridLayout;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class ChangeJOptionPaneIcons implements ActionListener
{

JButton button=new JButton("JOptionPane with Error Icon");
JButton button2=new JButton("JOptionPane with Information Icon");
JButton button3=new JButton("JOptionPane with Question Icon");
JButton button4=new JButton("JOptionPane with Warning Icon");

JFrame frame=new JFrame("Change JOptionPane icons");

public ChangeJOptionPaneIcons()
{
//---START SETTING NEW ICON---
UIManager uim=new UIManager();

Object error=LookAndFeel.makeIcon(getClass(),"ERROR.gif");
Object information=LookAndFeel.makeIcon(getClass(),"INFORMATION.gif");
Object question=LookAndFeel.makeIcon(getClass(),"QUESTION.gif");
Object warning=LookAndFeel.makeIcon(getClass(),"WARNING.gif");

//Set new icon for Error message
uim.put("OptionPane.errorIcon",error);

//Set new icon for Information message
uim.put("OptionPane.informationIcon",information);

//Set new icon for Question message
uim.put("OptionPane.questionIcon",question);

//Set new icon for Warning message
uim.put("OptionPane.warningIcon",warning);
//---END SETTING NEW ICON---

button.addActionListener(this);
button2.addActionListener(this);
button3.addActionListener(this);
button4.addActionListener(this);

frame.setLayout(new GridLayout(4,1));
frame.add(button);
frame.add(button2);
frame.add(button3);
frame.add(button4);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
JOptionPane.showMessageDialog(frame,"Error Icon","ERROR",JOptionPane.ERROR_MESSAGE);
}
else if(event.getSource()==button2)
{
JOptionPane.showMessageDialog(frame,"Information Icon","INFORMATION",JOptionPane.INFORMATION_MESSAGE);
}
else if(event.getSource()==button3)
{
JOptionPane.showMessageDialog(frame,"Question Icon","QUESTION",JOptionPane.QUESTION_MESSAGE);
}
else if(event.getSource()==button4)
{
JOptionPane.showMessageDialog(frame,"Warning Icon","WARNING",JOptionPane.WARNING_MESSAGE);
}
}

public static void main(String[]args)
{
ChangeJOptionPaneIcons cjopi=new ChangeJOptionPaneIcons();
}
}
//END


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

Get date using Calendar class

Complete source code below will show you, how to get date on local computer in java using Calendar class.



import java.util.Calendar;
import java.util.Locale;

public class GetDate
{
public static void main(String[]args)
{
//Get a calendar using the default time zone and locale.
Calendar currentComputerDate=Calendar.getInstance();

//Print date
System.out.print(currentComputerDate.get(Calendar.DATE));
System.out.print(".");

/*Print month in text representation. For example January is first month.
*Month that will print is in long representation.
*Short representation for January is Jan
*You can try to change Calendar.LONG to Calendar.SHORT
*Local.ROOT is useful constant for the root locale.
*/
System.out.print(currentComputerDate.getDisplayName(Calendar.MONTH,Calendar.LONG,Locale.ROOT));
System.out.print(".");

//Print year
System.out.print(currentComputerDate.get(Calendar.YEAR));
}
}

Get selected JRadioButton from ButtonGroup

Complete source code below will show you, how to get selected JRadioButton from ButtonGroup.

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


import javax.swing.JRadioButton;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.AbstractButton;

import java.awt.BorderLayout;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import java.util.Enumeration;

public class GetSelectedJRadioButtonFromButtonGroup implements ActionListener
{
//Create two radio button that will be put into a group
//Set start radio button selection to female
JRadioButton firstRadioButton=new JRadioButton("Female",true);
JRadioButton secondRadioButton=new JRadioButton("Male");

//Create a button with text ( What i select )
JButton button=new JButton("What i select");

//Create a window using JFrame with title ( Get selected JRadioButton from ButtonGroup)
JFrame frame=new JFrame("Get selected JRadioButton from ButtonGroup");

//Create a radio button group using ButtonGroup
ButtonGroup bg=new ButtonGroup();

public GetSelectedJRadioButtonFromButtonGroup()
{
//Add all radio button into created group
bg.add(firstRadioButton);
bg.add(secondRadioButton);

//Set JFrame layout to border layout
frame.setLayout(new BorderLayout());

//Create a panel that will be put radio button into it
JPanel panel=new JPanel();

//Add all created radio button into panel
panel.add(firstRadioButton);
panel.add(secondRadioButton);

//Add action listener to created button
button.addActionListener(this);

//Add panel and button into JFrame
frame.add(panel,BorderLayout.CENTER);
frame.add(button,BorderLayout.SOUTH);

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

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

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

//Action for button
//Get selected JRadioButton from ButtonGroup
public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
Enumeration<AbstractButton> allRadioButton=bg.getElements();

while(allRadioButton.hasMoreElements())
{
JRadioButton temp=(JRadioButton)allRadioButton.nextElement();
if(temp.isSelected())
{
JOptionPane.showMessageDialog(frame,"You select : "+temp.getText());
}
}
}
}

public static void main(String[]args)
{
GetSelectedJRadioButtonFromButtonGroup gsjrbfbg=new GetSelectedJRadioButtonFromButtonGroup();
}
}



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

Two text field in JOptionPane

Complete source code below will show you, how to put two text field into JOptionPane. First text field is to receive username from user and second is to receive password from user. This gui is suitable when you want to receive username and password from user using JOptionPane.

username : jamesBond
password : 007


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


import javax.swing.*;

import java.awt.*;

public class TwoTextFieldInJOptionPane
{
public static void main(String[]args)
{
//Create a panel that will be use to put
//one JTextField, one JPasswordField and two JLabel
JPanel panel=new JPanel();

//Set JPanel layout using GridLayout
panel.setLayout(new GridLayout(4,1));

//Create a label with text (Username)
JLabel username=new JLabel("Username");

//Create a label with text (Password)
JLabel password=new JLabel("Password");

//Create text field that will use to enter username
JTextField textField=new JTextField(12);

//Create password field that will be use to enter password
JPasswordField passwordField=new JPasswordField(12);

//Add label with text (username) into created panel
panel.add(username);

//Add text field into created panel
panel.add(textField);

//Add label with text (password) into created panel
panel.add(password);

//Add password field into created panel
panel.add(passwordField);

//Create a window using JFrame with title ( Two text component in JOptionPane )
JFrame frame=new JFrame("Two text component in JOptionPane");

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

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

//Set JFrame locate at center
frame.setLocationRelativeTo(null);

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

//Show JOptionPane that will ask user for username and password
int a=JOptionPane.showConfirmDialog(frame,panel,"Put username and password",JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);

//Operation that will do when user click 'OK'
if(a==JOptionPane.OK_OPTION)
{
if(textField.getText().equals("jamesBond")&&new String(passwordField.getPassword()).equals("007"))
{
JOptionPane.showMessageDialog(frame,"You are James Bond","Correct",JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(frame,"You are not James Bond","False",JOptionPane.ERROR_MESSAGE);
}
}

//Operation that will do when user click 'Cancel'
else if(a==JOptionPane.CANCEL_OPTION)
{
JOptionPane.showMessageDialog(frame,"You pressed Cancel button");
}
}
}


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

Open file using JFileChooser

Complete source code below will show you, how to open file using JFileChooser.

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


/*
*Desktop class only can get when you use JDK 6
*/
import java.awt.Desktop;

import javax.swing.JFileChooser;

import java.io.File;

public class OpenFileUsingJFileChooser
{
public static void main(String[]args)
{
//Create a file chooser
JFileChooser fileChooser=new JFileChooser();

//File chooser will appear in no windows parent
int a=fileChooser.showOpenDialog(null);

//Action that will take when user click open button
if(a==JFileChooser.APPROVE_OPTION)
{
//Get file that want to open
File fileToOpen=fileChooser.getSelectedFile();

try
{
//Open file using suitable program on computer.
//You don't need to tell what program to use.
//Java will select default program that your
//computer use to open the file.
//In windowsXP you can see what
//program that your computer use to open
//a file by right click on file,
//choose properties and see at
//Opens with : ProgramNameToOpenTheFile
Desktop.getDesktop().open(fileToOpen);
}
catch(Exception exception)
{
System.out.println("Problem occour when to open the file");
}
}
}
}


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

Open any file or folder using Desktop class

Complete source code below will show you, how to open C:\ drive using Desktop class. Desktop class is only can get when you use jdk 6.

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


/*
*If you want to use Desktop class,
*you must make sure that jdk version
*that you use is 6. This facilities
*is exist in jdk 6.
*/
import java.awt.Desktop;

import java.io.File;

public class OpenFileUsingDesktopClass
{
public static void main(String[]args)
{
try
{
//Open C:\ drive
//Make sure that you change \ to \\
//You can change to other file or folder that you want
//Example for file that you want to open:
//C:\Sunset.jpg
//So, change C:\\ below to
//C:\\Sunset.jpg
Desktop.getDesktop().open(new File("C:\\"));
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


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


Click here to download jdk6
Click here to download jdk6 documentation

Set JButton text color using UIManager

Complete source code below will show you, how to set JButton text color using UIManager. When you set JButton text color using this style, it will make all JButton in your program will have same text color. So, if you want to set only one text color for JButton, i suggest you click here.

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


import javax.swing.UIManager;

import javax.swing.plaf.ColorUIResource;

import javax.swing.*;

import java.awt.*;

public class SetJButtonForegroundColorUseUiManager
{
public static void main(String[]args)
{
/*
*Create color base on RGB color model
*that will use as JButton foreground color.
*Red=255
*Green=0
*Blue=0
*/
Color foregroundColor=new Color(255,0,0);

//Set JButton foreground color
UIManager.put("Button.foreground",new ColorUIResource(foregroundColor));

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

//Create two button
JButton button1=new JButton("Button 1");
JButton button2=new JButton("Button 2");

//Set JFrame layout to FlowLayout
frame.setLayout(new FlowLayout());

//Add created button into frame
frame.add(button1);
frame.add(button2);

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

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

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

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


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

Open any file or folder in java

Complete source code will show you, how to open any files or folders using java in windows.What you must know is :


rundll32 SHELL32.DLL,ShellExec_RunDLL File_Or_Folder_To_Open


What is rundll32.exe And Why Is It Running?


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


public class OpenFileUsingJava
{
public static void main(String[]args)
{
try
{
//Path for folder or file that you want to open
//In my case i will open C:\ drive
//So create a String like below
//Don't forget to change \ to \\
String a="C:\\";

//Execute command
//Command that you must know : rundll32 SHELL32.DLL,ShellExec_RunDLL File_Or_Folder_To_Open
Runtime.getRuntime().exec("rundll32 SHELL32.DLL,ShellExec_RunDLL \""+a+"\"");
}
catch(Exception exception)
{
exception.printStackTrace();
}
}
}


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

What is different between i++ and ++i

I want to share with you about different between i++ and ++i.

++i
**********
int i=0;
System.out.println(++i);
**********
It will print on screen 1


i++
**********
int i=0;
System.out.println(i++);
**********
It will print on screen 0

Answer :
++i will add current i value with 1 before print


i++ will add current i value with 1 after print

Draw triangle in JPanel

Complete source code below will show you, how to draw triangle in JPanel

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


import javax.swing.*;

import java.awt.*;

public class DrawTriangle extends JPanel
{
public DrawTriangle()
{
JFrame frame=new JFrame("Draw triangle in JPanel");
frame.add(this);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public void paint(Graphics g)
{
super.paint(g);

//All triangle corner x coordinate
int[]x={0,150,300};

//All triangle corner y coordinate
int[]y={200,0,200};

//Set color base on RGB
//You can get RGB value for your color at "Color picker" at above
//R=255
//G=192
//B=0
//So after this all you draw will use this color
g.setColor(new Color(255,192,0));

//Draw triangle in JPanel
g.fillPolygon(x,y,3);

//Set color base on RGB
//You can get RGB value for your color at "Color picker" at above
//R=1
//G=1
//B=1
//So after this all you draw will use this color
g.setColor(new Color(1,1,1));

//Set font that will use when draw String
g.setFont(new Font("Arial",Font.BOLD,14));

//Draw String in JPanel
g.drawString("(0,200)",10,200);
g.drawString("(150,0)",150,20);
g.drawString("(300,200)",290,200);
}

public static void main(String[]args)
{
DrawTriangle dt=new DrawTriangle();
}

}


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

Compare current date with user input date in java

Complete source code below will show you, how to compare current date with user input date in java.

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


import java.util.Date;

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class GetDate implements ActionListener
{
int year=0;
int month=0;
int date=0;

String [] yearContent={"2000","2001","2002","2003","2004","2005","2006","2007","2008","2009","2010","2011"};
String [] monthContent={"January","February","March","April","Mei","Jun","July","August","September","October","November","December"};
String [] dateContent={"1","2","3","4","5","6","7","8","9","10",
"11","12","13","14","15","16","17","18","19","20",
"21","22","23","24","25","26","27","28","29","30",
"31"};

JComboBox yearComboBox=new JComboBox(yearContent);
JComboBox monthComboBox=new JComboBox(monthContent);
JComboBox dateComboBox=new JComboBox(dateContent);

JButton button=new JButton("Click here to compare to current date");

JFrame frame=new JFrame("Compare date with current date");

public GetDate()
{
button.addActionListener(this);

Box box=Box.createHorizontalBox();
box.add(dateComboBox);
box.add(monthComboBox);
box.add(yearComboBox);

frame.setLayout(new GridLayout(2,1));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(box);
frame.add(button);
frame.setSize(500,100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource()==button)
{
String tempDate=(String)dateComboBox.getSelectedItem();
date=Integer.parseInt(tempDate);

month=monthComboBox.getSelectedIndex();

String tempYear=(String)yearComboBox.getSelectedItem();
year=Integer.parseInt(tempYear)-1900;

Date currentDateValue=new Date();
Date userChooserDate=new Date(year,month,date);

int currentYear=currentDateValue.getYear();
int currentMonth=currentDateValue.getMonth();
int currentDate=currentDateValue.getDate();

if((date==currentDate)&&(month==currentMonth)&&(year==currentYear))
{
JOptionPane.showMessageDialog(frame,"Same date","SAME",JOptionPane.INFORMATION_MESSAGE);
}
else if(userChooserDate.compareTo(currentDateValue)<0)>0)
{
JOptionPane.showMessageDialog(frame,"Welcome to the future","FUTURE",JOptionPane.INFORMATION_MESSAGE);
}
}
}

public static void main(String[]args)
{
GetDate gd=new GetDate();
}
}


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

RELAXING NATURE VIDEO