Archive for the ‘Swing’ Category

Firefox buttons in your JTabbedPane. (Example)

Tuesday, December 18th, 2007

For my last post I showed how easy it is to add components to the tabs in JTabbedPane. Someone replied that the example was a bit primitive and asked me how to add buttons that look similar to the Firefox tab buttons. Below is an example that uses Fixfox buttons.

import java.awt.*;
import java.awt.event.*;
import java.net.*;

import javax.swing.*;

public class JtabbedCloseExample extends JFrame {

JTabbedPane jtabbedPane;

class TabButton extends JPanel implements ActionListener {

ImageIcon reg = null;
ImageIcon over = null;public TabButton( String label ){

super(new FlowLayout());add( new JLabel( label ));
try{

// load firefox buttons
reg = new ImageIcon(new URL(”http://javajiggle.com/images/regular.JPG”));
over = new ImageIcon(new URL(”http://javajiggle.com/images/hoverOver.JPG”));

} catch( Exception e ){

e.printStackTrace();

}
setOpaque(false);
final TabButton self = this;
final JButton button = new JButton(reg);
button.setOpaque(false);
button.setRolloverIcon(over);
button.setPressedIcon(over);
button.setBorderPainted( false );
button.setContentAreaFilled(false);
button.addActionListener( this );
add( button );

}

public void actionPerformed(ActionEvent ae ){

// close the tab which was clicked
jtabbedPane.remove(jtabbedPane.indexOfTabComponent( this ) );

}

}

public JtabbedCloseExample() {

jtabbedPane = new JTabbedPane();
jtabbedPane.add(new JTextArea(”Tab 1 text area. Using Firefox buttons!”));
jtabbedPane.add(new JTextArea(”Tab 2 text area. Using Firefox buttons!”));
jtabbedPane.add(new JTextArea(”Tab 3 text area. Using Firefox buttons!”));
jtabbedPane.setTabComponentAt( 0, new TabButton(”Tab 1″) );
jtabbedPane.setTabComponentAt( 1, new TabButton(”Tab 2″) );
jtabbedPane.setTabComponentAt( 2, new TabButton(”Tab 3″) );
getContentPane().add( jtabbedPane );
setSize(new Dimension(300, 200));
setVisible(true);

}

public static void main ( String [] args ){

new JtabbedCloseExample();

}

}

JTabbedPane using firefox buttons.