How to create a transparent frame in Java ?

In a GUI programming at some point the transparent windows are very much in need. The transparent frames are mostly used to show some less important content to users. It is basically a JFrame with faded color. It can also used in creating some widget in a very large application. Here is a code snippet.

import javax.swing.JFrame;
import java.awt.Color;

public class TransparentDemo extends JFrame{
public TransparentDemo(){
setSize(200, 200);

/***
* To make a JFrame transparent this method needs to be set to true
* if this method is not set to true this will throw an exception
* java.awt.IllegalComponentStateException
*/

setUndecorated(true);

/***
* The Transparency of the frame is mainly done with the help of
  * class Color of the package java.awt
* there are 3 arguments of the construction first 3 args are of
  * color red, green, and blue and the
* the last 4th argument is called opacity which is an integeral
  * number raging from 0 to 100 which
* will improve the opacity from 100 to 0 means 0 will be no
  * background and 100 will be pure 
* background with color.
*/
setBackground(new Color(10,200,255,90));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new TransparentDemo().setVisible(true);
}
}

Type the above code in notepad or any editor and run it.

Number of Ways to create objects in Java

There are number of ways to create objects in java. But today i am going to show 4 mostly used ways to create objects in java.

The 4 ways to create object are :

    1. Using new operator
    2. Using Class.forName
    3. Cloning
    4. Deserialization
The first way is very common and mostly used by the developers community which using new operator. Almost all objects are created using this new operator. Here is the simple example code snippet to show the way.

MyObject obj = new MyObject();

The second way is using Class.forName. This is not so popular as much the first way but in some areas of codding we need this to be used. When we know the class name and the class the public default constructor then we can create the object using this way. 

MyObject obj = (MyObject)Class.forName("javaprg.coreprg.MyObject").newInstance();

The third way is using cloning where we use clone(). Generally the clone() is used to make a copy of an existing object. But here I will show you how to make a new object using clone(). See the below code snippet

MyObject myObj = new MyObject();
MyObject newObj = (MyObject) myObj.clone();

The fourth way is to create an object is using object deserialization. Well object deserialization is about creating an object form its own serialized form. Below is a small code snippet to show the process:

ObjectInputStream ois = new ObjectInputStream(anyInputStream);
MyObject obj = (MyObject)ois.readObject();

So here are the for mostly used way to create the object in java programming language.
Thanks for watching.

Run Simple DOS Command from java program

Some of us might have question that can we really run DOS command from our own java program? Yes it is true we can do that. For that we need Process class.

Below is the sample program to run the simple dir command from java program


import java.io.*;

public class RunDosCommands
{
public static void main(String args[])
{
try
{
Process p=Runtime.getRuntime().exec("cmd /c dir");
p.waitFor();
BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line=reader.readLine();
while(line!=null)
{
System.out.println(line);
line=reader.readLine();
}
}
catch(IOException e1) {}
catch(InterruptedException e2) {}

System.out.println("Done");
}
}

That's it you know the drill. Type the program in your editor. Save it as RunDosCommands.java. and run the class file.

Folks, remember it will print the list of directory where the class file is running. For Ex, if the class file is running from C directory it will print all the directory list of your C drive.

Gujarati Typing in Java Application

This Example shows how to use the 3rd party font (.ttf) in our java application. This sometime need when we want to use strictly to some of the other languages like Gujarati, etc. We just need to have a .ttf(True Type Font) file which is need to be loaded by programming in our application.

import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JOptionPane;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.awt.Font;
import java.awt.FontFormatException;

class GujaratiType extends JFrame
{
public Font font,fontUsed;
public GujaratiType()
{
try
{
InputStream myStream = new BufferedInputStream(new FileInputStream("LMG_LAX1.ttf"));
font = Font.createFont(Font.TRUETYPE_FONT, myStream);
fontUsed = font.deriveFont(Font.PLAIN,20);
}
catch(FontFormatException ex)
{
JOptionPane.showMessageDialog(GujaratiType.this,ex,"Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
catch(IOException ex)
{
JOptionPane.showMessageDialog(GujaratiType.this,"System can not find the file : LMG_LAX1.TTF","Error",JOptionPane.ERROR_MESSAGE);
System.exit(0);
}
JTextArea txt = new JTextArea();
txt.setFont(fontUsed);
JScrollPane jsp = new JScrollPane(txt);
add(jsp);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(0,0,300,300);
//setSize(300,300);
setVisible(true);
}
public static void main(String[] a)
{
new GujaratiType();
}
}

FizzBuzz Program

Following is the program for FizzBuzzProblem. It is program to print numbers from 1 to 100, but if the number is multiple of 3 then number should be replaced with "Buzz", if the number is multiple of 5 then number should be replaced with "Fizz", and if the number is multiple of both 3 and 5 then number should be replaced with "FizzBuzz".

public class FizzBuzzProblem
{
    public static void main(String args[])
    {
        for(int i = 1; i <= 100; i++)
        {
            if((i % (3*5)) == 0)
            {
                System.out.println("FizzBuzz");
            }
            else if ((i % 5) == 0)
            {
                System.out.println("Buzz");
              }
            else if ((i % 3) == 0)
            {
                System.out.println("Fizz");
            }
            else
            {
                System.out.println(i);
              }
        }
    }
}

Methods of Iteration we can perform on List

There are five methods we can iterate the List to view its data. I have wrapped up all five methods in one program.

import java.util.List;
import java.util.ListIterator;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.Arrays;

public class ListDemo
{
public static void main(String[] args)
{
List al = new ArrayList();

al.add(0,100);
al.add(1,20);
al.add(2,8);
al.add(3,65);
al.add(4,102);
al.add(5,88);
al.add(6,88);

System.out.println(al+"\n");

Iterator i = al.iterator(); // First Method to iterate
while(i.hasNext())
System.out.print(i.next() + " ");

System.out.println("\n");
Object ob[] = al.toArray(); // Second Method to iterate
Arrays.sort(ob);
for(Object o : ob)
System.out.print(o + " ");

System.out.println("\n");
ListIterator li = al.listIterator();// Third Method to iterate
while(li.hasNext())
System.out.print(li.next() + " ");


System.out.println("\n\nNow in backward");// iterate previous element
System.out.println("--- -- --------");
ListIterator li1 = al.listIterator();
while(li1.hasNext())li1.next();
while(li1.hasPrevious())
System.out.print(li1.previous() + " ");

System.out.println("\n");
for(int i1 = 0 ;i1 < al.size(); i1++) //Forth Method to iterate
{
System.out.print( al.get(i1) + " " );
}

al.set(3,"pranav");
System.out.println("\n");
System.out.println(al+"\n");

}
}

Can Interface have main method ?

First of all try to look at the following code and execute it on your own.

public interface testinterface1
{
String message = "welcome to this group";
static int add ( int a, int b)
{
return a+b;
}
public static void main(String j[])
{
System.out.println(message);
int x=5;
int y=15;
System.out.println(" sum of numbers " + x + " and " + y + " is " + add(x,y));
}
} 

Very first though we may have that this code will not even compile at all and it is true but this will compile in java8. Yes this is true, we can have main method in interface in java8. so try it in java8 and this code will compile for sure. 

Use of intern() in java

First of all, type the below code snippet and save it as Test.java , the compile and run it. and then view the description below code is given.

public class Test{
public static void main(String[] args){
String s1 = "Java";
String s2 = new String("Java");
System.out.println(s1==s2);
s2=s2.intern();
System.out.println(s1==s2);
}
}

When the intern() method is invoked on a String, a lookup is performed on a table of interned Strings. If a String object with the same content is already in the table, a reference to the String in the table is returned. 
Otherwise, the String is added to the table and a reference to it is returned. 
The result is that after interning, all Strings with the same content will point to the same object. 
This saves space, and also allows the Strings to be compared using the == operator, which is much faster than comparison with the equals(Object) method.
So in simple way this function my useful in development.

Example of JTabbedPane

Sometime we need to have something like multiple tabs like in chrome we have. So here i am posting a simple example of JTabbedPane which may help you in any way.

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

class TabDemo extends JFrame
{
JTabbedPane tb;
JTextArea txt;
private int tabCounter = 1;
public TabDemo()
{
tb = new JTabbedPane();
addTab();
setJMenuBar(createMenuBar());
getContentPane().add(tb,BorderLayout.CENTER);
//addTab();
setVisible(true);
setBounds(20,20,400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JMenuBar createMenuBar()
{
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem newFile = new JMenuItem("New");
newFile.setAccelerator(KeyStroke.getKeyStroke('N',KeyEvent.CTRL_DOWN_MASK));
newFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
addTab();
}
});
JMenuItem saveFile = new JMenuItem("Save");
saveFile.setAccelerator(KeyStroke.getKeyStroke('S',KeyEvent.CTRL_DOWN_MASK));
saveFile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int x = tb.getSelectedIndex();
JScrollPane jsp = (JScrollPane)tb.getComponentAt(x);
JTextArea tx = (JTextArea) jsp.getViewport().getView();
//JOptionPane.showMessageDialog(TabDemo.this,tx.getText());
fileSaver(tx.getText());
}
});
file.add(newFile);
file.add(saveFile);
mb.add(file);
return mb;

}
void addTab()
{
txt = new JTextArea();
JScrollPane txtPnl = new JScrollPane(txt);
JPanel tbPnl = new JPanel();
tbPnl.setOpaque(false);
tbPnl.setLayout(new FlowLayout());
JLabel lbl = new JLabel("Tab - "+tabCounter);
JButton btnClose = new JButton("X");
tbPnl.add(lbl);
tbPnl.add(btnClose);
tb.addTab(null,txtPnl);
btnClose.setActionCommand(""+tabCounter);
btnClose.setFont(new Font("Serif",1,9));
lbl.setFont(new Font("Serif",1,9));
btnClose.setOpaque(false);
btnClose.setBorder(null);
btnClose.setBackground(Color.RED);
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JButton btn =(JButton) e.getSource();
String str = btn.getActionCommand();
for(int i =0 ;i <tb.getTabCount();i++)
{
JPanel pnl = (JPanel)tb.getTabComponentAt(i);
btn = (JButton)pnl.getComponent(1);
String str2 = btn.getActionCommand();
if(str.equals(str2))
{
tb.removeTabAt(i);
tabCounter--;
break;
}
}
}
};
btnClose.addActionListener(al);

//tb.setTabComponentAt(tb.getTabCount()-1 ,lbl);
tb.setTabComponentAt(tb.getTabCount()-1 , tbPnl);
tb.setSelectedIndex(tb.getTabCount() - 1);
tabCounter++;
}
public static void main(String []args)
{
new TabDemo();
}
private void fileSaver(String text)
{
JFileChooser chooser = new JFileChooser();
int result = chooser.showSaveDialog(TabDemo.this);

/*if(result != JFileChooser.APPROVE_OPTION)
{ return false; }*/
File file = chooser.getSelectedFile();
setTitle(file.getName());

try
{
FileOutputStream out = new FileOutputStream(file);
//String str = txt.getText();
byte b[] = text.getBytes();
out.write(b);
out.close();
//return true;
}
catch(Exception ex){}//return false;}
}
}

Now Type the above code in text editor save it as TabDemo.java.
Then compile it by command javac TabDemo.java
and execute it by command java TabDemo

A Simple Enumeration demo in java

Here is a code for simple enum in java.

enum Cal
{
ADD
{
public double compute(double a, double b)
{ return a+b; };
},
SUB
{
public double compute(double a, double b)
{ return a-b; };
},
MUL
{
public double compute(double a, double b)
{ return a*b; };
},
DIV
{
public double compute(double a, double b)
{ return a/b; };
},
MOD
{
public double compute(double a, double b)
{ return a%b; };
},
;

public abstract double compute(double a, double b);


public static void main(String[] ar)
{
String opName = ar[0].toUpperCase();
double a = Double.parseDouble(ar[1]);
double b = Double.parseDouble(ar[2]);

System.out.println(Cal.valueOf(opName).compute(a,b));
}
}

To execute this code type the above code in any text editor and compile it by the command javac Cal.java and execute it by command java Cal 10 ADD 20

Differentiate Total Zeros and Total Non Zeros from a whole number

A simple program to differentiate the Zeros and non zeros value from a complete number.

public class DiffZeroNonZero{
public static void main(String[] args){
long no;
try{
no = Long.parseLong(args[0]);
}catch(ArrayIndexOutOfBoundsException ex){
System.out.println("Please provide proper number as argument....");
return;
}
long tmp_z=0,tmp_nz=0,a;
int count_z=0,count_nz=0;
int pos_z = 0;
int pos_nz = 0;
System.out.println("\n\nEntered Nuber Is :-> " + no);
//Storing the number for future use.....
tmp_z = no;
tmp_nz = no;
//Getting the number of zeros and non_zeros from whole number.....
while(no>0){
a = no%10;
if(a!=0)
count_nz++;
else
count_z++;
no=no/10;
}
long zeros[] = new long[count_z];
long non_zeros[] = new long[count_nz];
//Storing the values of zeros and non_zeros in different arrays....
while(tmp_nz>0){
a = tmp_nz%10;
if(a!=0){
non_zeros[pos_nz++]=a;
}
tmp_nz=tmp_nz/10;
}
while(tmp_z>0){
a = tmp_z%10;
if(a!=0){
}else{
zeros[pos_z++]=a;
}
tmp_z=tmp_z/10;
}
//Printing both the arrays to user.....
System.out.print("\n\n Zeros :->" + java.util.Arrays.toString(zeros));
System.out.print("\n\n Non Zeros :->" + java.util.Arrays.toString(non_zeros));
}
}

Default and Escape Button in Java

We may sometimes need to have that when we press the enter key it automatically performs some tasks.
And when we press the escape key it automatically exits the application or like else.
So here is a simple example to do so.

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionEvent;

public class DefaultEscapeButton extends JFrame
{
JButton btn1,btn2;
        //Preparing ActionListener for escape key pressed
ActionListener al = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
};
DefaultEscapeButton()
{
setLayout(null);
btn1 = new JButton("Default");
btn1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
System.out.println(btn1.getText());
}
});
btn1.setBounds(10,10,150,30);
btn2 = new JButton("Cancel");
btn2.setBounds(10,50,150,30);
                //This is the code for when Escape key is pressed
getRootPane().registerKeyboardAction(al,KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE,0),JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);


add(btn1);
add(btn2);
getRootPane().setDefaultButton(btn1);
setVisible(true);
setSize(300,300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new DefaultEscapeButton();
}
}

Add Button in Tab of JTabbedPane

There are lots of things we can do in the desktop application using java's swing technology. One of  which here is adding a button to the Tab for some help user to closing the tab, etc. This kind of example can help to build some application having facility for multiple infinite tab like Browser application, or a kind of text editor, etc.

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JToolBar;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class AddButtonToTabBar extends JFrame {
private JTabbedPane tp;
private int tabCounter = 0;

public AddButtonToTabBar() {
super("Editor");
setDefaultCloseOperation(EXIT_ON_CLOSE);

JToolBar jtb = new JToolBar();
JButton btnAdd = new JButton("Add Tab");
ActionListener addTabl = new ActionListener() {
 public void actionPerformed(ActionEvent e) {
addTab();
 }
};
btnAdd.addActionListener(addTabl);
jtb.add(btnAdd);

JPanel pnlURL = new JPanel();
tp = new JTabbedPane();
addTab();
getContentPane().add(jtb, BorderLayout.NORTH);
getContentPane().add(tp, BorderLayout.CENTER);

setSize(700, 700);
setVisible(true);
}

void addTab() {
// A Simple Text editor
JEditorPane ep = new JEditorPane();
ep.setEditable(true);
tp.addTab("Tab - " + tabCounter, new JScrollPane(ep));

//Preparing a button to add 
JButton tabCloseButton = new JButton("X");
tabCloseButton.setActionCommand("" + tabCounter);

//ActionListener for what to do when the button is clicked, here is to close the particular tab
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JButton btn = (JButton) ae.getSource(); // It will get the button object which is clicked
String s1 = btn.getActionCommand();
for (int i = 1; i < tp.getTabCount(); i++) {
JPanel pnl = (JPanel) tp.getTabComponentAt(i); // It will return the whole component which we had set in the Tab

// It will get the button component. The parameter for the getComponent 
// is index of the total number of component. Here 1 means the button and 0 means the lable.
btn = (JButton) pnl.getComponent(1);
String s2 = btn.getActionCommand();
if (s1.equals(s2)) {
tp.removeTabAt(i);
break;
}
}
}
};
tabCloseButton.addActionListener(al);

// This condition is to make at least one tab to be in the application.
if (tabCounter != 0) {
JPanel pnl = new JPanel();
pnl.setOpaque(false);
pnl.add(new JLabel("Tab - "+tabCounter));
pnl.add(tabCloseButton);
tp.setTabComponentAt(tp.getTabCount() - 1, pnl);
tp.setSelectedIndex(tp.getTabCount() - 1);
}
tabCounter++;
}

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

}
}

Write the above program, save it as AddButtonToTabBar.java , compile it and run it.