MouseListener in JTabbedPane jdk1.4

Hi guys,
I am trying to use JTabbedPane with jkd1.4. my problem is I am not able to detect mouse click if i use new feature of JTabbedPane.SCROLL_TAB_LAYOUT. because I thinkg it is already used for up and arrow. If i comment out that line form the following code mouse click works fine. Any way to have both the feature on .i.e. mouseclick detection and scrollable tabs.
Thanks for help.
import javax.swing.table.*;
import javax.swing.event.*;
import javax.swing.border.*;
import javax.swing.text.*;
public class TabbedPaneDemo extends JPanel implements MouseListener {
public TabbedPaneDemo() {
ImageIcon icon = new ImageIcon("images/middle.gif");
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
tabbedPane.setTabPlacement(SwingConstants.LEFT);
for(int i =0;i< 50;i++){
tabbedPane.addTab( "panel " + i, icon, makeTextPanel("Blah blah blah " + i), "Still does nothing");
// System.out.println(i);
     tabbedPane.addMouseListener(this);
//Add the tabbed pane to this panel.
setLayout(new GridLayout(1, 1));
add(tabbedPane);
public void mouseClicked(MouseEvent e){
     System.out.println("HI I AM IN MOUSE EVENT");
public void mouseEntered(MouseEvent e){};
public void mouseExited(MouseEvent e){};
public void mousePressed(MouseEvent e){};
public void mouseReleased(MouseEvent e){};
protected Component makeTextPanel(String text) {
JPanel panel = new JPanel(false);
JLabel filler = new JLabel(text);
filler.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(filler);
return panel;
public static void main(String[] args) {
JFrame frame = new JFrame("TabbedPaneDemo");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}
frame.getContentPane().add(new TabbedPaneDemo(),
BorderLayout.CENTER);
frame.setSize(800, 400);
frame.setVisible(true);

This is a known bug which is not going to be fixed until the 1.5 release:
http://developer.java.sun.com/developer/bugParade/bugs/4465870.html

Similar Messages

  • JTabbedPane MouseListener on tabs

    I want to add a MouseListener to a JTabbedPane, but not on the content JPanel, but on the right of the tabs.
    (see this image: http://yfrog.com/aijtabbedpaneg , the arrows mark where I want the mouse to be clicked when the listener acts)
    How can I do this?
    A simple tabbedpane.addMouseListener doesn't work and I can't find the tabs component where I can add the listener.

    Here's my attempt.
    import java.awt.Dimension;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTabbedPane;
    import javax.swing.SwingUtilities;
    public class TabbedPaneTest {
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    JFrame frame = new JFrame("Test");
                    frame.setBounds(20, 20, 300, 300);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    JTabbedPane tabs = new JTabbedPane();
                    Dimension size = new Dimension(100, 200);
                    JLabel label = new JLabel("Label 1");
                    JLabel otherLabel = new JLabel("Label 2");
                    label.setPreferredSize(size);
                    otherLabel.setPreferredSize(size);
                    tabs.add("Tab 1", label);
                    tabs.add("Tab 2", otherLabel);
                    tabs.addMouseListener(new MouseAdapter() {
                        @Override
                        public void mouseClicked(MouseEvent e) {
                            JTabbedPane tabs = (JTabbedPane)e.getSource();
                            //Check that click was on tabbed pane itself an that there is no tab at that location.
                            System.out.println(tabs.findComponentAt(e.getX(), e.getY()) == tabs && tabs.indexAtLocation(e.getX(), e.getY()) == -1 ? "No tab at location." : "Tab at location.");
                    frame.add(tabs);
                    frame.setVisible(true);
    }

  • JTabbedPane questions

    Hi Everyone,
    I understand the JTabbedPane in Swing is rather basic, but I have the need to add some more extended functionality:
    1) Flash a given tab
    2) Add a clickable button to a tab (maybe in addition to an icon)
    3) Not display the tabs if there is only one item in the tabbed pane
    4) Popup menu on a per-tab basis
    5) Add button(s) in the "trough" of the tab (the area in the tabbed pane, outside of the tab but not in the content pane)
    6) ... ? Maybe others
    What is the best way to achieve these kinds of things? Are there any JTabbedPane extensions out there? If not, how would I do it myself?

    If not, how would I do it myself? Search the forums for examples and modify the suggestions.
    1) Flash a given tab
    Use a timer to change the background color of a selected tab.
    2) Add a clickable button to a tab (maybe in addition to an icon)
    I'm not sure if I've seen any solutions with buttons, but I have seen solutions with clickable icons to close a tab. I think the search keywords where "jtabbedpane close icon"
    3) Not display the tabs if there is only one item in the tabbed pane
    Simple programming problem. Use the removeTab method
    4) Popup menu on a per-tab basis
    Add a MouseListener to the tabbed pane:
    http://forum.java.sun.com/thread.jspa?threadID=615004&tstart=75
    5) Add button(s) in the "trough" of the tab (outside of the tab but not in the content pane)
    I'm sure there's a better way, but here is one way to get you started:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    public class TabbedPaneWithText extends JFrame
         public TabbedPaneWithText()
              JTabbedPane tabbedPane = new JTabbedPane()
                   public void paintComponent(Graphics g)
                        super.paintComponent(g);
                        Rectangle lastTab = getUI().getTabBounds(this, getTabCount() - 1);
                        int tabEnd = lastTab.x + lastTab.width;
                        String text = "Some Text";
                        FontMetrics fm = getFontMetrics( getFont() );
                        int stringWidth = fm.stringWidth( text ) + 10;
                        int x = getSize().width - stringWidth;
                        if (x < tabEnd)
                             x = tabEnd;
                        g.drawString(text, x + 5, 18);
              tabbedPane.add("1", new JTextField("one"));
              tabbedPane.add("2", new JTextField("two"));
              getContentPane().add(tabbedPane);
         public static void main(String args[])
            TabbedPaneWithText frame = new TabbedPaneWithText();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setLocationRelativeTo( null );
            frame.setVisible(true);
    }

  • JDialog jdk1.5 vs jdk1.6

    Hi,
    I'm having a different behaviour when I'm executing the following code on jdk1.5 and 1.6 :
    import java.awt.BorderLayout;
    import java.awt.Color;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JPasswordField;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    class test extends JFrame {
         private JTabbedPane tabbedPane;
         private JPanel panel1;
         private JPanel panel2;
         private JPanel panel3;
         // Main method to get things started
         public static void main(String args[]) {
              // Create an instance of the test application
              test mainFrame = new test();
              mainFrame.setVisible(true);
         public test() {
              // NOTE: to reduce the amount of code in this example, it uses
              // panels with a NULL layout. This is NOT suitable for
              // production code since it may not display correctly for
              // a look-and-feel.
              setTitle("Tabbed Pane Application");
              setSize(300, 200);
              setBackground(Color.gray);
              JPanel topPanel = new JPanel();
              topPanel.setLayout(new BorderLayout());
              getContentPane().add(topPanel);
              // Create the tab pages
              createPage1();
              createPage2();
              // Create a tabbed pane
              tabbedPane = new JTabbedPane();
              tabbedPane.addTab("Page 1", panel1);
              tabbedPane.addTab("Page 2", panel2);
              topPanel.add(tabbedPane, BorderLayout.CENTER);
              tabbedPane.addChangeListener(new ChangeListener() {
                   // This method is called whenever the selected tab changes
                   public void stateChanged(ChangeEvent evt) {
                        JTabbedPane pane = (JTabbedPane) evt.getSource();
                        // Get current tab
                        int sel = pane.getSelectedIndex();
                        if (sel == 1) {
                             JDialog dial = new JDialog();
                             dial.setModal(true);
                             dial.setVisible(true);
         public void createPage1() {
              panel1 = new JPanel();
              panel1.setLayout(null);
              JLabel label1 = new JLabel("Username:");
              label1.setBounds(10, 15, 150, 20);
              panel1.add(label1);
              JTextField field = new JTextField();
              field.setBounds(10, 35, 150, 20);
              panel1.add(field);
              JLabel label2 = new JLabel("Password:");
              label2.setBounds(10, 60, 150, 20);
              panel1.add(label2);
              JPasswordField fieldPass = new JPasswordField();
              fieldPass.setBounds(10, 80, 150, 20);
              panel1.add(fieldPass);
         public void createPage2() {
              panel2 = new JPanel();
              panel2.setLayout(new BorderLayout());
              panel2.add(new JButton("North"), BorderLayout.NORTH);
              panel2.add(new JButton("South"), BorderLayout.SOUTH);
              panel2.add(new JButton("East"), BorderLayout.EAST);
              panel2.add(new JButton("West"), BorderLayout.WEST);
              panel2.add(new JButton("Center"), BorderLayout.CENTER);
    }On jdk1.5 when I press the 2nd tab, the popup is displayed but the tab 2 is only displayed when I close the popup.
    On jdk1.6 when I press the 2nd tab, the popup is displayed and tab 2 is also displayed even when I don't close the popup.
    Does anyone had this kind of problem ?
    I would expect to have the same behaviour on 1.5 and 1.6..
    Is there any workaround to display the 2nd tab only when popup is close on jdk 1.6 ?
    Regards
    Tiago

    It can easily be solved by inelegant kludge.
    class test extends JFrame
      private JTabbedPane tabbedPane;
      private JPanel panel1;
      private JPanel panel2;
      private JPanel panel3;
      private boolean dlgShown = false; // *** class variable
        tabbedPane.addChangeListener(new ChangeListener()
          public void stateChanged(ChangeEvent evt)
            JTabbedPane pane = (JTabbedPane) evt.getSource();
            int sel = pane.getSelectedIndex();
            if (sel == 1)
              if (!dlgShown) // ***
                pane.setSelectedIndex(0); // ***
                JDialog dial = new JDialog();
                dial.setModal(true);
                dial.setPreferredSize(new Dimension(200, 100));
                dial.pack();
                dial.setLocationRelativeTo(null);
                dial.setVisible(true);
                dlgShown = !dlgShown; // ***
                pane.setSelectedIndex(1); // ***
              else
                dlgShown = !dlgShown;
    }note: more elegant solutions most welcome!

  • Bug: JTabbedPane setTabLayoutPolicy in 1.4

    I noticed weird behavior when using setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT). When adding a MouseListener to a JTabbedPane with this property set (it's a recent addition since 1.4), mouseClicked, mouseReleased, and mousePressed events do not occur. These events don't occur when clicked on the tab name (it works in other various areas though), but this is not standard behavior. When adding a MouseListener to a JTabbedPane, these events should occur no matter where you clicked on the JTabbedPane. Expected results are received with the default value, setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT). Here's someone else (the only other person I know) who experienced this problem:
    http://forum.java.sun.com/thread.jsp?forum=57&thread=185937
    Try running his code (my code is too long to show, it's part of a big project) and let me know if this bug exists for whatever operating system you use. Could anyone let me know if there's a workaround for this problem? I filed this bug and I hope Sun will fix it soon :) Thanks.

    I dunno whether its a bug or not but in my old application Tab key stopped working when run on JRE1.4.1!
    And if I had Java Console open Tab worked fine (earlier we were using JRE1.3 plugin, now I tried the application on JRE1.4.1 ).
    Only after setting the myApplet.FocusCycleRoot(true) did it started working again.
    Cheers,
    Amit

  • JTabbedPane with one close button for all tabs

    Hello,
    there have several solutions been posted for JTabbedPane subclasses that provide tabs with icons working as close buttons on each tab. I think this is not user friendly because the user can hit the close button accidentally when selecting a tab. And a "really close?" dialog is clumsy.
    Therefore I prefer the Netscape browser style: There's only one close button rightmost of the tabs that closes the selected tab. But I don't have an idea how to achieve this.
    Does anyone have a solution or an idea? Thanks in advance for help.

    This solution has been posted several times and is not what I wanted. But I rewrote the thing so that
    - the close buttons are on the right hand side of each tab so that it is conformant with Eclipse style, and
    - the close buttons work only with a left click (see code below).
    I just wonder how I can move the text a little bit to the left so that the appearence is a bit more balanced. Can someone help, please?
    import java.awt.Color;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    class TabbedPaneCloseButtonUI extends BasicTabbedPaneUI {
        public TabbedPaneCloseButtonUI() {
            super();
        protected void paintTab(
            Graphics g,
            int tabPlacement,
            Rectangle[] rects,
            int tabIndex,
            Rectangle iconRect,
            Rectangle textRect) {
            super.paintTab(g, tabPlacement, rects, tabIndex, iconRect, textRect);
            Rectangle rect = rects[tabIndex];
            g.setColor(Color.black);
            g.drawRect(rect.x + rect.width -19, rect.y + 4, 13, 12);
            g.drawLine(
                rect.x + rect.width -16,
                rect.y + 7,
                rect.x + rect.width -10,
                rect.y + 13);
            g.drawLine(
                rect.x + rect.width -10,
                rect.y + 7,
                rect.x + rect.width -16,
                rect.y + 13);
            g.drawLine(
                rect.x + rect.width -15,
                rect.y + 7,
                rect.x + rect.width -9,
                rect.y + 13);
            g.drawLine(
                rect.x + rect.width -9,
                rect.y + 7,
                rect.x + rect.width -15,
                rect.y + 13);
        protected int calculateTabWidth(
            int tabPlacement,
            int tabIndex,
            FontMetrics metrics) {
            return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + 24;
        protected MouseListener createMouseListener() {
            return new MyMouseHandler();
        class MyMouseHandler extends MouseHandler {
            public MyMouseHandler() {
                super();
            public void mouseReleased(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                int tabIndex = -1;
                int tabCount = tabPane.getTabCount();
                for (int i = 0; i < tabCount; i++) {
                    if (rects.contains(x, y)) {
    tabIndex = i;
    break;
         if (tabIndex >= 0 && ! e.isPopupTrigger()) {
    Rectangle tabRect = rects[tabIndex];
    y = y - tabRect.y;
    if ((x >= tabRect.x + tabRect.width - 18)
    && (x <= tabRect.x + tabRect.width - 8)
    && (y >= 5)
    && (y <= 15)) {
    tabPane.remove(tabIndex);
    import java.awt.BorderLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTabbedPane;
    public class TabbedPaneWithCloseButtons {
    JFrame frame;
    JTabbedPane tabPane;
    public TabbedPaneWithCloseButtons() throws Exception {
    frame=new JFrame();
    frame.getContentPane().setLayout(new BorderLayout());
    tabPane=new JTabbedPane();
    tabPane.addTab("test1xxxxxxxxxxxxxx", new JLabel("1"));
    tabPane.addTab("test2xxxxxxxxxxxxxxxxxxx", new ImageIcon("images/icon.gif"), new JLabel("2"));
    tabPane.addTab("test3xxxxxxxx", new JLabel("3"));
    tabPane.setUI(new TabbedPaneCloseButtonUI());
    frame.getContentPane().add(tabPane);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200,200);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    public static void main(String[] args) throws Exception {
    TabbedPaneWithCloseButtons test=new TabbedPaneWithCloseButtons();

  • 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);
    }

  • Help with JTabbedPane..

    I've read the tutorials lots, but to no avail, I need help with make it so when you click a tab it actually changes, here take a look at this private static void createTabbedPane() {
         tabBox = new JTabbedPane();
         tabBox.addTab("User Stuff", userPanel);
         tabBox.addTab("Initialization", passPanel);
    }Do i need a Listener to change tabs with a click of the mouse?

    you don't need a mouselistener...
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    public class MyTabbedPane extends JFrame {
         private static JTabbedPane tabBox;
         private static JPanel userPanel;
         private static JPanel passPanel;
         public MyTabbedPane() {
              createUserPanel();
              createPassPanel();
              createTabbedPane();
              add(tabBox);
         private static void createUserPanel() {
              userPanel = new JPanel();
    //              just for demonstrating i add a label here
              JLabel label = new JLabel("userPanel");
              userPanel.add(label);
         private static void createPassPanel() {
              passPanel = new JPanel();
    //          just for demonstrating i add a label here
              JLabel label = new JLabel("passLabel");
              passPanel.add(label);
         private static void createTabbedPane() {
              tabBox = new JTabbedPane();
              tabBox.addTab("User Stuff", userPanel);
              tabBox.addTab("Initialization", passPanel);
          * Create the GUI and show it.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame();
              frame = new MyTabbedPane();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setTitle("MyTabbedPane");
              frame.setPreferredSize(new Dimension(300, 300));
              // Display the window.
              frame.pack();
              frame.setVisible(true);
         public static void main(String[] args) {
              // Schedule a job for the event-dispatching thread:
              // creating and showing this application's GUI.
              javax.swing.SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        createAndShowGUI();
    }

  • Mousewheel -- How to get Event in a mouseListener.

    Hi, i'm trying to scroll a table in a JScrollpane (with JViewport) by using the Mousewheel like you are used to in the windows enviroment.
    My problem is that the Button_Mask2 is only triggered when you press the mouseWheel
    like a Button.
    So which modifiers must i check to get the correct Event for the Mousewheel.
    Thanks in advance.
    Michael
    PS.: Please excuse my bad english.

    Hi, thanks. But I'm using jdk1.3 at the moment.
    Is here any possibilty in jdk1.3.x, or do i have to
    move to jdk 1.4 which is still Beta yet.I'm affraid not. In jdk1.3 you can catch only mouse pressed, released, clicked, entered and exited events with the MouseListener interface, and mouse dragged and mouse moved events with the MouseMotionListener interface. If you can I suggest to use jdk 1.4. It has lots of new features.

  • JTabbedPane gives ArrayIndexOutof Bounds Exception

    I have a project where I am using a JTabbedPane that has 5 tabs.
    Every now and then I receive the following error. The error is not consistent and generally occurs at start up. I am using JBuilder5 (jdk1.3) on a Windows 2000 machine.
    Any help will be appreciated.
    Thanks
    V Shah
    Exception occurred during event dispatching:
    java.lang.ArrayIndexOutOfBoundsException
         at javax.swing.plaf.basic.BasicTabbedPaneUI.paint(BasicTabbedPaneUI.java:343)
         at javax.swing.plaf.metal.MetalTabbedPaneUI.paint(MetalTabbedPaneUI.java:664)
         at javax.swing.plaf.metal.MetalTabbedPaneUI.update(MetalTabbedPaneUI.java:559)
         at javax.swing.JComponent.paintComponent(JComponent.java:398)
         at javax.swing.JComponent.paint(JComponent.java:739)
         at javax.swing.JComponent.paintChildren(JComponent.java:523)
         at javax.swing.JComponent.paint(JComponent.java:748)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:4393)
         at javax.swing.JComponent._paintImmediately(JComponent.java:4336)
         at javax.swing.JComponent.paintImmediately(JComponent.java:4187)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:205)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:334)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:134)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:101)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:96)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:88)

    Looks to me as if you are looping too far when you add tabs to your TabbedPane...check your logic. Your stack trace is worthless without posting code.

  • Closable Tab in JTabbedPane

    Hi
    I trying to develop a Closable Tab in JTabbedPane. The close button should appear after/before the tab title all the time (like in JBuilder IDE).
    I know the trick where close button appears when the mouse is in that area, but i want it to be displayed all the time irrespective of the mouse position.
    How i should be able to create this component??
    I am very new to swing please help...
    Thanks for your help...
    -Vinod

    Thanks Stas,
    Your code was really helpfull.
    I've improved it a litte bit. So I'd like to share It.
    To use it, just create a ClosableTabbedPane.
    If you need to change the default action (remove the tab) then use the method setCloseTabAction(CloseTabAction) to change the action.
    Cheers,
    Rafa
    ================================
    The TabbedPaneUI
    ================================
    import java.awt.Color;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Rectangle;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    public class ClosableTabbedPaneUI extends BasicTabbedPaneUI
         public final static int BUTTON_SIZE = 12;
         public final static int BORDER_SIZE = 3;
         public ClosableTabbedPaneUI()
              super();
         protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex, Rectangle iconRect, Rectangle textRect)
              super.paintTab(g,tabPlacement,rects,tabIndex,iconRect,textRect);
              Rectangle rect=rects[tabIndex];
              int yPosition = (rect.height-BUTTON_SIZE)/2;
              int xPosition = rect.x+rect.width-Math.round(BUTTON_SIZE*1.5f);
              g.setColor(Color.BLACK);
              g.drawRect(xPosition,yPosition,BUTTON_SIZE,BUTTON_SIZE);
              g.setColor(Color.black);
              g.drawLine(xPosition+BORDER_SIZE,yPosition+BORDER_SIZE,xPosition+BUTTON_SIZE-BORDER_SIZE,yPosition-BORDER_SIZE+BUTTON_SIZE);
              g.drawLine(xPosition+BORDER_SIZE,yPosition-BORDER_SIZE+BUTTON_SIZE,xPosition+BUTTON_SIZE-BORDER_SIZE,yPosition+BORDER_SIZE);
         protected int getTabLabelShiftX(int tabPlacement, int tabIndex, boolean isSelected)
              return super.getTabLabelShiftX(tabPlacement, tabIndex, isSelected)-BUTTON_SIZE;     
         protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics)
              return super.calculateTabWidth(tabPlacement,tabIndex,metrics)+BUTTON_SIZE;
         protected MouseListener createMouseListener()
              return new MyMouseHandler();
         class MyMouseHandler extends MouseHandler
              public MyMouseHandler()
                   super();
              public void mouseClicked(MouseEvent e)
                   int x=e.getX();
                   int y=e.getY();
                   int tabIndex=-1;
                   int tabCount = tabPane.getTabCount();
                   for (int i = 0; i < tabCount; i++)
                        if (rects[ i ].contains(x, y))
                             tabIndex= i;
                             break;
                   if (tabIndex >= 0)
                        Rectangle rect = rects[tabIndex];
                        int yPosition = (rect.height-BUTTON_SIZE)/2;
                        int xPosition = rect.x+rect.width-Math.round(BUTTON_SIZE*1.5f);
                        if( new Rectangle(xPosition,yPosition,BUTTON_SIZE,BUTTON_SIZE).contains(x,y))
                             if( tabPane instanceof ClosableTabbedPane )
                                  ClosableTabbedPane closableTabbedPane = (ClosableTabbedPane)tabPane;
                                  CloseTabAction closeTabAction = closableTabbedPane.getCloseTabAction();
                                  if(closeTabAction != null)
                                       closeTabAction.act(closableTabbedPane, tabIndex);
                             else
                                  // If somebody use this class as UI like setUI(new ClosableTabbedPaneUI())
                                  tabPane.removeTabAt(tabIndex);
    ======================================
    The Closable TabbedPane
    ======================================
    public class ClosableTabbedPane extends JTabbedPane
         private CloseTabAction closeTabAction = null;
         public ClosableTabbedPane()
              super();
              init();
         public ClosableTabbedPane(int arg0)
              super(arg0);
              init();
         public ClosableTabbedPane(int arg0, int arg1)
              super(arg0, arg1);
              init();
         private void init()
              setUI(new ClosableTabbedPaneUI());
              closeTabAction = new CloseTabAction()
                   public void act(ClosableTabbedPane closableTabbedPane, int tabIndex)
                        closableTabbedPane.removeTabAt(tabIndex);
         public CloseTabAction getCloseTabAction()
              return closeTabAction;
         public void setCloseTabAction(CloseTabAction action)
              closeTabAction = action;
    =========================
    The Action
    =========================
    public interface CloseTabAction
         public void act(ClosableTabbedPane closableTabbedPane, int tabIndex);

  • How to save JTabbedPane to file so it can be restored later

    I am trying to build a program that will allow the user to add/remove tabs and buttons in a JTabbedPane and then save this to a file so that it can be restored later. However when I try to restore it from the file I cannot get it to update the panel.
    public class LightCommander extends JFrame
         private Container windowContent;
         private JPanel mainPanel;
         // menubar items and actionlistener
         private JMenuBar mainMenu;
         private JMenu f,v,c,c1,h;
         private ButtonGroup view_group;
         private MenuHandler mlistener;
         private static JMenuItem f1,f2,f3,c11,c12,c2,c3,c4,c5,h1,h2,h3;
         private JRadioButtonMenuItem v1;
         // mainWindow items
         private JScrollPane scrollWindow;
         private TabbedView mainWindow;
         // infoBar items and mouselistener
         private JPanel infoBar;
         private JLabel info;
         private InfoHandler ilistener;
         // program variables
         private Color defaultColor;
         private File setupFile;
         private FileInputStream fis;
         private FileOutputStream fos;
         private ObjectInputStream ois;
         private ObjectOutputStream oos;
         public LightCommander()
              super("LightCommander2 - \"The Light Project\"");
              windowContent = getContentPane();
              setupFile = null;
              defaultColor = this.getBackground();
              // create the mainPanel of the program which will
              // contain all the programs gui elements
              mainPanel = new JPanel(new BorderLayout());
              mainPanel.setPreferredSize(new Dimension(800,600));
              mainPanel.setMaximumSize(new Dimension(1400,1050));
                   // create the menuBar and it's menus
                   mainMenu = new JMenuBar();
                   // create the file menu
                   f  = new JMenu("File");
                   f.setMnemonic(KeyEvent.VK_F);
                   f1 = new JMenuItem("New");
                   f1.setMnemonic(KeyEvent.VK_N);
                   f1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + n) for power users
                   f2 = new JMenuItem("Open");
                   f2.setMnemonic(KeyEvent.VK_O);
                   f2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + o) for power users
                   f3 = new JMenuItem("Exit");
                   f3.setMnemonic(KeyEvent.VK_X);
                   f3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + x) for power users
                   f.add(f1);
                   f.add(f2);
                   f.addSeparator();
                   f.add(f3);
                   // create the view menu
                   v  = new JMenu("View");
                   v.setMnemonic(KeyEvent.VK_V);
                   v1 = new JRadioButtonMenuItem("Tabs");
                   view_group = new ButtonGroup();
                   view_group.add(v1);
                   v1.setSelected(true);
                   v.add(v1);
                   // create the command menu
                   c   = new JMenu("Command");
                   c.setMnemonic(KeyEvent.VK_C);
                   c1  = new JMenu("Add");
                   c1.setMnemonic(KeyEvent.VK_A);
                   c11 = new JMenuItem("Light");
                   c11.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + 1) for power users
                   c12 = new JMenuItem("Switch");
                   c12.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + 2) for power users
                   c1.add(c11);
                   c1.add(c12);
                   c2  = new JMenuItem("Remove");
                   c2.setMnemonic(KeyEvent.VK_R);
                   c2.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_3, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + 3) for power users
                   c3  = new JMenuItem("Reset");
                   c3.setMnemonic(KeyEvent.VK_E);
                   c3.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_4, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + 4) for power users
                   c4  = new JMenuItem("All On");
                   c4.setMnemonic(KeyEvent.VK_N);
                   c4.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_5, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + 5) for power users
                   c5  = new JMenuItem("All Off");
                   c5.setMnemonic(KeyEvent.VK_F);
                   c5.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_6, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + 6) for power users
                   c.add(c1);
                   c.add(c2);
                   c.add(c3);
                   c.addSeparator();
                   c.add(c4);
                   c.add(c5);
                   // create the help menu
                   h  = new JMenu("Help");
                   h.setMnemonic(KeyEvent.VK_H);
                   h1 = new JMenuItem("Help Topics");
                   h1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F1, ActionEvent.CTRL_MASK));     // set shortcut = (Ctrl + F1) for power users
                   h2 = new JMenuItem("Technical Support");
                   h3 = new JMenuItem("About LightCommander2...");
                   h.add(h1);
                   h.add(h2);
                   h.addSeparator();
                   h.add(h3);
                   // add actionlistener and infolistener to the menuitems
                   mlistener = new MenuHandler();
                   ilistener = new InfoHandler();
                   f.addMouseListener(ilistener);
                   f1.addActionListener(mlistener);
                   f1.addMouseListener(ilistener);
                   f2.addActionListener(mlistener);
                   f2.addMouseListener(ilistener);
                   f3.addActionListener(mlistener);
                   f3.addMouseListener(ilistener);
                   v.addMouseListener(ilistener);
                   v1.addActionListener(mlistener);
                   v1.addMouseListener(ilistener);
                   c.addMouseListener(ilistener);
                   c11.addActionListener(mlistener);
                   c11.addMouseListener(ilistener);
                   c12.addActionListener(mlistener);
                   c12.addMouseListener(ilistener);
                   c2.addActionListener(mlistener);
                   c2.addMouseListener(ilistener);
                   c3.addActionListener(mlistener);
                   c3.addMouseListener(ilistener);
                   c4.addActionListener(mlistener);
                   c4.addMouseListener(ilistener);
                   c5.addActionListener(mlistener);
                   c5.addMouseListener(ilistener);
                   h.addMouseListener(ilistener);
                   h1.addActionListener(mlistener);
                   h1.addMouseListener(ilistener);
                   h2.addActionListener(mlistener);
                   h2.addMouseListener(ilistener);
                   h3.addActionListener(mlistener);
                   h3.addMouseListener(ilistener);
                   // disable menu items with no functionality as of yet
    //               f1.setEnabled(false);
    //               f2.setEnabled(false);
    //               v1.setEnabled(false);
                   c1.setEnabled(false);
                   c11.setEnabled(false);
                   c12.setEnabled(false);
                   c2.setEnabled(false);
                   c3.setEnabled(false);
                   c4.setEnabled(false);
                   c5.setEnabled(false);
                   h1.setEnabled(false);
                   h2.setEnabled(false);
                   h3.setEnabled(false);
                   // add the menus to the menubar
                   mainMenu.add(f);
                   mainMenu.add(v);
                   mainMenu.add(c);
                   mainMenu.add(h);
                   // create the mainWindow for displaying
                   // switch and light elements
                   mainWindow = new TabbedView();
                   scrollWindow = new JScrollPane(mainWindow);
                   // create the infoBar to display
                   // the mouseOver information of components
                   infoBar = new JPanel(new BorderLayout());
                   infoBar.setPreferredSize(new Dimension(800,20));
                   info = new JLabel("");
                   info.setPreferredSize(new Dimension(400,20));
                   info.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.GRAY));
                   infoBar.add(info,BorderLayout.WEST);
              // add the items to the mainPanel
              mainPanel.add(mainMenu,BorderLayout.NORTH);
              mainPanel.add(scrollWindow,BorderLayout.CENTER);
              mainPanel.add(infoBar,BorderLayout.SOUTH);
              windowContent.add(mainPanel);
              pack();
              show();
         public static void main(String[] args)
              LightCommander GUI = new LightCommander();
              GUI.addWindowListener(
                        new WindowAdapter()
                             public void windowClosing(WindowEvent e)
                             { f3.doClick(); }
         // inner class that handles all Events
         // created by the menu items in the JFrame
         public class MenuHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   if(e.getSource() == f1)
                   //* New File:                                                                                *
                   //*      updates any currently open file, creates a fileBrowser for user          *
                   //*      input, and then creates the file and enables additional menu items     *
                        //*** check to see if a file is currently open and if so save it
                        if(setupFile != null)
                             try
                                  fos = new FileOutputStream(setupFile);
                                  oos = new ObjectOutputStream(fos);
                                  oos.writeObject(mainWindow);
                                  oos.close();
                                  fos.close();
                                  setupFile = null;
                             catch(Exception f) { JOptionPane.showMessageDialog(mainPanel,"ERROR: " + f); }
                        //*** create popup window to request file name and location (fileBrowser)
                        JFileChooser chooser = new JFileChooser();
                        int result = chooser.showSaveDialog(mainMenu);
                        if(result == JFileChooser.CANCEL_OPTION) return;
                        setupFile = chooser.getSelectedFile();
                        try
                             setupFile.createNewFile();
                             mainWindow = new TabbedView();     // reset the view here
                             mainWindow.repaint();
                             // enable the menu items that should now be functional
                             c1.setEnabled(true);
                             c12.setEnabled(true);
                        catch(Exception f){ JOptionPane.showMessageDialog(mainPanel, "ERROR: " + f); }
                   if(e.getSource() == f2)
                   //* Open File:                                                                                     *
                   //*          updates any currently open file, creates a fileBrowser for user               *
                   //*          input, opens the file, builds the view from file, enables menu items     *
                        //*** check to see if a current file is open and if so save it
                        if(setupFile != null)
                             try
                                  fos = new FileOutputStream(setupFile);
                                  oos = new ObjectOutputStream(fos);
                                  oos.writeObject(mainWindow);
                                  oos.close();
                                  fos.close();
                                  setupFile = null;
                             catch(Exception f) { JOptionPane.showMessageDialog(mainPanel,"ERROR: " + f); }
                        //*** create popup window (file browser) to allow user to select the file to be opened
                        JFileChooser chooser = new JFileChooser();
                        int result = chooser.showOpenDialog(mainMenu);
                        if(result == JFileChooser.CANCEL_OPTION) return;
                        try
                             //*** open the selected file and fill the view
                             setupFile = chooser.getSelectedFile();
                             fis = new FileInputStream(setupFile);
                             ois = new ObjectInputStream(fis);
                             mainWindow = (TabbedView) ois.readObject();
                             mainWindow.reset();
                             ois.close();
                             fis.close();
                             // finally, enable the menu items that should now be functional
                             c1.setEnabled(true);
                             c11.setEnabled(true);
                             c12.setEnabled(true);
    //                         c2.setEnabled(true);
    //                         c3.setEnabled(true);
    //                         c4.setEnabled(true);
    //                         c5.setEnabled(true);
                        catch(Exception f){ JOptionPane.showMessageDialog(mainPanel,"ERROR: " + f); }
                   if(e.getSource() == f3)
                   //* Exit Program:                                        *
                   //*          update the currently open file and exit     *
                        //*** check to see if a current file is open and if so save it
                        if(setupFile != null)
                             try
                                  fos = new FileOutputStream(setupFile);
                                  oos = new ObjectOutputStream(fos);
                                  oos.writeObject(mainWindow);
                                  oos.close();
                                  fos.close();
                                  setupFile = null;
                             catch(Exception f) { JOptionPane.showMessageDialog(mainPanel,"ERROR: " + f); }
                        System.exit(0);
                   if(e.getSource() == c11)
                   // add a lightObject to the selected switch
                   // and also add the lightObject to each view
                        //*** get the selected switchObject
                             // if the current view is tabbed find the selected tab
                             // if the current view is matrix then find the selected button
                        //*** add a lightObject to the selected switchObject
                        //*** finally add the lightObject as a button to both views
                   if(e.getSource() == c12)
                   // add a switchObject to the current setup
                   // and also add a tab to the mainWindow
                        if(!mainWindow.addSwitch())     JOptionPane.showMessageDialog(mainPanel,"ERROR: MAX number of switches are installed.");
                        // enable menu items that should now be functional
                        c11.setEnabled(true);
    //                    c2.setEnabled(true);
    //                    c3.setEnabled(true);
    //                    c4.setEnabled(true);
    //                    c5.setEnabled(true);
                   if(e.getSource() == c2){ System.out.println("event - remove"); }
                   if(e.getSource() == c3){ System.out.println("event - reset"); }
                   if(e.getSource() == c4){ System.out.println("event - all on"); }
                   if(e.getSource() == c5){ System.out.println("event - all off"); }
                   if(e.getSource() == h1){ System.out.println("event - help topics"); }
                   if(e.getSource() == h2){ System.out.println("event - technical support"); }
                   if(e.getSource() == h3){ System.out.println("event - about lightcommander2..."); }
         // displays mouseover information in the infoPanel
         public class InfoHandler implements MouseListener
              // the mouse has entered a mouselistener object
              public void mouseEntered(MouseEvent e)
                   if(e.getSource() == f ) { info.setText(" file menu");     }
                   if(e.getSource() == f1) { info.setText(" create a new setup file"); }
                   if(e.getSource() == f2) { info.setText(" open an existing setup file"); }
                   if(e.getSource() == f3) { info.setText(" exit the program");     }
                   if(e.getSource() == v ) { info.setText(" view menu");     }
                   if(e.getSource() == v1) { info.setText(" change the main window layout to tabular layout"); }
                   if(e.getSource() == c ) { info.setText(" command menu"); }
                   if(e.getSource() == c11){ info.setText(" add a light to the current lighting setup"); }
                   if(e.getSource() == c12){ info.setText(" add a switch to the current lighting setup"); }
                   if(e.getSource() == c2) { info.setText(" remove the selected item from the lighting setup");     }
                   if(e.getSource() == c3) { info.setText(" reset the selected item in the lighting setup"); }
                   if(e.getSource() == c4) { info.setText(" turn on all the lights"); }
                   if(e.getSource() == c5) { info.setText(" turn off all the lights"); }
                   if(e.getSource() == h ) { info.setText(" help menu");     }
                   if(e.getSource() == h1) { info.setText(" open a list of common help topics"); }
                   if(e.getSource() == h2) { info.setText(" open a window with company contact information"); }
                   if(e.getSource() == h3) { info.setText(" open a window displaying program info"); }
              public void mouseExited(MouseEvent e){ info.setText(""); }
              public void mousePressed(MouseEvent e){  }
              public void mouseReleased(MouseEvent e){  }
              public void mouseClicked(MouseEvent e){  }
    public class TabbedView extends JTabbedPane implements Serializable
         private SwitchObject[] switches;
         private int numSwitches;
         public TabbedView()
              super();
              switches = new SwitchObject[128];
              numSwitches = 0;
         public boolean addSwitch()
              if(numSwitches < 128)
                   for(int i=0; i<128; i++)
                        if(switches[i] == null)
                             SwitchObject x = new SwitchObject("S" + Integer.toString(i), i);
                             switches[i] = x;
                             this.addTab(x.getLabel(), x);
                             break;
                   numSwitches++;     // increment the number of switches installed
                   return true;     // signal a successful operation
              else return false;     // signal that all available switch addresses are used
    public class SwitchObject extends JPanel implements Serializable
         private String s_label;
         private int s_addr;
         private int numLights;
         private LightObject[] lights;
         // SwitchObject Constructor
         public SwitchObject(String label, int addr)
              super();
              s_label = label;
              s_addr = addr;
              numLights = 0;
              lights = new LightObject[128];     // create an empty array of lights
              for(int i=0; i<3; i++) Tx();     // send the switches addr 3 times in order to setup the hardware addr
         public String getLabel(){ return s_label; }
         public int getAddr(){ return s_addr; }
         // add a light to the switch
         public boolean addLight()
              if(numLights < 128)
                   for(int i=0; i<128; i++)
                        if(lights[i] == null)
                             lights[i] = new LightObject("L" + Integer.toString(i), i+128);
                             break;
                   numLights++;
                   return true;
              else return false;
         // transmit the switches addr to the hardware
         public void Tx()
              //*** Add Code Here ***
              System.out.println("Tx: " + Integer.toString(s_addr));     // output for debugging
    public class LightObject extends JButton implements Serializable,ActionListener
         private int l_addr;
         private boolean isOn;
         public LightObject(String label, int addr)
              super(label);
              this.addActionListener(this);
              this.setBackground(Color.YELLOW);
              l_addr = addr;
              for(int i=0; i<3; i++) Tx();          // send the light addr 3 times to setup the hardware addr
              isOn = true;
         public int getAddr(){ return l_addr; }
         // Transmit the light's addr to the hardware
         public void Tx()
              //*** Add Code Here ***
              System.out.println("Tx: " + Integer.toString(l_addr));
         public void actionPerformed(ActionEvent e)
              Tx();
              if(isOn)
                   isOn = false;
                   this.setBackground(Color.GRAY);
              else
                   isOn = true;
                   this.setBackground(Color.YELLOW);
    }

    You're welcome for the help I gave you in your last posting on this topic.
    Why are you posting 200 lines of code? 90% of the code is not related to saving/restoring a component. Create a simple demo program and then maybe someone will take a look. We are not here to debug you entire application.
    How to create a [url http://www.physci.org/codes/sscce.jsp]Short, Self Contained, Correct (Compilable), Example

  • JTabbedPane using a JLabel in setTabComponent

    Hi,
    I am in front of a problem with the JTabbedPane and the setTabComponent function. I want to use a specific JLabel in the tab. I have done this but I have pointed out that using the setToolTipText on my JLabel prevent me from browsing the tab by clicking on the label (in the tab).
    I just want to know if there is a way to fix this?
    Here is an example :
    public class test extends JFrame
        public test()
            JTabbedPane pane = new JTabbedPane();
            pane.add( "Tab1", new JLabel( "Tab1" ) );
            pane.add( "Tab2", new JLabel( "Tab2" ) );
            pane.add( "Tab3", new JLabel( "Tab3" ) );
            JLabel notClickableTab = new JLabel( "notClickableTab" );
            notClickableTab.setToolTipText( "notClickableTab" );
            pane.setTabComponentAt( 1, notClickableTab );
            JLabel clickableTab = new JLabel( "clickableTab" );
            pane.setTabComponentAt( 2, clickableTab );
            getContentPane().add( pane );
            getContentPane().setPreferredSize( new Dimension( 200, 200 ) );
            pack();
            setVisible( true );
        public static void main( String[] args )
            new test();
    }I hope this is understandable :)

    Don't set the tooltip?With this post I only want to see if there is something to do with that. In fact some property to set or anything like that , to correct that behavior.
    Obviously, not setting the tooltip can be a solution, but this is not the result i want.
    I already manage to find out some workaround using a mouseListener, but it may not be a solution in other circumstances.
    Anyway, thanks for the "tip" :P

  • Multiple JTabbedPane focussing

    I have a Swing GUI (applet) that has 2 JTabbedPanes side-by-side. The tabbed panes can contain JPanels that have many different types of components (JTable, JButtons, etc. ) on them.
    Depending on which tabbed pane has focus, other components have to be enabled/disabled. This is easily accomplished by registering the appropriate listeners with the tabbed panes themselves and clicking on the tab when I want to change focus.
    However, with focus currently on the left tabbed pane, I want to be able to just click within a JPanel on the right tabbed pane and have focus change. Since my JPanels contain many components, this involves addiing a MouseListener to every visible component. This can be quite cumbersome since a listener must be added to a table header as well as to the table and to the vertical and horizontal scrollbars as well as to the scrollpane.
    Does anyone know a better way to do this?
    I was hoping to utilize something like the glasspane, but that's only available from the applet level or JDialogs.
    Thanks.

    I may have used the term "focus" when I should have said something like "active."
    And in my attempt to simplify the question I may have described the workings of my GUI inaccurately, too.
    My GUI can "open" many different types of "documents." These documents (which basically consist of JPanels that contain many different types of components) open as tabs in a JTabbedPane. Similar to many IDEs nowadays, this group of tabs can be split into a second tab group (JTabbedPane) to view 2 docs at once. Open documents can be moved between these 2 groups.
    To be more user friendly, I make sure the currently active tab title (there can be only one) is rendered uniquely.
    Depending on which type of document is currently active (or in focus), toolbar buttons, menu actions and the such are enabled/disabled.
    I need notification when a user is selecting the other tab group so it can be made active. As I said previously, this is quite easy if the user just clicks on the tab itself, but if the user clicks within the already open document it seems I need a mouse listener on every component. I tried focus listeners, at one time, but they only work when components are enabled, and some of the components I use could be disabled.
    It seems that there is no shortcut, and listeners have to be added to every component in a document. I was hoping someone would know a technique similar to a glass pane where I could just add one listener and then pass on the event when I handled it.

  • JTabbedPane SelectedTab Color

    I have this problem: I would like to change the Default Tab Background Color in a JTabbedPane (not the setBackgroundAt method!!!).
    Thanks to all

    The key is:
    UIManager.put("TabbedPane.selected", Color.green);
    .. as this example (found in www.esus.com/javaindex/j2se/jdk1.2/javaxswing/generalpurposecontainers/jtabbedpane/jtabbgcolor.html)
    shows:
    import javax.swing.plaf.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class Main extends JPanel {
    public Main() {
    setLayout(new BorderLayout());
    UIManager.put("TabbedPane.selected", Color.green);
    JTabbedPane tabbedPane = new JTabbedPane();
    for (int i=0;i<10;i++) {
    tabbedPane.addTab("Tab #" + i, new JLabel("Tab #" + i));
    tabbedPane.setBackgroundAt(i, new Color(25*i, 25*i, 25*i));
    add(tabbedPane, BorderLayout.CENTER);
    JPanel createPane(String s) {
    JPanel p = new JPanel();
    p.add(new JLabel(s));
    return p;
    public static void main(String[] args) {
    JFrame frame = new JFrame("JTabbedPane Selected Color Demonstration");
    frame.addWindowListener( new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    System.exit(0);
    frame.getContentPane().add(new Main());
    frame.setSize(200, 100);
    frame.setVisible(true);
    bye!

Maybe you are looking for