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