Category Archives: Java

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

Creating a JButton component in swing

Java swing provides a native look and feel that emulates the look and feel of several platforms.
Here i am going to create a Button and adding it to Frame.

For this first create a Jframe object,a JPanel object and a Container object

JFrame f = new JFrame();
JPanel panel1 = new JPanel();
Container con = f.getContentPane();

Then Create a button object and add this ti JPanel object

JButton panel1_but = new JButton();
panel1.add(panel1_but);

and finally add JPanel to JFrame

panel1.add(panel1_but);

This full code is given below

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class mainframe implements WindowListener
{
	JFrame f = new JFrame();
	Container con = f.getContentPane();
	JPanel panel1 = new JPanel();
	mainframe()
	{
		createpanel1();
		f.addWindowListener(this);
		f.setSize(900, 600);
		f.setVisible(true);
		f.setLocationRelativeTo(null);
		f.setResizable(false);    ///cannot maximize
	   	f.setVisible(true);
	}
	public static void main(String args[])
	{
		new mainframe();
	}
	private void createpanel1()
	{
		JButton panel1_but = new JButton();
		panel1_but.setBounds(new Rectangle(450,400,200,40));
		panel1_but.setText("Continue");

		panel1.add(panel1_but);
		panel1_but.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(ActionEvent e)
			{
				//action to be performed....
			}
			}
		);
		panel1.setLayout(new BorderLayout());
		panel1.setBackground(Color.white);
		panel1.setVisible(true);
		con.add(panel1);
	}

	@Override
	public void windowActivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosed(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowClosing(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeactivated(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowDeiconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowIconified(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
	@Override
	public void windowOpened(WindowEvent arg0) {
		// TODO Auto-generated method stub
	}
}

Java Applet MouseEvents

A simple event based applet applications is described below
First importing the necessary header files
// Demonstrate the mouse event handlers.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=”MouseEvents” width=300 height=100>
</applet>
*/
Next step is to create a class which implements the “MouseListener” and “MouseMotionListener ”
public class MouseEvents extends Applet implements MouseListener,
MouseMotionListener {
String msg = “”;
int mouseX = 0, mouseY = 0; // coordinates of mouse
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse clicked.”;
repaint();
}
Handle mouse entered.
public void mouseEntered(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse entered.”;
repaint();
}
Handle mouse exited.
public void mouseExited(MouseEvent me) {
// save coordinates
mouseX = 0;
mouseY = 10;
msg = “Mouse exited.”;
repaint();
}
Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Down”;
repaint();
}
Handle button released.
public void mouseReleased(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “Up”;
repaint();
}
Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
// save coordinates
mouseX = me.getX();
mouseY = me.getY();
msg = “*”;
showStatus(“Dragging mouse at ” + mouseX + “, ” + mouseY);
repaint();
}
Handle mouse moved.
public void mouseMoved(MouseEvent me) {
// show status
showStatus(“Moving mouse at ” + me.getX() + “, ” + me.getY());
}
Display msg in applet window at current X,Y location. This “paint” method is called when JVM execute “repaint()” function . The “paint” method will refresh the screen
public void paint(Graphics g) {
g.drawString(msg, mouseX, mouseY);
}
}

JComboBox in Java swing

This shows you how to add JcomboBox to JPanel

import java.awt.*;
import java.awt.event.*;
import java.text.DecimalFormat;

import javax.imageio.ImageIO;
import javax.swing.*;

public class Example implements WindowListener
{
  JFrame content_frame = new JFrame();
  JPanel panel = new JPanel();
  JComboBox Combonote;
  public Example()
  {
  	    content_frame.setTitle("Contents");
		content_frame.addWindowListener(this);
		content_frame.setSize(300, 300);
		content_frame.setVisible(true);
		content_frame.setLocationRelativeTo(null);
		content_frame.setResizable(false);    ///cannot maximize
		content_frame.setVisible(true);

		showComboBox();
  }
  private void showComboBox()
  {
	  String test[]= {"[select Exercise...]","Exercise1","Exercise2","Exercise3","Exercise4","Exercise5"};
	  panel.setBackground(Color.lightGray);
	  panel.setVisible(true);
	  Combonote = new JComboBox(test);
	  Combonote.setBounds(250, 240, 250, 30);
	  panel.add(Combonote);

	  panel.setBounds(250, 240, 250, 30);
	  content_frame.getContentPane().add(panel);
	  Combonote .addItemListener(new ItemListener()
	  {
	  	  public void itemStateChanged(ItemEvent ie)
	      {
	      	  if(ie.getStateChange() == ie.SELECTED)
	      	  {
	      		    if(Combonote.getSelectedItem().equals("Exercise1"))
	  		  		{
	                                          //code...
	                }
	          }
	      }
	  });
  }

  public static void main(String[] args)
  {
    new Example();
  }

@Override
public void windowActivated(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowClosed(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowClosing(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowDeactivated(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowDeiconified(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowIconified(WindowEvent arg0) {
	// TODO Auto-generated method stub

}

@Override
public void windowOpened(WindowEvent arg0) {
	// TODO Auto-generated method stub

}
}


Java check memory Allocation

class test
{
	public static void main(String args[])
	{
			Runtime r = Runtime.getRuntime();
			long mem1, mem2;
			Integer someints[] = new Integer[1000];
			System.out.println("Total memory is: " +r.totalMemory());
			mem1 = r.freeMemory();
			System.out.println("Initial free memory: " + mem1);
			r.gc();
			mem1 = r.freeMemory();
			System.out.println("Free memory after garbage collection: "+ mem1);

			for(int i=0; i<1000; i++)
				someints[i] = new Integer(i); // allocate integers
			mem2 = r.freeMemory();

			System.out.println("Free memory after allocation: "	+ mem2);
			System.out.println("Memory used by allocation: "+ (mem1-mem2));

			// 	discard Integers
			for(int i=0; i<1000; i++) someints[i] = null;
				r.gc(); // request garbage collection

			mem2 = r.freeMemory();
			System.out.println("Free memory after collecting" +" discarded Integers: " + mem2);
	}
}

When run the code the output will be similar to this

Total memory is: 5177344
Initial free memory: 4986744
Free memory after garbage collection: 5063784
Free memory after allocation: 5045296
Memory used by allocation: 18488
Free memory after collecting discarded Integers: 5063784

How to Convert a string to date in JAVA ?

Hi,

For converting string to a date in JAVA use the following code.

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {

  public static void main(String[] args) throws Exception {

    SimpleDateFormat myDateFormat = new SimpleDateFormat("dd/MM/yyyy");

    Date dateToday = dateFormat.parse("25/06/2011");

    System.out.println(myDateFormat.format(dateToday));

  }
}

:)

How to find if a string starts with a particular word – JAVA ?

Hi,

In order to find whether a given string starts with a particular string or not in JAVA, use the following code.


public class Main {

  public static void main(String[] args) {

    String urStr = "Coderz Heaven";

    if (urStr.startsWith("Coderz")) {

      System.out.println("Yes! Your string starts with Coderz");

    }

    else {

      System.out.println("No!");

    }

  }

}

Exception Handling – Divide by Zero – Java Example

Hi,

Given below is a code snippet which will demonstrate an exception handling in Java with Divide by zero error.

public class MainClass {
  public static void main(String args[]) {

    int urAns, urDiv;

    try {

      urDiv = 0;
      urAns = 25 / urDiv;

      System.out.println("Do you really think this will print out? No! It won't!");

    }

    catch (ArithmeticException e) {

      System.out.println("Division by zero not Possible!");

    }

    System.out.println("This will print out after Exception Handling");
  }

}

:)

Simple String Concatenation Example in JAVA

Hi,

Given below is a simple concatenation example in JAVA where two strings are joined together to form a single string.

public class MainClass {

  public static void main(String[] arg) {

    String yourString = "Coderz" + "Heaven";

    System.out.println(yourString);

  }

}

And…the output will be.. “CoderzHeaven”
:)

How to search for substring from a string in JAVA ?

Hi,

For searching for a particular substring from a starting index of a string and get the starting index of it in JAVA, use the following sample of code.


public class MainClass{

  public static void main(String[] arg){

    String myStr = "coderzco";

    int begIndex= 2;

    int myIndex= 0;

    myIndex = str.indexOf("co", begIndex);

    System.out.println(myIndex);
  }

}

It will print out the starting index of the substring ‘co’ (the second ‘co’), that is 6.

:)

How to search for characters from strings in JAVA ?

Hi,

For searching for a particular character from a string and getting the index of that particular character, use the following code.


public class MainClass{

  public static void main(String[] arg){

    String myStr = "Coderz";

    int strIndex = 0;
    strIndex = myStr.indexOf('o');

    System.out.println(strIndex);
  }

}

It will print out the index of ‘o’, that’s 1.
:)

Applet FlowLayout Example

The FlowLayout class puts components in a row, sized at their preferred size.

Creates a new flow layout manager with the indicated alignment and the indicated horizontal and vertical gaps. The hgap and vgap arguments specify the number of pixels to put between components.

import java.applet.*;
import java.awt.*;
/*
  <applet code="FlowLayoutApplet" width=300 height=200>
  </applet>
*/

public class test extends Applet
{

  public void init()
  {
    setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
    for (int i = 0; i < 20; i++)
    {
    	add(new Button("Button" + i));
    }
  }
}

The output window look like this

Swing JPanel with background image

This code add an image to Jpanel.

JPanel panel1 = new JPanel();
JFrame recursion_frame = new JFrame();

BackgroundPanel stack_image1 = new BackgroundPanel("Recursion.jpg");

panel1.setLayout(null);
panel1.setLayout(new BorderLayout());
panel1.setBackground(Color.lightGray);
panel1.setVisible(true);
recursion_frame.setContentPane(panel1);  ///adding to panel...
recursion_frame.getContentPane().add(stack_image1);  //adding image to panel...

Position swing window in center of the screen

In some case we need to position the window in the center of the screen . The same effect can be achieved by hard coding the center points .But in that case the window position change when the screen resolution changes

This code will position the window in center irrespective of different screen resolutions

public JFrame stack_frame = new JFrame();
stack_frame.setLocationRelativeTo(null);

Creating a JMenubar in java swing

Creating a JMenubar is simple.

        JMenuBar  menubar = new JMenuBar();
	JMenu menu1 = new JMenu("File");
	JMenu menu2= new JMenu("Help");
	file = new JMenuItem("Exit to menu");
	edit = new JMenuItem("Exit");

	JMenuItem about = new JMenuItem("About us");
	f.setJMenuBar(menubar);
	menu1.add(file);
	menu1.add(edit);
	menu2.add(about);
	menubar.add(menu1);
	menubar.add(menu2);

	file.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Action......
		}
	});
	edit.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Action.....
		}
	});
	about.addActionListener(new ActionListener()
	{
		public void actionPerformed(ActionEvent arg0)
		{
			//Action....
		}
	});

Preventing Overriding in Java

Methods and variables can be ‘override’ in subclasses. (Yes, it’s a good

feature too!). But what if we don’t want to ‘override’ our Methods and Variables in Java?

It’s simple…

Declare them using the keyword ‘final’ as modifier. That’s it.

eg:

final int myVariable = 79;

So the value of myVariable can never be changed any way.

Also for Classes/Methods.

eg:

final class myClass{ whatever your code;} 

It will prevent our myClass being extended.

Creating Exceptions in JAVA

This is a simple custom exception in java. That is, we can create an exception by extending the exception class.

The “throw new MyExcep” will throw an exception and the error message we specified will be displayed

import java.lang.Exception;
@SuppressWarnings("serial")
class MyExcep extends Exception
{
	MyExcep(String Errormsg)
	{
		super(Errormsg);	// call Exception class error message
	}
}
public class Example
{
	public static void main(String[] args)
	{
		int x = 5 , y = 1000;
		try
		{
			float z = (float) x / (float) y;
			if(z < .01)
			{
				throw new MyExcep("Number is too small");
			}
		}
		catch(MyExcep e)
		{
			System.out.println("Caught My Exception");
			System.out.println(e.getMessage());
		}
		finally
		{
			System.out.println("I am Always Here");
		}
	}
}

The output will be like this

Caught My Exception
Number is too small
I am Always Here

Abstract Class in java

This example shows how a simple java abstract class works
Here “Shape” is the abstract class
abstract class Shape
{
abstract void initial(); // methods only defined…..
abstract void display();
}
class cube extends Shape
{
void initial() // Abstract Methods defined….
{
System.out.println(“Hello !! “);
}
void display()
{
System.out.println(“How are you?”);
}
}
public class Abstract
{
public static void main(String[] args)
{
// Shape S = new Shape(); // error cannot create objects for abstrac classes…..
cube C = new cube();
C.initial();
C.display();
}
}
Here we cannot create “Shape” class object because it is abstract
The output is
Hello !!
How are you?

How to create custom layout for your spinner in ANDROID? or Customizable spinner

This code helps you to customize the spinner in ANDROID.

For that you have to create an XML file inside your layout folder as shown below and name it spinner.xml.
You can give all properties that are available for TextView inside this which is going to be then applied for your spinner.

<xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="14sp"
android:typeface="serif"
android:textStyle="bold|italic"
android:textColor="@drawable/yellow"
>
TextView>

Now I will show you how to add it to a spinner.

ArrayAdapter my_Adapter = new ArrayAdapter(this, R.layout.spinner,my_array);
My_spinner.setAdapter(my_Adapter);

“my_array” is an array that populates the spinner and “My_spinner” is the spinner.

Please leave your valuable comments if this post was useful…..

Java Exception

Simple java program to show how exception works

public class exception
{
public static void main(String[] args)
{
try
{
int a = 10;
int b = 10/0;
}
catch(ArithmeticException e)
{
System.out.println(“Exception Caught ” + e);
}
}
}
The output will be like you expect
Exception Caught java.lang.ArithmeticException: / by zero