Jumat, 10 Januari 2014

This basic tutorial demonstrates how to create tabs in a java GUI window . Let’s assume that we are going to create a Crypto tool, which can encrypt some data and also decrypt  some encrypted data into some readable format. But of course I have no intention to discuss how to encrypt/decrypt data here. For the user friendliness of our GUI it is better to separately display these two tasks in it. hence we will have a Encryption tab and a decryption tab and so on.

This is the preview of the tabbed window. I added only a single button to keep the code short and concise.

Untitled

The GUI has just two tabs. every tab has a title , an icon (optional) and a component ( the component to be displayed when the tab is clicked). this component is most probably a JPanel which contains all the other components (buttons , labels …etc). and optionally , a tooltip can also be added . the source code for  creating tabbed window is given below.

package hasijournal.tabbeddemo;
import javax.swing.*;
import java.awt.*;
class Crypto extends JFrame {
    public Crypto() {
        setTitle("Crypto Tool");
        JTabbedPane jtp = new JTabbedPane();
        // get the container
        getContentPane().add(jtp);
        // create tab components
        JPanel jp1 = new JPanel();
        JPanel jp2 = new JPanel();
        jp1.setLayout(new BorderLayout());
        jp2.setLayout(new BorderLayout());
        
        JButton ebtn = new JButton("Encrypt data");
        jp1.add(ebtn, BorderLayout.SOUTH);
        JButton dbtn = new JButton("Decrypt data");
        jp2.add(dbtn, BorderLayout.SOUTH);
        
        // add icons
        Icon it1= new ImageIcon("enc.png");
        Icon it2= new ImageIcon("dec.png");
        
        /*--- Overloaded addTab methods in JTabbePane class---*/
        //  void addTab(String title, Component component)
        /*  Adds a component represented by a title and no icon. */
        // void addTab(String title, Icon icon, Component component)          
        /* Adds a component represented by a title and/or icon,*/
        
        // void addTab(String title, Icon icon, Component component, String tip)
        /* Adds a component and tip represented by a title and/or icon */
        jtp.addTab("Encrypt",it1,jp1,"Encrypts data");
        jtp.addTab("Decrypt",it2,jp2,"Decrypts data");
        
        
    }
    public static void main(String[] args)  {
        Crypto tp = new Crypto();
        tp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tp.setBounds(100,100, 300, 300);
        try{
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(Exception e){}
        SwingUtilities.updateComponentTreeUI(tp);
        
        tp.setVisible(true);
    }
}


 

Related Posts by Categories

Categories: , , , , , , ,

0 komentar:

Posting Komentar

FOOTER