Arbitrary Components for JTabbedPane Tab Headers

Một phần của tài liệu Beginning Java SE 6 Platform From Novice to Professional phần 3 pps (Trang 41 - 47)

The javax.swing.JTabbedPaneclass implements a component divided into tabs. Each tab contains one component. You can place more than one component on a tab by using a combination of layout managers and containers. The user clicks a tab’s header to switch to that tab.

Prior to Java SE 6, the header was restricted to presenting some combination of a Stringlabel and a javax.swing.Icon(and a tool tip String). Many developers found this too limiting; for example, they wanted to be able to place a close button on the header, to allow users to close the tab. Java SE 6 now allows an arbitrary java.awt.Componentto appear on the header.

119

C H A P T E R 4

Three methods have been added to JTabbedPaneto support placing arbitrary components on tab headers. Check out their descriptions in Table 4-1.

Table 4-1.JTabbedPane Class Tab-Component Methods

Method Description

public void Specifies the componentthat renders the title for a setTabComponentAt(int index, specified tab. The tab is identified by the zero-based Component component) index. An IndexOutOfBoundsExceptionis thrown if

indexis less than zero or greater than the final tab’s index. An IllegalArgumentExceptionis thrown if a component has already been specified.

public Component Returns the component associated with the index getTabComponentAt(int index) tab. An IndexOutOfBoundsExceptionis thrown if index

is less than zero or greater than the final tab’s index.

public int Returns the index of the tab associated with indexOfTabComponent(Component tabComponent. Returns –1 if there is no tab.

tabComponent)

To demonstrate the setTabComponentAt()and getTabComponentAt()methods, I’ve prepared a minimal web browser application. The application lets you enter a URL and display its web page on the current tab. You can add new tabs via the menu, switch between tabs, and click a tab header’s close button to close the tab and remove the displayed page. Listing 4-1 shows the application’s source code.

Listing 4-1.Browser.java // Browser.java

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import javax.swing.*;

import javax.swing.event.*;

public class Browser extends JFrame implements HyperlinkListener {

private JTextField txtURL;

private JTabbedPane tp;

private JLabel lblStatus;

private ImageIcon ii = new ImageIcon ("close.gif");

private Dimension iiSize = new Dimension (ii.getIconWidth (), ii.getIconHeight ());

private int tabCounter = 0;

public Browser () {

super ("Browser");

setDefaultCloseOperation (EXIT_ON_CLOSE);

JMenuBar mb = new JMenuBar ();

JMenu mFile = new JMenu ("File");

JMenuItem mi = new JMenuItem ("Add Tab");

ActionListener addTabl = new ActionListener () {

public void actionPerformed (ActionEvent e) {

addTab ();

} };

mi.addActionListener (addTabl);

mFile.add (mi);

mb.add (mFile);

setJMenuBar (mb);

JPanel pnlURL = new JPanel ();

pnlURL.setLayout (new BorderLayout ());

pnlURL.add (new JLabel ("URL: "), BorderLayout.WEST);

txtURL = new JTextField ("");

pnlURL.add (txtURL, BorderLayout.CENTER);

getContentPane ().add (pnlURL, BorderLayout.NORTH);

tp = new JTabbedPane ();

addTab ();

getContentPane ().add (tp, BorderLayout.CENTER);

lblStatus = new JLabel (" ");

getContentPane ().add (lblStatus, BorderLayout.SOUTH);

ActionListener al;

al = new ActionListener () {

public void actionPerformed (ActionEvent ae) {

try {

Component c = tp.getSelectedComponent ();

JScrollPane sp = (JScrollPane) c;

c = sp.getViewport ().getView ();

JEditorPane ep = (JEditorPane) c;

ep.setPage (ae.getActionCommand ());

}

catch (Exception e) {

lblStatus.setText ("Browser problem: "+e.getMessage ());

} } };

txtURL.addActionListener (al);

setSize (300, 300);

setVisible (true);

}

void addTab () {

JEditorPane ep = new JEditorPane ();

ep.setEditable (false);

ep.addHyperlinkListener (this);

tp.addTab (null, new JScrollPane (ep));

JButton tabCloseButton = new JButton (ii);

tabCloseButton.setActionCommand (""+tabCounter);

tabCloseButton.setPreferredSize (iiSize);

ActionListener al;

al = new ActionListener () {

public void actionPerformed (ActionEvent ae)

{

JButton btn = (JButton) ae.getSource ();

String s1 = btn.getActionCommand ();

for (int i = 1; i < tp.getTabCount (); i++) {

JPanel pnl = (JPanel) tp.getTabComponentAt (i);

btn = (JButton) pnl.getComponent (0);

String s2 = btn.getActionCommand ();

if (s1.equals (s2)) {

tp.removeTabAt (i);

break;

} } } };

tabCloseButton.addActionListener (al);

if (tabCounter != 0) {

JPanel pnl = new JPanel ();

pnl.setOpaque (false);

pnl.add (tabCloseButton);

tp.setTabComponentAt (tp.getTabCount ()-1, pnl);

tp.setSelectedIndex (tp.getTabCount ()-1);

}

tabCounter++;

}

public void hyperlinkUpdate (HyperlinkEvent hle) {

HyperlinkEvent.EventType evtype = hle.getEventType ();

if (evtype == HyperlinkEvent.EventType.ENTERED) lblStatus.setText (hle.getURL ().toString ());

else

if (evtype == HyperlinkEvent.EventType.EXITED) lblStatus.setText (" ");

}

public static void main (String [] args)

{

Runnable r = new Runnable () {

public void run () {

new Browser ();

} };

EventQueue.invokeLater (r);

} }

In Listing 4-1, notice the use of tabCounter, setActionCommand(), and getActionCommand() to uniquely identify each tab. I did this to identify the tab whose close button was clicked.

Although I could have attempted to use the JTabbedPaneclass’s getSelectedIndex() method to accomplish the same task, that method is useless if the tab is not selected when its close button is clicked.

After compiling the source code, launch this application. As shown in Figure 4-1, the GUI consists of a File menu (for adding tabs), a text field for entering URLs, a tabbed area with a single starting tab for viewing a web page, and a status bar for viewing links and error messages. The starting tab does not have a close button, because at least one tab must be present for the button to be added.

Figure 4-1.The simple web browser application lets you add tabs, which will appear with close buttons.

Enter a complete URL in the text field (http://www.apress.com, for example), and the page will appear on the starting tab. (The status bar will present an error message if the page cannot be loaded.) From the File menu, choose the Add Tab menu item to add another tab. Then enter another complete URL. Notice the close button on this new tab’s header. After toggling between these tabs, click this button to close the newly added tab.

Caution The Browserapplication must be able to load close.gif, which presents the close button’s graphic. If this file cannot be loaded, you will not see a close button on the tab headers (the starting tab header never displays a close button), and you will not be able to close these tabs.

Một phần của tài liệu Beginning Java SE 6 Platform From Novice to Professional phần 3 pps (Trang 41 - 47)

Tải bản đầy đủ (PDF)

(51 trang)