Icons in jTabbedPane

Hi,
I am using Sun One Studio 4 update 1. There seems to be a bug in the automatic code generation of jTabbedPanes: if you try to insert a tab Icon (from URL) you can see the icon in the preview but there is no change in the source code! Does anyone know how to solve this problem?
Thanks for your help, Elke

I figured it out, I made a custom UI class that extends BasicTabbedUI and set the constraints that I desired.

Similar Messages

  • How to add icons to JTabbedPane?

    hi, how to add an icon on each tabbed in JTabbedPane?

    Use JTabbedPane's setIconAt(...) method tabPane.setIconAt(int index, Icon icon) Please read the API a little more carefully.
    ICE

  • How to replace coffeecup icon on JTabbedPane, setIconImage doesnt work?

    I've read many posts where people ask how to replace the coffeecup icon with their own chosen icon and all the replies say to use "setIconImage" but this does not work with a JTabbedPane. Does anyone know how to replace the coffeecup on an application that is using a JTabbedPane?

    Are you talking about the icon on a tab or the icon in the upper left corner of the frame?
    To set the icon for the frame:
    java.net.URL url = getClass().getResource("./images/my_image.jpg"); this.setIconImage(Toolkit.getDefaultToolkit().getImage(url));To set the icon on a tab, look at the addTab() method of javax.swing.JTabbedPane.

  • Clickable icons on JTabbedPane's tabs

    Hey,
    I'm working on a close icon for tabbing pages in a JTabbedPane. The icon
    should only appear on some tabs. The amount of tabs varies, there are
    always opened new tabs and others closed.
    The class that implements a tabbing page contains a boolean for beeing
    closeable and generates an ImageIcon showing some cross, there are
    getters and setters for the access of each.
    The class that contains the JTabbedPane stores those tabs also in a
    separate ArrayList. It contains methods to add and remove tabs using the
    following line in the case of closeable tabs:
         public void addTab( Tab06 tab){
              tabpan.addTab( tab.getTabName(), tab.getImageIcon(), tab.getTab());
    // ...To remove the closeable tab like this:
         public void removeCloseableTabAt( int idx){
              if( getTabAt( idx).isCloseable()){
                   removeTabAt(idx);
    // ...Ok, there's a MouseListener that should work like this:
              tabpan.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent me) {
                        int index = tabpan.getSelectedIndex();                    
                        if(getTabAt(index).isCloseable()){
                             if(getTabAt(index).getImageIcon().contains(me.getX(), me.getY())){
                                  removeCloseableTabAt( index);
              });My problem now is, ImageIcon doesn't contain a "contains(y,x)" method.
    How can I realize checking if a click appeared within the Icon Rectangle, so that it should close in an elegant way? TIA

    Hey,
    I'm working on a close icon for tabbing pages in a
    JTabbedPane. The icon
    should only appear on some tabs. The amount of tabs
    varies, there are
    always opened new tabs and others closed.If you are using JDK 1.6, you can use the setTabComponentAt() method to use any component as a tab. This allows you to put normal JButtons and other things in a tab. Here's an example:
    ==============
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Image;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.awt.image.FilteredImageSource;
    import java.awt.image.ImageFilter;
    import java.awt.image.ImageProducer;
    import java.awt.image.RGBImageFilter;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    public class CloseableTabComponentTest {
        public CloseableTabComponentTest() {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            File file = new File("C:\\TEMP\\terminate.gif");
            BufferedImage img = null;
            try {
                img = ImageIO.read(file);
            } catch (IOException ioe) {
                ioe.printStackTrace();
                System.exit(0);
            final JTabbedPane tabbedPane = new JTabbedPane();
            for (int i = 0; i < 10; i++) {
                final JPanel nextPanel = new JPanel();
                nextPanel.add(new JLabel("Pane " + i), BorderLayout.CENTER);
                tabbedPane.add(nextPanel);
                CloseableTabComponent ctc = new CloseableTabComponent("Tab " + i, img);
                ctc.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ae) {
                        tabbedPane.remove(nextPanel);
                tabbedPane.setTabComponentAt(i, ctc);
            f.add(tabbedPane, BorderLayout.CENTER);
            f.setSize(400,300);
            f.setVisible(true);
        public static void main(String[] args) throws Exception {
            new CloseableTabComponentTest();
    class CloseableTabComponent extends JPanel {
        private String title;
        private Icon buttonIcon;
        private Icon rolloverIcon;
        private JButton delegateButton;
        CloseableTabComponent(String title, Image img) {
            this.title = title;
            this.rolloverIcon = new ImageIcon(img);
            ImageFilter filter = new RolloverImageFilter();
            ImageProducer producer = new FilteredImageSource(img.getSource(),filter);
            buttonIcon = new ImageIcon(Toolkit.getDefaultToolkit().createImage(producer));
            initialize();
        public void addActionListener(ActionListener l) {
            delegateButton.addActionListener(l);
        public void removeActionListener(ActionListener l) {
            delegateButton.removeActionListener(l);
        private void initialize() {
            setOpaque(false);
            setLayout(new GridBagLayout());
            delegateButton = new JButton(buttonIcon);
            delegateButton.setPreferredSize(new Dimension(buttonIcon.getIconWidth(), buttonIcon.getIconHeight()));
            delegateButton.setBorderPainted(false);
            delegateButton.setFocusPainted(false);
            delegateButton.setOpaque(false);
            delegateButton.setContentAreaFilled(false);
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.weightx = 1.0f;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weighty = 1.0f;
            gbc.anchor = GridBagConstraints.CENTER;
            gbc.insets = new Insets(0,2,0,2);
            JLabel titleLabel = new JLabel(this.title);
            add(titleLabel/*, gbc*/);
            gbc = new GridBagConstraints();
            gbc.anchor = GridBagConstraints.EAST;
            add(delegateButton/*, gbc*/);
            delegateButton.setRolloverIcon(rolloverIcon);
        private static class RolloverImageFilter extends RGBImageFilter {
            RolloverImageFilter() {
                canFilterIndexColorModel = true;
            public int filterRGB(int x, int y, int rgb) {
                int r = ((rgb >> 16) & 0xff);
                int g = ((rgb >> 8) & 0xff);
                int b = (rgb & 0xff);
                int gray = Math.max(Math.max(r, g), b);
                return (rgb & 0xff000000) | (gray << 16) | (gray << 8) |
                    (gray << 0);
    }>
    The class that implements a tabbing page contains a
    boolean for beeing
    closeable and generates an ImageIcon showing some
    cross, there are
    getters and setters for the access of each.
    The class that contains the JTabbedPane stores those
    tabs also in a
    separate ArrayList. It contains methods to add and
    remove tabs using the
    following line in the case of closeable tabs:
         public void addTab( Tab06 tab){
    tabpan.addTab( tab.getTabName(),
    ), tab.getImageIcon(), tab.getTab());
    // ...To remove the closeable tab like this:
         public void removeCloseableTabAt( int idx){
              if( getTabAt( idx).isCloseable()){
                   removeTabAt(idx);
    // ...Ok, there's a MouseListener that should work like
    this:
              tabpan.addMouseListener(new MouseAdapter() {
                   public void mouseReleased(MouseEvent me) {
                        int index = tabpan.getSelectedIndex();                    
                        if(getTabAt(index).isCloseable()){
                             if(getTabAt(index).getImageIcon().contains(me.get
    X(), me.getY())){
                                  removeCloseableTabAt( index);
              });My problem now is, ImageIcon doesn't contain a
    "contains(y,x)" method.
    How can I realize checking if a click appeared within
    the Icon Rectangle, so that it should close in an
    elegant way? TIA

  • Clickable icons on JTabbedPane's tabs- java 1.5

    Hi all,
    i implement a button with java1.6 inside a tab (using setTabComponentAt() ).
    but i also should implement it with java1.5.
    i saw that the only method that giving me the option to change the tab its only for icons.
    is any one can give me some hint???
    TIA

    Hi all,
    i implement a button with java1.6 inside a tab (using setTabComponentAt() ).
    but i also should implement it with java1.5.
    i saw that the only method that giving me the option to change the tab its only for icons.
    is any one can give me some hint???
    TIA

  • Help with disabling close icon of last opened tab in JTabbedPane

    Hello
    Would someone help me out ? I have 3 tabs opened in a JTabbedPane, each with close icon "X". I am looking for a way to tell my program: if the user closes 2 tabs and only 1 remain, disable the close icon "X" of the last opened tab so that the user is unable to close the last tab. I have searched the forum, most I have run into are how to create the close icon. Would someone give me some insight into how to go about doing this? or if you have come across a forum that discusses this, do please post the link. Also, I am using java 1.6.
    Thanks very much in advance

    On each close, look how many tabs are remaining open in the JTabbedPane (getTabCount).
    If there is only one left, set its close button to invisible. Something like this:
    if (pane.getTabCount() == 1) {
        TabCloseButton tcb = (TabCloseButton) pane.getTabComponentAt(0);
        tcb.getBtClose().setVisible(false);
    }

  • JTabbedPane with close Icons

    Ok, so I was trying to get a JTabbedPane with 'X' icons on each tab. Searched this site, and found no answers, but loads of questions on how to do it. I've done it now, and here's my code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    * A JTabbedPane which has a close ('X') icon on each tab.
    * To add a tab, use the method addTab(String, Component)
    * To have an extra icon on each tab (e.g. like in JBuilder, showing the file type) use
    * the method addTab(String, Component, Icon). Only clicking the 'X' closes the tab.
    public class JTabbedPaneWithCloseIcons extends JTabbedPane implements MouseListener {
      public JTabbedPaneWithCloseIcons() {
        super();
        addMouseListener(this);
      public void addTab(String title, Component component) {
        this.addTab(title, component, null);
      public void addTab(String title, Component component, Icon extraIcon) {
        super.addTab(title, new CloseTabIcon(extraIcon), component);
      public void mouseClicked(MouseEvent e) {
        int tabNumber=getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) return;
        Rectangle rect=((CloseTabIcon)getIconAt(tabNumber)).getBounds();
        if (rect.contains(e.getX(), e.getY())) {
          //the tab is being closed
          this.removeTabAt(tabNumber);
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
    * The class which generates the 'X' icon for the tabs. The constructor
    * accepts an icon which is extra to the 'X' icon, so you can have tabs
    * like in JBuilder. This value is null if no extra icon is required.
    class CloseTabIcon implements Icon {
      private int x_pos;
      private int y_pos;
      private int width;
      private int height;
      private Icon fileIcon;
      public CloseTabIcon(Icon fileIcon) {
        this.fileIcon=fileIcon;
        width=16;
        height=16;
      public void paintIcon(Component c, Graphics g, int x, int y) {
        this.x_pos=x;
        this.y_pos=y;
        Color col=g.getColor();
        g.setColor(Color.black);
        int y_p=y+2;
        g.drawLine(x+1, y_p, x+12, y_p);
        g.drawLine(x+1, y_p+13, x+12, y_p+13);
        g.drawLine(x, y_p+1, x, y_p+12);
        g.drawLine(x+13, y_p+1, x+13, y_p+12);
        g.drawLine(x+3, y_p+3, x+10, y_p+10);
        g.drawLine(x+3, y_p+4, x+9, y_p+10);
        g.drawLine(x+4, y_p+3, x+10, y_p+9);
        g.drawLine(x+10, y_p+3, x+3, y_p+10);
        g.drawLine(x+10, y_p+4, x+4, y_p+10);
        g.drawLine(x+9, y_p+3, x+3, y_p+9);
        g.setColor(col);
        if (fileIcon != null) {
          fileIcon.paintIcon(c, g, x+width, y_p);
      public int getIconWidth() {
        return width + (fileIcon != null? fileIcon.getIconWidth() : 0);
      public int getIconHeight() {
        return height;
      public Rectangle getBounds() {
        return new Rectangle(x_pos, y_pos, width, height);
    }You can also specify an extra icon to put on each tab. Read my comments on how to do it.

    With the following code you'll be able to have use SCROLL_TAB_LAYOUT and WRAP_TAB_LAYOUT. With setCloseIcons() you'll be able to set images for the close-icons.
    The TabbedPane:
    import javax.swing.Icon;
    import javax.swing.JComponent;
    import javax.swing.JTabbedPane;
    import javax.swing.JViewport;
    import javax.swing.SwingUtilities;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import javax.swing.event.EventListenerList;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import javax.swing.plaf.metal.MetalTabbedPaneUI;
    * A JTabbedPane which has a close ('X') icon on each tab.
    * To add a tab, use the method addTab(String, Component)
    * To have an extra icon on each tab (e.g. like in JBuilder, showing the file
    * type) use the method addTab(String, Component, Icon). Only clicking the 'X'
    * closes the tab.
    public class CloseableTabbedPane extends JTabbedPane implements MouseListener,
      MouseMotionListener {
       * The <code>EventListenerList</code>.
      private EventListenerList listenerList = null;
       * The viewport of the scrolled tabs.
      private JViewport headerViewport = null;
       * The normal closeicon.
      private Icon normalCloseIcon = null;
       * The closeicon when the mouse is over.
      private Icon hooverCloseIcon = null;
       * The closeicon when the mouse is pressed.
      private Icon pressedCloseIcon = null;
       * Creates a new instance of <code>CloseableTabbedPane</code>
      public CloseableTabbedPane() {
        super();
        init(SwingUtilities.LEFT);
       * Creates a new instance of <code>CloseableTabbedPane</code>
       * @param horizontalTextPosition the horizontal position of the text (e.g.
       * SwingUtilities.TRAILING or SwingUtilities.LEFT)
      public CloseableTabbedPane(int horizontalTextPosition) {
        super();
        init(horizontalTextPosition);
       * Initializes the <code>CloseableTabbedPane</code>
       * @param horizontalTextPosition the horizontal position of the text (e.g.
       * SwingUtilities.TRAILING or SwingUtilities.LEFT)
      private void init(int horizontalTextPosition) {
        listenerList = new EventListenerList();
        addMouseListener(this);
        addMouseMotionListener(this);
        if (getUI() instanceof MetalTabbedPaneUI)
          setUI(new CloseableMetalTabbedPaneUI(horizontalTextPosition));
        else
          setUI(new CloseableTabbedPaneUI(horizontalTextPosition));
       * Allows setting own closeicons.
       * @param normal the normal closeicon
       * @param hoover the closeicon when the mouse is over
       * @param pressed the closeicon when the mouse is pressed
      public void setCloseIcons(Icon normal, Icon hoover, Icon pressed) {
        normalCloseIcon = normal;
        hooverCloseIcon = hoover;
        pressedCloseIcon = pressed;
       * Adds a <code>Component</code> represented by a title and no icon.
       * @param title the title to be displayed in this tab
       * @param component the component to be displayed when this tab is clicked
      public void addTab(String title, Component component) {
        addTab(title, component, null);
       * Adds a <code>Component</code> represented by a title and an icon.
       * @param title the title to be displayed in this tab
       * @param component the component to be displayed when this tab is clicked
       * @param extraIcon the icon to be displayed in this tab
      public void addTab(String title, Component component, Icon extraIcon) {
        boolean doPaintCloseIcon = true;
        try {
          Object prop = null;
          if ((prop = ((JComponent) component).
                        getClientProperty("isClosable")) != null) {
            doPaintCloseIcon = (Boolean) prop;
        } catch (Exception ignored) {/*Could probably be a ClassCastException*/}
        super.addTab(title,
                     doPaintCloseIcon ? new CloseTabIcon(extraIcon) : null,
                     component);
        if (headerViewport == null) {
          for (Component c : getComponents()) {
            if ("TabbedPane.scrollableViewport".equals(c.getName()))
              headerViewport = (JViewport) c;
       * Invoked when the mouse button has been clicked (pressed and released) on
       * a component.
       * @param e the <code>MouseEvent</code>
      public void mouseClicked(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when the mouse enters a component.
       * @param e the <code>MouseEvent</code>
      public void mouseEntered(MouseEvent e) { }
       * Invoked when the mouse exits a component.
       * @param e the <code>MouseEvent</code>
      public void mouseExited(MouseEvent e) {
        for (int i=0; i<getTabCount(); i++) {
          CloseTabIcon icon = (CloseTabIcon) getIconAt(i);
          if (icon != null)
            icon.mouseover = false;
        repaint();
       * Invoked when a mouse button has been pressed on a component.
       * @param e the <code>MouseEvent</code>
      public void mousePressed(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when a mouse button has been released on a component.
       * @param e the <code>MouseEvent</code>
      public void mouseReleased(MouseEvent e) { }
       * Invoked when a mouse button is pressed on a component and then dragged.
       * <code>MOUSE_DRAGGED</code> events will continue to be delivered to the
       * component where the drag originated until the mouse button is released
       * (regardless of whether the mouse position is within the bounds of the
       * component).<br/>
       * <br/>
       * Due to platform-dependent Drag&Drop implementations,
       * <code>MOUSE_DRAGGED</code> events may not be delivered during a native
       * Drag&Drop operation.
       * @param e the <code>MouseEvent</code>
      public void mouseDragged(MouseEvent e) {
        processMouseEvents(e);
       * Invoked when the mouse cursor has been moved onto a component but no
       * buttons have been pushed.
       * @param e the <code>MouseEvent</code>
      public void mouseMoved(MouseEvent e) {
        processMouseEvents(e);
       * Processes all caught <code>MouseEvent</code>s.
       * @param e the <code>MouseEvent</code>
      private void processMouseEvents(MouseEvent e) {
        int tabNumber = getUI().tabForCoordinate(this, e.getX(), e.getY());
        if (tabNumber < 0) return;
        CloseTabIcon icon = (CloseTabIcon) getIconAt(tabNumber);
        if (icon != null) {
          Rectangle rect= icon.getBounds();
          Point pos = headerViewport == null ?
                      new Point() : headerViewport.getViewPosition();
          Rectangle drawRect = new Rectangle(
            rect.x - pos.x, rect.y - pos.y, rect.width, rect.height);
          if (e.getID() == e.MOUSE_PRESSED) {
            icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
            repaint(drawRect);
          } else if (e.getID() == e.MOUSE_MOVED || e.getID() == e.MOUSE_DRAGGED ||
                     e.getID() == e.MOUSE_CLICKED) {
            pos.x += e.getX();
            pos.y += e.getY();
            if (rect.contains(pos)) {
              if (e.getID() == e.MOUSE_CLICKED) {
                int selIndex = getSelectedIndex();
                if (fireCloseTab(selIndex)) {
                  if (selIndex > 0) {
                    // to prevent uncatchable null-pointers
                    Rectangle rec = getUI().getTabBounds(this, selIndex - 1);
                    MouseEvent event = new MouseEvent((Component) e.getSource(),
                                                      e.getID() + 1,
                                                      System.currentTimeMillis(),
                                                      e.getModifiers(),
                                                      rec.x,
                                                      rec.y,
                                                      e.getClickCount(),
                                                      e.isPopupTrigger(),
                                                      e.getButton());
                    dispatchEvent(event);
                  //the tab is being closed
                  //removeTabAt(tabNumber);
                  remove(selIndex);
                } else {
                  icon.mouseover = false;
                  icon.mousepressed = false;
                  repaint(drawRect);
              } else {
                icon.mouseover = true;
                icon.mousepressed = e.getModifiers() == e.BUTTON1_MASK;
            } else {
              icon.mouseover = false;
            repaint(drawRect);
       * Adds an <code>CloseableTabbedPaneListener</code> to the tabbedpane.
       * @param l the <code>CloseableTabbedPaneListener</code> to be added
      public void addCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
        listenerList.add(CloseableTabbedPaneListener.class, l);
       * Removes an <code>CloseableTabbedPaneListener</code> from the tabbedpane.
       * @param l the listener to be removed
      public void removeCloseableTabbedPaneListener(CloseableTabbedPaneListener l) {
        listenerList.remove(CloseableTabbedPaneListener.class, l);
       * Returns an array of all the <code>SearchListener</code>s added to this
       * <code>SearchPane</code> with addSearchListener().
       * @return all of the <code>SearchListener</code>s added or an empty array if
       * no listeners have been added
      public CloseableTabbedPaneListener[] getCloseableTabbedPaneListener() {
        return listenerList.getListeners(CloseableTabbedPaneListener.class);
       * Notifies all listeners that have registered interest for notification on
       * this event type.
       * @param tabIndexToClose the index of the tab which should be closed
       * @return true if the tab can be closed, false otherwise
      protected boolean fireCloseTab(int tabIndexToClose) {
        boolean closeit = true;
        // Guaranteed to return a non-null array
        Object[] listeners = listenerList.getListenerList();
        for (Object i : listeners) {
          if (i instanceof CloseableTabbedPaneListener) {
            if (!((CloseableTabbedPaneListener) i).closeTab(tabIndexToClose)) {
              closeit = false;
              break;
        return closeit;
       * The class which generates the 'X' icon for the tabs. The constructor
       * accepts an icon which is extra to the 'X' icon, so you can have tabs
       * like in JBuilder. This value is null if no extra icon is required.
      class CloseTabIcon implements Icon {
         * the x position of the icon
        private int x_pos;
         * the y position of the icon
        private int y_pos;
         * the width the icon
        private int width;
         * the height the icon
        private int height;
         * the additional fileicon
        private Icon fileIcon;
         * true whether the mouse is over this icon, false otherwise
        private boolean mouseover = false;
         * true whether the mouse is pressed on this icon, false otherwise
        private boolean mousepressed = false;
         * Creates a new instance of <code>CloseTabIcon</code>
         * @param fileIcon the additional fileicon, if there is one set
        public CloseTabIcon(Icon fileIcon) {
          this.fileIcon = fileIcon;
          width  = 16;
          height = 16;
         * Draw the icon at the specified location. Icon implementations may use the
         * Component argument to get properties useful for painting, e.g. the
         * foreground or background color.
         * @param c the component which the icon belongs to
         * @param g the graphic object to draw on
         * @param x the upper left point of the icon in the x direction
         * @param y the upper left point of the icon in the y direction
        public void paintIcon(Component c, Graphics g, int x, int y) {
          boolean doPaintCloseIcon = true;
          try {
            // JComponent.putClientProperty("isClosable", new Boolean(false));
            JTabbedPane tabbedpane = (JTabbedPane) c;
            int tabNumber = tabbedpane.getUI().tabForCoordinate(tabbedpane, x, y);
            JComponent curPanel = (JComponent) tabbedpane.getComponentAt(tabNumber);
            Object prop = null;
            if ((prop = curPanel.getClientProperty("isClosable")) != null) {
              doPaintCloseIcon = (Boolean) prop;
          } catch (Exception ignored) {/*Could probably be a ClassCastException*/}
          if (doPaintCloseIcon) {
            x_pos = x;
            y_pos = y;
            int y_p = y + 1;
            if (normalCloseIcon != null && !mouseover) {
              normalCloseIcon.paintIcon(c, g, x, y_p);
            } else if (hooverCloseIcon != null && mouseover && !mousepressed) {
              hooverCloseIcon.paintIcon(c, g, x, y_p);
            } else if (pressedCloseIcon != null && mousepressed) {
              pressedCloseIcon.paintIcon(c, g, x, y_p);
            } else {
              y_p++;
              Color col = g.getColor();
              if (mousepressed && mouseover) {
                g.setColor(Color.WHITE);
                g.fillRect(x+1, y_p, 12, 13);
              g.setColor(Color.black);
              g.drawLine(x+1, y_p, x+12, y_p);
              g.drawLine(x+1, y_p+13, x+12, y_p+13);
              g.drawLine(x, y_p+1, x, y_p+12);
              g.drawLine(x+13, y_p+1, x+13, y_p+12);
              g.drawLine(x+3, y_p+3, x+10, y_p+10);
              if (mouseover)
                g.setColor(Color.GRAY);
              g.drawLine(x+3, y_p+4, x+9, y_p+10);
              g.drawLine(x+4, y_p+3, x+10, y_p+9);
              g.drawLine(x+10, y_p+3, x+3, y_p+10);
              g.drawLine(x+10, y_p+4, x+4, y_p+10);
              g.drawLine(x+9, y_p+3, x+3, y_p+9);
              g.setColor(col);
              if (fileIcon != null) {
                fileIcon.paintIcon(c, g, x+width, y_p);
         * Returns the icon's width.
         * @return an int specifying the fixed width of the icon.
        public int getIconWidth() {
          return width + (fileIcon != null ? fileIcon.getIconWidth() : 0);
         * Returns the icon's height.
         * @return an int specifying the fixed height of the icon.
        public int getIconHeight() {
          return height;
         * Gets the bounds of this icon in the form of a <code>Rectangle<code>
         * object. The bounds specify this icon's width, height, and location
         * relative to its parent.
         * @return a rectangle indicating this icon's bounds
        public Rectangle getBounds() {
          return new Rectangle(x_pos, y_pos, width, height);
       * A specific <code>BasicTabbedPaneUI</code>.
      class CloseableTabbedPaneUI extends BasicTabbedPaneUI {
        * the horizontal position of the text
        private int horizontalTextPosition = SwingUtilities.LEFT;
         * Creates a new instance of <code>CloseableTabbedPaneUI</code>
        public CloseableTabbedPaneUI() {
         * Creates a new instance of <code>CloseableTabbedPaneUI</code>
         * @param horizontalTextPosition the horizontal position of the text (e.g.
         * SwingUtilities.TRAILING or SwingUtilities.LEFT)
        public CloseableTabbedPaneUI(int horizontalTextPosition) {
          this.horizontalTextPosition = horizontalTextPosition;
         * Layouts the label
         * @param tabPlacement the placement of the tabs
         * @param metrics the font metrics
         * @param tabIndex the index of the tab
         * @param title the title of the tab
         * @param icon the icon of the tab
         * @param tabRect the tab boundaries
         * @param iconRect the icon boundaries
         * @param textRect the text boundaries
         * @param isSelected true whether the tab is selected, false otherwise
        protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                                   int tabIndex, String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected) {
          textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
          javax.swing.text.View v = getTextViewForTab(tabIndex);
          if (v != null) {
            tabPane.putClientProperty("html", v);
          SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                             metrics, title, icon,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             //SwingUtilities.TRAILING,
                                             horizontalTextPosition,
                                             tabRect,
                                             iconRect,
                                             textRect,
                                             textIconGap + 2);
          tabPane.putClientProperty("html", null);
          int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
          int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
          iconRect.x += xNudge;
          iconRect.y += yNudge;
          textRect.x += xNudge;
          textRect.y += yNudge;
       * A specific <code>MetalTabbedPaneUI</code>.
      class CloseableMetalTabbedPaneUI extends MetalTabbedPaneUI {
        * the horizontal position of the text
        private int horizontalTextPosition = SwingUtilities.LEFT;
         * Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
        public CloseableMetalTabbedPaneUI() {
         * Creates a new instance of <code>CloseableMetalTabbedPaneUI</code>
         * @param horizontalTextPosition the horizontal position of the text (e.g.
         * SwingUtilities.TRAILING or SwingUtilities.LEFT)
        public CloseableMetalTabbedPaneUI(int horizontalTextPosition) {
          this.horizontalTextPosition = horizontalTextPosition;
         * Layouts the label
         * @param tabPlacement the placement of the tabs
         * @param metrics the font metrics
         * @param tabIndex the index of the tab
         * @param title the title of the tab
         * @param icon the icon of the tab
         * @param tabRect the tab boundaries
         * @param iconRect the icon boundaries
         * @param textRect the text boundaries
         * @param isSelected true whether the tab is selected, false otherwise
        protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                                   int tabIndex, String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected) {
          textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
          javax.swing.text.View v = getTextViewForTab(tabIndex);
          if (v != null) {
            tabPane.putClientProperty("html", v);
          SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                             metrics, title, icon,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             SwingUtilities.CENTER,
                                             //SwingUtilities.TRAILING,
                                             horizontalTextPosition,
                                             tabRect,
                                             iconRect,
                                             textRect,
                                             textIconGap + 2);
          tabPane.putClientProperty("html", null);
          int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
          int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
          iconRect.x += xNudge;
          iconRect.y += yNudge;
          textRect.x += xNudge;
          textRect.y += yNudge;
    }The Listener:
    import java.util.EventListener;
    * The listener that's notified when an tab should be closed in the
    * <code>CloseableTabbedPane</code>.
    public interface CloseableTabbedPaneListener extends EventListener {
       * Informs all <code>CloseableTabbedPaneListener</code>s when a tab should be
       * closed
       * @param tabIndexToClose the index of the tab which should be closed
       * @return true if the tab can be closed, false otherwise
      boolean closeTab(int tabIndexToClose);
    }

  • Actionlistener (or equiv) on the tab's icon in a JTabbedPane

    Imagine for a moment the tab of a JTabbedPane, on it is a nice icon of an "X" in the left(ish) side. When the user clicks this "X" icon, the tab its on closes. If anyone knows how to make this work, and is willing to share the source/example how to do it, it would be much appreciated! Ive been coming back to it over and over for a month.

    Try this. Far from perfect, but a start. If you want to switch to SWT (eclipse) I've got a fully functional one you can have.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.util.*;
    public class Rrahl1
         static class Tab
              Component component;
              String name;
              TabButton button;
              public Tab(Component component, String name)
                   this.component= component;
                   this.name= name;
         static class TabButton
              extends JPanel
              public static int SELECT= 0;
              public static int CLOSE= 1;
              private static CompoundBorder sEtchedBorder= new CompoundBorder(
                   new EtchedBorder(EtchedBorder.LOWERED),
                   new EmptyBorder(0, 2, 0, 2));
              private static EmptyBorder sEmptyBorder= new EmptyBorder(2,4,2,4);
              private ImageIcon sImageClose= new ImageIcon("images/close.gif");
              private JLabel mLabel;
              private JLabel mCheck;
              private ActionListener mListener;
              private boolean mSelected= false;
              private boolean mMouseIn= false;
              private Dimension mPreferredSize;
              public TabButton(String title, ActionListener listener)
                   mListener= listener;
                   mCheck= new JLabel(sImageClose);
                   mCheck.setBorder(sEtchedBorder);
                   mLabel= new JLabel(title);
                   mLabel.setBorder(sEmptyBorder);
                   setLayout(new BorderLayout(0,2));
                   add(mLabel, BorderLayout.CENTER);
                   add(mCheck, BorderLayout.EAST);
                   setBorder(sEmptyBorder);
                   addMouseListener(new MouseAdapter() {
                        public void mousePressed(MouseEvent e) {
                             System.err.println(
                                  getComponentAt(e.getPoint().x, e.getPoint().y) == mCheck ? "Check" : "Label");
                             if (getComponentAt(e.getPoint().x, e.getPoint().y) == mCheck)
                                  mListener.actionPerformed(new ActionEvent(mCheck, CLOSE, null));
                             else
                                  mListener.actionPerformed(new ActionEvent(mCheck, SELECT, null));
                        public void mouseExited(MouseEvent e) {
                             mMouseIn= false;
                             if (!mSelected) {
                                  mLabel.setBorder(sEmptyBorder);
                                  mCheck.setVisible(false);
                        public void mouseEntered(MouseEvent e) {
                             mMouseIn= true;
                             if (!mSelected) {
                                  mLabel.setBorder(sEtchedBorder);
                                  mCheck.setVisible(true);
                   mPreferredSize= getPreferredSize();
                   mCheck.setVisible(false);
              public void setSelected(boolean selected)
                   mSelected= selected;
                   if (!mMouseIn) {
                        if (mSelected) {
                             mLabel.setBorder(sEtchedBorder);
                             mCheck.setVisible(true);
                        else {
                             mLabel.setBorder(sEmptyBorder);
                             mCheck.setVisible(false);
              public Dimension getPreferredSize() {
                   return mPreferredSize == null ? super.getPreferredSize() : mPreferredSize;
         static class TabPanel
              extends JPanel
              private ArrayList mTabs= new ArrayList();
              private Tab mCurrent= null;
              private JPanel mTabPanel= new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
              private JPanel mControlPanel= new JPanel();
              public TabPanel()
                   setLayout(new BorderLayout());
                   add(mTabPanel, BorderLayout.NORTH);
                   add(mControlPanel, BorderLayout.CENTER);
                   mControlPanel.setLayout(new OverlayLayout(mControlPanel));
              public void add(final Tab tab)
                   mTabs.add(tab);
                   TabButton button= new TabButton(tab.name, new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                             if (e.getID() == TabButton.SELECT)
                                  show(tab);
                             else
                                  close(tab);
                   mTabPanel.add(button);
                   mControlPanel.add(tab.component);
                   tab.button= button;
                   show(tab);
              private void show(Tab tab)
                   if (mCurrent == tab)
                        return;
                   if (mCurrent != null) {
                        mCurrent.component.setVisible(false);
                        mCurrent.button.setSelected(false);
                   tab.component.setVisible(true);
                   tab.button.setSelected(true);
                   mCurrent= tab;
              private void close(Tab tab)
                   mTabPanel.remove(tab.button);
                   mTabPanel.setVisible(false);
                   mTabPanel.setVisible(true);
                   mControlPanel.remove(tab.component);
                   int index= mTabs.indexOf(tab);
                   Tab removed= (Tab) mTabs.remove(index);
                   if (removed == mCurrent) {
                        if (index < mTabs.size())
                             show((Tab)mTabs.get(index));
                        else if (mTabs.size() > 0)
                             show((Tab)mTabs.get(index-1));
                   validate();
         static int newTab= 0;
         public static void main(String[] argv)
              JPanel blue= new JPanel();
              blue.setBackground(Color.BLUE);
              JPanel red= new JPanel();
              red.setBackground(Color.RED);
              JPanel green= new JPanel();
              green.setBackground(Color.GREEN);
              green.setPreferredSize(new Dimension(320,240));
              final TabPanel tabPanel= new TabPanel();
              tabPanel.add(new Tab(red, "Red"));
              tabPanel.add(new Tab(green, "Green"));
              tabPanel.add(new Tab(blue, "Blue"));
              JButton btn= new JButton("Add tab...");
              btn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        tabPanel.add(new Tab(
                             new JLabel(new java.util.Date().toString()),
                             "Tab " +(newTab++)));
              JFrame frame= new JFrame("Tab");
              frame.getContentPane().add(tabPanel, BorderLayout.CENTER);
              frame.getContentPane().add(btn, BorderLayout.SOUTH);
              frame.pack();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
    }

  • It is possible to put an icon&text on the table�s header of JTabbedPane?

    Hi
    It is possible to put an icon&text on the table�s header of JTabbedPane?
    Tx
    D

    its not what i'm looking for.
    maybe its a JTabbedPane at all. if yuo know the Emule interface,it seems like all the comnents Connect,Servers,Transffers,etc they all like a combination of a jTogglebuttn and a JTabbedpane.
    can it be a JToolBar and JToggle buttons in it,that has an event that changh the content of the JFrame?
    Tx
    D

  • Icon and a button in JTabbedPane Tabs

    Hi,
    i want to put an icon on the left side of the text and a button on the right side(Same as the eclipse tabs). Can any one help me how to do this.
    thnx in advance.

    Search the forum using "jtabbedpane close icon" for other discussions on this topic.

  • JTabbedPane and a Clsoe icon

    i know this has been asked before, but noone has ever answered completly
    i want to add a close button <an X basically> o nthe tab itself <a la Eclipse>, and while i can obviosly put an icon there, ther eis no way to add an action listener to the tab.
    i cna add an action listener to the tabpane, which will tell me that a tab was clicked on, and which one, but what i need really is a wya to see the x/y coordinates of where on the tab the click happened. This makes me think i need to overide the listener soewhere, but i am nto sure where.
    thanks

    You can get the location of the click by adding a MouseListener to the JTabbedPane. To map it to the tab, you'll have to use the TabbedPaneUI returned by getUI() - it has a method tabForCoordinate(JTabbedPane, int, int) which will tell you which tab was clicked, and a method getTabBounds(JTabbedPane, int) which will tell you the bounds of the tab, and allow you to work out where the click occurred within the tab. However, if you want to paint a cross on the tab as well, you'll have to write your own TabbedPaneUI with a custom paint method. You can install it with JTabbedPane.setUI.

  • JTabbedPane icon changes....sometimes

    Hi all,
    ive got the following problem: I've got a swing applet that allows users to perform queries on a database. Each of the queries has there own tab and label etc are populated with the results. when a user clicks on a tab and sets off a query a hour glass icon (to indicate the query is queued, they are executed in series) is put on the tab, when the query is executed running stick person is put in the tab, when the query result returns a tick icon is put in the tab. My problem is this, about 1/5 of the time this actually happens, most of the time the hour glass stays in the tab even though I know that the setIconAt method is called. Its randomness is baffling. Is there a known bug in the setIconAt function? any ideas on what to try?
    thanks,

    its in a seperate thread already If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
    The code in your "separate thread" would just be Thread.sleep(...) to simulate a long running task.

  • Animated GIF in JTabbedPane - repaint madness!

    Loading and animated GIF into the icon for a JTabbedPAne just works, but it causes the paintComponent method on the main part of the panel to be called repeatedly. Anyway to distinguish between the two areas? The icon repaints automatically but I don't want to have to repaint the rest of the panel unnecessarily.

    I've run into the same problem simon, the only way I came over this was to do my own animation for the gif. Bit of a bother really. Anyone have any other solutions?

  • How do I left justify the text in the tabs of a JTabbedPane.

    In 1.3.1 this used to work by supplying an HTML string with <div align="left"> but when I run with 1.4.1 this is now broken and I get center justification.
    Does anybody know a way to get the text in the tabs to be left justified.
    Thanks,
    Philip

    First, I found while using JTabbedPane that the "standard" behavior is to allow to a tab the exact space needed to display the tab text. Hence with this behavior, there is actualy no difference of "left" or "center" aligned text. So I assumed that you found a way or another to make your tabs wider than the "string width"...
    Here is a solution:
    You can override the TabbedPaneUI class and ajust the "layoutLabel()" method. Here is the code..
    //Your code using the tabbedPane
    JTabbedPane tp = new JTabbedPane();
    tp.setUI(new LeftTabbedPaneUI());
    //File containing the overrided TabbedPaneUI
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.text.View;
    class LeftTabbedPaneUI extends javax.swing.plaf.metal.MetalTabbedPaneUI {
            //I also overrided this function just to force tabs wider than
            //the displayed "String Width". I asume that you found another
            //way to do this so you can delete this function in your
            //implementation
         protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics){
              return 150;
        protected void layoutLabel(int tabPlacement,
                                   FontMetrics metrics, int tabIndex,
                                   String title, Icon icon,
                                   Rectangle tabRect, Rectangle iconRect,
                                   Rectangle textRect, boolean isSelected ) {
            textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
         View v = getTextViewForTab(tabIndex);
         if (v != null) {
             tabPane.putClientProperty("html", v);
         //This Line is added to avoid writing on tab border while aligned to left.
         //You can comment this line to test and or adjust the "5" pixel space
         Rectangle rec = new Rectangle(tabRect.x+5,tabRect.y,tabRect.width,tabRect.height);
            SwingUtilities.layoutCompoundLabel((JComponent) tabPane,
                                               metrics, title, icon,
                                               SwingUtilities.CENTER,
                                               SwingUtilities.LEFT,
                                               SwingUtilities.CENTER,
                                               SwingUtilities.TRAILING,
                                               rec,
                                               iconRect,
                                               textRect,
                                               textIconGap);
         tabPane.putClientProperty("html", null);
         int xNudge = getTabLabelShiftX(tabPlacement, tabIndex, isSelected);
         int yNudge = getTabLabelShiftY(tabPlacement, tabIndex, isSelected);
         iconRect.x += xNudge;
         iconRect.y += yNudge;
         textRect.x += xNudge;
         textRect.y += yNudge;
    }Here I overrided the "Metal" implementation of the tab but you must override the implementation of the used Look And Feel,
    ex. "com.sun.java.swing.plaf.window.WindowsTabbedPaneUI" for the windows LAF.

  • JTabbedPane: Components before and after the tabs themselves.

    I want to make Google Chrome..!
    Well, really, I want to have GUI stuff up in the title pane. In particular, I want the tabs of a TabbedPane up there.
    I've concluded that the easiest way to accomplish this (hopefully in a somewhat LaF-neutral way) is to set the frame to be undecorated, and instead implement my own frame with handling and all. I'd set a JFrame undecorated, and put a JTabbedPane over the entire thing, sticking the application icon to the left of the tabs, and the minimize, maximize, close buttons to the far right of the tabs themselves.
    If anyone have any other suggestions to this initial problem, I would seriously appreciate to hear about them.
    But given the above solution: How would I go about getting a component to the left of the tabs, and some other components to the right of the tabs, of a JTabbedPane? A LaF-neutral solution would be very much appreciated - but I have faint hopes here, so pointers for how to accomplish this using LaF-tricks will be appreciated too.
    I've seen that laf-widget from kirill, https://laf-widget.dev.java.net/, does something like it (the magnifying-glass icon to the left of the tabs) for several LaFs. However, I must admit that I'm not yet well enough versed to understand how he does it - and also it seems like a somewhat complicated process, whereby one "physically" change the LaF in question (bytecode manipulates it), injecting the laf-widget stuff (and I still don't know how the JTabbedPane or TabbedPaneUI is modulated to inject that icon).
    Any help or pointers will be much appreciated!
    Thanks,
    Endre.

    Could you elaborate slightly on that? I don't get your "what's left" idea..?
    I think the JTabbedPane should have this functionality built-in. It is a truly obvious need, to the extent that it has had to be solved several times by others.
    From an answer to this problem on StackOverflow: The JideTabbedPane from the Jide open source parts have an setTabLeadingComponent. However, Jide doesn't manage to follow the active LaF (the installs its own UI delegate), so I don't instantly want to jump on it.

Maybe you are looking for