Sunday, 17 November 2013

AbstractButton and its sub classes - Tutorial

Here is a complete list of exhaustive tutorials on JButton, JToggleButton, JCheckBox, JRadioButton which will help you ace all the children of AbstractButton.
Let us now look about what they are.

JButton

JButton is a nothing more than a push-button which you might already have gone through many times. User can click on it to get anything done.

JToggleButton

A JToggleButton is another component much similar to a JButton. But the difference is a JToggleButton goes into pressed state when mouse is pressed on it. To get that back into normal state, we need to press again. This component is mostly used when there is an on/off situation. You'll get a better idea of what it is when you see it in practical.

JCheckBox

A JCheckBox lies on a single principle, checked/unchecked. This component is mostly used in when we are checking multiple items, for example in Job search site, you might have undergone this where you select multiple skills, a check box is mostly used.

JRadioButton

JRadioButton is also based on the same principle as that of the JCheckBox. But the difference is that a JRadioButton is typically used when the user has to choose only one among the many items in a group. For instance, you can use it for Male/Female, the user has to select either of it, but not both. In AWT, you don't have specified class for JRadioButton as here.

JMenuItem

A JMenuItem as said previously, is an item included in a menu where the user can click on it or invoke it by a shortcut. You can see this in Notepad, New, Open, Save etc. are called menu items. You can invoke them either by click on them or selecting them and hitting enter or via a shortcut.

JCheckBoxMenuItem

This is a JMenuItem with JCheckBox in it. You might have seen this in Notepad > Format > Wordwrap.

JRadioButtonMenuItem

This is a JMenuItem with a JRadioButton in it. You can better know it and its uses if you take a look at the example.

Note: JButton, JToggleButton, JMenuItem are all sub-classes of AbstractButton, JCheckBox and JRadioButton are sub-classes of JToggleButton. JRadioButtonMenuItem and JCheckBoxMenuItem are sub-classes of JMenuItem.

ObjectInputStream — Reading Object From a File

This example will show you how to read a Java object from a file using ObjectInputStream. This is a part of serialization topic.

import java.io.*;

class ReadObj

{

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

    {

        FileInputStream fin=new FileInputStream("obj.dat");

       

        ObjectInputStream oin=new ObjectInputStream(fin);

       

        String st=(String)oin.readObject();

       

        System.out.println(st);

    }

}


Here, the file obj.dat contains a String object in it. You need to note that to read an object from a file, you need to write it to that file first. The previous program will show you how to write an object to a file.

fin=new FileInputStream("obj.dat"): This statement creates a FileInputStream object pointing to obj.dat
oin=new ObjectInputStream(fin): This statement creates an ObjectInputStream object pointing to FileInputStream object fin.
oin.readObject(): This method in ObjectInputStream class reads an object from the file obj.dat and returns it. As this method returns java.lang.Object, type casting is necessary.

ObjectOutputStream — Writing Object To a File

This example illustrates using ObjectOutputStream to write an object to a file. This is a part of serialization tutorial.

import java.io.*;

class WriteObj

{

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

    {

        FileOutputStream fout=new FileOutputStream("obj.dat");

       

        ObjectOutputStream out=new ObjectOutputStream(fout);

       

        String st="I am written in the file.";

       

        out.writeObject(st);

       

        out.close();

        fout.close();

    }

}


fout=new FileOutputStream("obj.dat"): This statement creates a FileOutputStream object pointing to obj.dat
out=new ObjectOutputStream(fout): This statement creates an ObjectOutputStream object pointing to the given FileOutputStream object.
writeObject(st): This method in the ObjectOutputStream class writes a String object to the file obj.dat

Saturday, 16 November 2013

java.io.SequenceInputStream — Everything You Need to Know

Here are two SequenceInputStream examples that you should know. First of all, a SequenceInputStream is an input stream object pointing to multiple input streams. It can read data from several InputStreams in the given order. You can combine files using this class.

In this tutorial, you'll know
  1. Constructors and Methods of java.io.SequenceInputStream class
  2. Printing data read from SequenceInputStream
  3. Writing SequenceInputStream to a file using FileOutputStream
The first example is on the first constructor which takes two InputStream objects and the second is on the last constructor which takes an enumeration of InputStream classes. Let us have a look.

public SequenceInputStream(InputStream s1,InputStream s2)

public SequenceInputStream(Enumeration<? extends InputStream> e)


Here are the methods of SequenceInputStream

// Returns the no.of bytes pointing to the SequenceInputStream

public int available()


// Close the SequenceInputStream

public void close()


// Read each byte from the SequenceInputStream and return it

public int read()


// Read upto len bytes from offset into a byte array b

public void read(byte[] b,int off,int len)


Example on SequenceInputStream using first Constructor



import java.io.*;

class SequenceInputStreamFirstCon

{

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

    {

    SequenceInputStream sin=new SequenceInputStream(new FileInputStream(args[0]),new FileInputStream(args[1]));

   

    int k;

   

    FileOutputStream fout=new FileOutputStream("final.txt");

   

        while((k=sin.read())!=-1)

        {

            fout.write(k);

            System.out.print((char)k);

        }

   

    sin.close();

    fout.close();

    }

}



Example of SequenceInputStream class using second constructor



import java.io.*;

import java.util.*;

class SequenceInputStreamExample

{

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

    {

    Vector<FileInputStream> v=new Vector<FileInputStream>();



        for(String k:args)

        v.add(new FileInputStream(k));

   

    SequenceInputStream sin=new SequenceInputStream(v.elements());

   

    int k;

   

    FileOutputStream fout=new FileOutputStream("final.txt");

   

        while((k=sin.read())!=-1)

        {

            fout.write(k);

            System.out.print((char)k);

        }

   

    sin.close();

    fout.close();

    }

}


Friday, 15 November 2013

Create an Advanced Chat Box in Java

The following example illustrates creating an advanced chat box in Java in Swing that detects whether the user is thinking or typing and displays the message accordingly. This chat box is just for demo purpose and it doesn't use any of the networking concepts to interact with the second person.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
class Chatbox extends JFrame
{
JPanel jp;
JTextField jt;
JTextArea ta;
JLabel l;
boolean typing;
Timer t;

    public Chatbox()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
   
        // Set frame properties
        setTitle("Chatbox");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
       
        // Create a JPanel and set layout
        jp=new JPanel();
        jp.setLayout(new GridLayout(2,1));
        l=new JLabel();
        jp.add(l);
       
        // Create a timer that executes every 1 millisecond
        t=new Timer(1,new ActionListener(){
            public void actionPerformed(ActionEvent ae)
            {
                // If the user isn't typing, he is thinking
                if(!typing)
                l.setText("Thinking..");
            }
        });
       
        // Set initial delay of 2000 ms
        // That means, actionPerformed() is executed 2500ms
        // after the start() is called
        t.setInitialDelay(2000);
       
        // Create JTextField, add it.
        jt=new JTextField();
        jp.add(jt);
       
       
        // Add panel to the south,
        add(jp,BorderLayout.SOUTH);
       
       
        // Add a KeyListener
        jt.addKeyListener(new KeyAdapter(){
            public void keyPressed(KeyEvent ke)
            {
           
                // Key pressed means, the user is typing
                l.setText("You are typing..");
               
                // When key is pressed, stop the timer
                // so that the user is not thinking, he is typing
                t.stop();
               
                // He is typing, the key is pressed
                typing=true;
               
                // If he presses enter, add text to chat textarea
                if(ke.getKeyCode()==KeyEvent.VK_ENTER) showLabel(jt.getText());
            }
           
            public void keyReleased(KeyEvent ke)
            {
           
                // When the user isn't typing..
                typing=false;
               
                // If the timer is not running, i.e.
                // when the user is not thinking..
                if(!t.isRunning())
               
                // He released a key, start the timer,
                // the timer is started after 2500ms, it sees
                // whether the user is still in the keyReleased state
                // which means, he is thinking
                t.start();
            }
        });
       
        // Create a textarea
        ta=new JTextArea();
               
        // Make it non-editable
        ta.setEditable(false);
       
        // Set some margin, for the text
        ta.setMargin(new Insets(7,7,7,7));
       
        // Set a scrollpane
        JScrollPane js=new JScrollPane(ta);
        add(js);
       
        addWindowListener(new WindowAdapter(){
            public void windowOpened(WindowEvent we)
            {
                // Get the focus when window is opened
                jt.requestFocus();
            }
        });
       
        setSize(400,400);
        setLocationRelativeTo(null);
        setVisible(true);
    }
   
    private void showLabel(String text)
    {
        // If text is empty return
        if(text.trim().isEmpty()) return;
       
        // Otherwise, append text with a new line
        ta.append(text+"\n");
       
        // Set textfield and label text to empty string
        jt.setText("");
        l.setText("");
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new Chatbox();
            }
        });
    }
}

Chat box screenshot

Get IP address in Java using InetAddress

The following example illustrates getting IP address in Java using InetAddress class.

import java.net.*;
class GetIP
{
    public static void main(String args[]) throws Exception
    {
        InetAddress i=InetAddress.getByName(args[0]);
        System.out.println(new String(i.getHostAddress()));
    }
}
getByName(args[0]): This static method of InetAddress class gets the IP address of the given host name which has to be in the format, google.com for example.

Thursday, 14 November 2013

Getting Started with JList and JComboBox

The following tutorial illustrates getting started with two major swing components, the JList and JComboBox. The examples below provide you a basic understanding of what they are.

JComboBox lets the user choose a single item from multiple items. It only displays single item to the user. You can see it in many sites, where they ask you to choose your country.
JList is another light-weight component similar to a JComboBox but with two major differences. The first is that JList shows multiple items (rows) to the user and also it gives an option to let the user select multiple items.