Understanding basics of jTabbedPane

UPDATED: 25 May 2013
This tutorial for beginners. I'll help you to understand the basics of jTabbedPane. We'll understand the below topics in this tutorial.

  • How to add new tab in jTabbedPane? or How to add new tab in java swing?
  • How to remove tab from jTabbedPane? or How to remove tab in java swing?
  • How to set popup menu in jTabbedPane? or How to set icon in popup menu item?

jTabbedPane , swing

If you are working with IDE like netbeans then it provides drag and drop facilities for components. All you need to implement code for new tab. Lets have a look at code snippet.
/*
 * New Tab 
 * Code for non IDE environment 
 */
JTabbedPane jTabbedPane1 = new JTabbedPane();
JPanel content = new JPanel();
setContentPane(content);
content.setLayout(new BorderLayout());
content.add(jTabbedPane1);

/* 
 * Code for IDE environment and non IDE enviroment 
 * Add this line of code for button click event, key stroke event, etc...
 * Below code insert jTextArea in every new tab. You can insert component as per your need.
 * jTabbedPane1.addTab("Untitled",new JScrollPane(new JTextArea());
*/
jTabbedPane1.addTab("Untitled", new JScrollPane());

Now lets check out the code for closing the tab. I think there no need to say that jTabbedPane must be initialized.
/* 
 * Remove tab / Close tab
 * Add this line of code for button click event, key stroke event, etc... 
 */
int remIndex = jTabbedPane1.getSelectedIndex();
if (remIndex < 0) {
     JOptionPane.showMessageDialog(rootPane, "No tab available to close");
} else {
     jTabbedPane1.remove(remIndex);
}

Let's create popup menu on the tab. I'm giving you the basic idea for creating popup menu. You need to implement click event for that popup menu items. In below code snippet you can also find how to set icon in popup menuitems.

How to implement click event on popup menuitems?
- You can attach action listener for that menu items.
 /* 
  * Popup menu
  * images/icons for popup menuitems are available in package com.javaquery.images
  * Add this code in constructor 
 */
 JPopupMenu pop_up = new JPopupMenu();
 JMenuItem savefile = new JMenuItem("Save");
 savefile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Save.gif")));
 JMenuItem openfile = new JMenuItem("Open File");
 openfile.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/javaquery/images/Open.gif")));
 JMenuItem newtab = new JMenuItem("New Tab");
 JMenuItem closetab = new JMenuItem("Close Tab");

 //savefile.setAccelerator(KeyStroke.getKeyStroke("control S")); //Key stroke
 //savefile.addActionListener(new savefile()); //new savefile() is class the implements actionlistner

 pop_up.add(savefile);
 pop_up.add(openfile);
 pop_up.addSeparator();
 pop_up.add(newtab);
 pop_up.add(closetab);
 jTabbedPane1.setComponentPopupMenu(pop_up);

0 comments :