JTabbedPane with actionlistener?

Hi. I need to make a JTabbedPane and have every tab listen to an action (mouse or otherwise). In general, i wrote methods to detach and reattach the pane, and they responde perfectly to a temprorary button I made. What i need to do now is detach a tab when the tab name (where the getTitle would go) is double-clicked, but i cant add an action listener to that part of the tab, because, frankly, i dont know how to edit it, besides changing the title. Is there a way to add a button where the title goes? Thank you.

Search the forum using "+jtabbedpane +close +icon" to find ideas on this topic.

Similar Messages

  • JTabbedpane with JRadiobutton?

    I have a JTabbedpane with 2 tabs (tab1, tab2).
    I have 2 radiobutton (JRadioButton).
    So for now, i want to when i click on radiobutton1 it will be show tab1
    when i click on radiobutton2 it will be show tab2.
    Here is my source code, please help me to slove it:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.FlowLayout;
    import java.awt.GridBagLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    public class JTablePaneTest extends JFrame implements ActionListener{
    private JTabbedPane pane;
    private JRadioButton radioButton1 = new JRadioButton("Radiobutton1", true);
    private JRadioButton radioButton2 = new JRadioButton("Radiobutton2", false);
    JPanel radioPanel =null;
    public JTablePaneTest() {
    super("TEST");
    this.setLayout(new BorderLayout());
    this.setSize(new Dimension(300,300));
    this.getContentPane().add(this.getAllRadioButton(), BorderLayout.SOUTH);
    this.getContentPane().add(this.getPane(), BorderLayout.CENTER);
    this.pack();
    this.setVisible(true);
    private JPanel getAllRadioButton(){
    if(radioPanel==null){
    radioPanel = new JPanel();
    radioPanel.setLayout(new FlowLayout());
    radioPanel.setBorder(BorderFactory.createEmptyBorder());
    ButtonGroup bg = new ButtonGroup();
    bg.add(radioButton1);
    bg.add(radioButton2);
    radioPanel.add(radioButton1);
    radioPanel.add(radioButton2);
    return radioPanel;
    private JTabbedPane getPane(){
    if(pane == null){
    pane = new JTabbedPane();
    pane.addTab("Tab1", null, panel1(), "Tab1");
    pane.addTab("Tab2", null, panel2(), "Tab2");
    return pane;
    private JPanel panel1(){
    JPanel panel1 = new JPanel();
    panel1.setLayout(new GridBagLayout());
    panel1.add(new JButton("TEST1"));
    return panel1;
    private JPanel panel2(){
    JPanel panel2 = new JPanel();
    panel2.setLayout(new GridBagLayout());
    panel2.add(new JTextField(12));
    return panel2;
    public static void main(String[] args) {
    new JTablePaneTest();
    @Override
    public void actionPerformed(ActionEvent e) {
    if(e.getSource() == radioButton1){
    //show tab1
    if(e.getSource() == radioButton2){
    //show tab2
    }Thanks you very much.
    Edited by: ecard104 on Sep 1, 2008 10:01 AM

    ecard104 wrote:
    can you tell me the method you want to say?I'd prefer to have you look at the API and the tutorial. It would be better for you in the long run. It's spelled out in the tutorial.
    [http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html]
    [http://java.sun.com/javase/6/docs/api/javax/swing/JTabbedPane.html]
    Edited by: Encephalopathic on Sep 1, 2008 10:17 AM

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

  • Jtabbedpane with replacing tab content

    Hello,
    I am developing an applet that should contain a JTabbedPane with 2 tabs.
    The second tab is easy to do because ti contains one Jpanel all the way.
    the first however is an issue, because i am supposed to change its content when the applet is running.
    this means i have 3 JPanels, J1, J2, J3.
    At tge beginning the applet contains J1 in the first tab.
    and J1 contains a button. when i click that button the applet should replace J1 with J2.
    the problem is i haven't managed to find a solution yet :(
    I have tried with setvisible(false) and validate(). It won't work. I also tried to add the J2 panel over J1, but encountered no succes.
    anybody has any idea ?
    Message was edited by:
    asrfel

    If you want to change back and forth repeatedly then wrap J1/2/3 in a JPanel with a CardLayout.
    If you can discard one when it's done with, use the remove() and insertTab() methods of JTabbedPane.

  • A component within JTabbedPane with overlay layout

    Hi, I use the following solution to have a component within the upper right corner of the JTabbedPane: [http://forums.sun.com/thread.jspa?forumID=57&threadID=636289&start=2|http://forums.sun.com/thread.jspa?forumID=57&threadID=636289&start=2] . It works great, but when I'm resizing a window with the JTabbedPane with the JTabbedPane.WRAP_TAB_LAYOUT and width of all of the tabs is higher than size of the window the tabs are wrapped. But it should be wrapped when width of all tabs + width of the added component is higher than the size. I have no idea how to do this. Any ideas?
    Please see the screenshot: [http://img150.imageshack.us/img150/5629/btn.png|http://img150.imageshack.us/img150/5629/btn.png]

    Just a quick idea:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.plaf.*;
    class TabbedPaneTest {
      public JComponent makeUI() {
        UIManager.put("TabbedPane.tabAreaInsets",
                      new InsetsUIResource(6, 2, 0, 60));
        JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        sp.setTopComponent(makeTabPanel(new JTabbedPane()));
        sp.setBottomComponent(makeTabPanel(new ClippedTitleTabbedPane()));
        sp.setPreferredSize(new Dimension(320, 240));
        return sp;
      private JPanel makeTabPanel(final JTabbedPane tab) {
        tab.addTab("asdfasd", new JLabel("456746"));
        tab.addTab("1234123", new JScrollPane(new JTree()));
        tab.addTab("6780969", new JLabel("zxcvzxc"));
        tab.setAlignmentX(1.0f);
        tab.setAlignmentY(0.0f);
        JButton b = new JButton(new AbstractAction("add") {
          @Override public void actionPerformed(ActionEvent e) {
            tab.addTab("test", new JScrollPane(new JTree()));
        b.setAlignmentX(1.0f);
        b.setAlignmentY(0.0f);
        JPanel p = new JPanel();
        p.setLayout(new OverlayLayout(p));
        p.add(b);
        p.add(tab);
        return p;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(new TabbedPaneTest().makeUI());
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    class ClippedTitleTabbedPane extends JTabbedPane {
      //XXX Nimbus NPE
      Insets tabInsets = UIManager.getInsets("TabbedPane.tabInsets");
      Insets tabAreaInsets = UIManager.getInsets("TabbedPane.tabAreaInsets");
      public ClippedTitleTabbedPane() {
        super(JTabbedPane.TOP);
        setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        addComponentListener(new ComponentAdapter() {
          @Override public void componentResized(ComponentEvent e) {
            initTabWidth();
      @Override
      public void insertTab(String title, Icon icon, Component component,
                            String tip, int index) {
        super.insertTab(title, icon, component, tip==null?title:tip, index);
        JLabel label = new JLabel(title, JLabel.CENTER);
        Dimension dim = label.getPreferredSize();
        label.setPreferredSize(
            new Dimension(0, dim.height+tabInsets.top+tabInsets.bottom));
        setTabComponentAt(index, label);
        initTabWidth();
      private void initTabWidth() {
        Insets insets = getInsets();
        int areaWidth = getWidth() - tabAreaInsets.left - tabAreaInsets.right
                                   - insets.left        - insets.right;
        int tabCount = getTabCount();
        int tabWidth = 0;
        switch(getTabPlacement()) {
          case LEFT: case RIGHT:
          tabWidth = areaWidth/4;
          break;
          case BOTTOM: case TOP: default:
          tabWidth = areaWidth/tabCount;
        int gap = areaWidth - (tabWidth * tabCount);
        if(tabWidth>80) {
          tabWidth = 80;
          gap = 0;
        tabWidth = tabWidth - tabInsets.left - tabInsets.right - 3;
        for(int i=0;i<tabCount;i++) {
          JLabel l = (JLabel)getTabComponentAt(i);
          if(l==null) break;
          int h = l.getPreferredSize().height;
          l.setPreferredSize(new Dimension(tabWidth+((gap>0)?1:0), h));
          gap--;
        revalidate();
    }

  • JTabbedPane with two rows of tabs

    Hi,
    I need to create a JTabbedPane with layout policy as SCROLL_TAB_LAYOUT with two rows of tabs. The first level will have say 10 tabs and the all the remaining tabs (say 20) will be added in the next level. Please help me out on this, to how to proceed with it?
    Edited by: Soundarapandian on Nov 25, 2009 3:10 PM

    Soundarapandian wrote:
    I need to create a JTabbedPane with layout policy as SCROLL_TAB_LAYOUT with two rows of tabs. The first level will have say 10 tabs and the all the remaining tabs (say 20) will be added in the next level. Please help me out on this, to how to proceed with it?Try this (imho better) approach:
    create a new tabbedpane for each level and add each of these tabbedpanes to an upperlevel tabbedpane, thus allowing you to pre-select the desired level.

  • JTabbedPane with JSplitPane - HELP !!!

    What am I missing??? I have a JSplitPane in a TabbedPane. The topComponent contains a JComboBox with Key values, the Bottom Component will display details based on the key value passed. The bottomComponent has 2 constructors: one default and one accepting an Argument. The default constructor instantiate the class that would represent the data and formats the bottomComponent. The second constructor retrieves the data from the Oracle database and formats the BottomComponent using the same method. I put System.out messages and the values are showing using the Second constructor. Your help is greatly appreciated.

    This is the complete set of code. I hope you can follow the logic. I tried your last suggestion without any success. Maybe by reviewing the code you can see a problem. I appreciate your help greatly. Thanks.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Management extends JPanel implements ChangeListener{
    //private JFrame dlframe;
    private JTabbedPane propPane;
    public Management(){
    propPane = new JTabbedPane(SwingConstants.TOP);
    propPane.setSize(795, 550);
    propPane.addChangeListener(this);
    populateTabbedPane();
    // getContentPane().add(propPane);
    add(propPane);
    } // end of constructor
    // create tabs with titles
    private void populateTabbedPane(){
         propPane.addTab("Management", null, new Mgmt(), "Management");
         propPane.addTab("Management Contact", null,
    new Management_Contact(), "Management Contact");
    } // end of populateTabbedPane
    public void stateChanged(ChangeEvent e){
         System.out.println("\n\n ****** Management.java " + propPane.getSelectedIndex() + " " + propPane.getTabPlacement());
    public static void main(String[] args){
    Home dl = new Home();
    dl.pack();
    dl.setSize(800, 620);
    dl.setBackground(Color.white);
    dl.setVisible(true);
    } // end of class Management
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Management_Contact extends JPanel {
         Mgmt_Class mgmt = null;
         Mgmt_Contact mgmtContact = null;
         public Management_Contact() {
              JSplitPane split = new JSplitPane();
              split.setOrientation(JSplitPane.VERTICAL_SPLIT);
              Mgmt_Header hdr = new Mgmt_Header();
              split.setTopComponent(hdr);
              Mgmt_Contact mgmtContact = new Mgmt_Contact();
              JScrollPane scrollPane = new JScrollPane(mgmtContact,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
              JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scrollPane.setPreferredSize(new Dimension(650,300));
              split.setBottomComponent(scrollPane);
              add(split);
    } // end of Management class
    import java.util.Vector;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Mgmt_Header extends JPanel implements ActionListener{
    private JComboBox cmbMgmt;
    private JTextField txtMgmtCode;
    private JTextField txtMgmtAddr1;
    private JTextField txtMgmtAddr2;
    private JTextField txtMgmtCity;
    private JButton sel;
    private JLabel lblBlk;
    private JPanel pWork;
    private Box vertBox;     
    private Box topBox;     
    private Box midBox;     
    private Box botBox;     
    JToolTip toolTip = null;
    private Mgmt_Class mClass = null;
    private Mgmt_Contact cnt = null;
    Vector mgmtVct = null;
    public Mgmt_Header(){
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
    mClass = new Mgmt_Class();
    mgmtVct = new Vector();
         cmbMgmt = new JComboBox();
         cmbMgmt.addItem(" ");
         mgmtVct = mClass.bldMgmtHeader();
         for (int x1=0; x1<mgmtVct.size() ;x1++ )
         mClass = (Mgmt_Class)mgmtVct.get(x1);
         cmbMgmt.addItem(mClass.getManagementName());
    System.out.println("MgmtHeader " + mgmtVct.size() + " " + cmbMgmt.getItemCount());
         cmbMgmt.setEditable(false);
         cmbMgmt.setBackground(Color.white);
         cmbMgmt.setName("cmbMgmt");
         cmbMgmt.setPreferredSize(new Dimension(250,27));
         cmbMgmt.setFont(new Font("Times-Roman",Font.PLAIN,12));
         cmbMgmt.addActionListener(this);
         pWork = new JPanel();
         pWork.setLayout(new FlowLayout(FlowLayout.CENTER));
         pWork.setBorder(BorderFactory.createTitledBorder(" Select Management Name "));
         pWork.add(new JLabel("Name: "));
         pWork.add(cmbMgmt);
         topBox.add(pWork);
         txtMgmtAddr1 = new JTextField("Address line 1",15);
         txtMgmtAddr1.setEditable(false);
         txtMgmtAddr2 = new JTextField("Address line 2",15);
         txtMgmtAddr2.setEditable(false);
         txtMgmtCity = new JTextField("City",15);
         txtMgmtCity.setEditable(false);
         midBox.add(midBox.createVerticalStrut(10));
         botBox.add(new JLabel("Address:"));
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtAddr1);
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtAddr2);
         botBox.add(topBox.createHorizontalStrut(15));
         botBox.add(txtMgmtCity);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         add(vertBox);
    } // end of constructor
         public void actionPerformed(ActionEvent evt){
         if (evt.getSource() instanceof JComboBox){
         if (((JComboBox)evt.getSource()).getName() == "cmbMgmt"){
         int sel = ((JComboBox)evt.getSource()).getSelectedIndex();
         System.out.println("ActionListener " + sel + " " + ((JComboBox)evt.getSource()).getItemAt(sel) + " " + cmbMgmt.getItemAt(sel));
         Mgmt_Class mClass = (Mgmt_Class)mgmtVct.get(sel - 1);
         System.out.println("From Vector " + mClass.getAddress1() + " " + mClass.getAddress2() + " " + mClass.getManagementCode());
         txtMgmtAddr1.setText(mClass.getAddress1());
         txtMgmtAddr2.setText(mClass.getAddress2());
         txtMgmtCity.setText(City.getCityName(mClass.getCityCode()));
         System.out.println("\n\nListener " + ((JComboBox)evt.getSource()).getSelectedItem() + " " + (((JComboBox)evt.getSource()).getSelectedIndex()) );
         int mCode = mClass.getManagementCode();
         cnt = new Mgmt_Contact(mCode);
    System.out.println("\n After new Mgmt_Contact constructor");
         } // end of JComboBox
    } // end of actionPerformed
    } // end of Mgmt_Header
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    import java.io.*;
    public class Mgmt_Contact extends JPanel implements KeyListener{
         private Mgmt_Contact_Class contact = null;
         private DefaultFocusManager mgr = null;
         private JTextField txtFName = null;
         private JTextField txtLName = null;
         private JTextField txtAddr1 = null;
         private JTextField txtAddr2 = null;
         private JButton btnUpd = null;
         private JButton btnNew = null;
         private JButton btnDel = null;
         private JButton btnNext = null;
         private JButton btnPrior = null;
         private JButton btnSel = null;
         private JPanel cntct = null;
         private JPanel pWork = null;
         private JPanel pWest = null;
         private JPanel pEast = null;
         private JPanel pNorth = null;
         private JPanel pSouth = null;
         private JPanel pCenter = null;
         public Mgmt_Contact() {
         System.out.println("\n MgmtContact default constructor");
              contact = new Mgmt_Contact_Class();
              bldPage();
         System.out.println("\n ******* After bldPage() routine");
         public Mgmt_Contact(int mCode) {
    System.out.println("\n MgmtContact second constructor " + mCode);
         Vector mgmtVct = new Vector();
         contact = new Mgmt_Contact_Class();
         mgmtVct = contact.bldMgmtContactTbl(mCode);
         contact =(Mgmt_Contact_Class)mgmtVct.get(0);
    System.out.println("\n ******* Management Contact Table *** " + contact.getFirstName());          
         bldPage();
    System.out.println("\n ******* After bldPage() routine");
         public void bldPage(){
    System.out.println("\n MgmtContact bldPage ");
              cntct = new JPanel();
              cntct.setLayout(new BorderLayout());
              pWest = new JPanel();
              pWest.setLayout(new GridLayout(0,1));
              pCenter = new JPanel();
              pCenter.setLayout(new GridLayout(0,1));
              pNorth = new JPanel();
              pNorth.setLayout(new FlowLayout(FlowLayout.CENTER));
              pSouth = new JPanel();
              pSouth.setLayout(new FlowLayout());
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              pWest.add(new JLabel("First :"));
              txtFName = new JTextField(15);
              txtFName.setText(contact.getFirstName());
    System.out.println("\n First Name " + txtFName.getText() + " " + contact.getFirstName());
              txtFName.setPreferredSize(new Dimension(200,27));
              txtFName.addKeyListener(this);
              txtFName.setName("txtFName");
              pWork.add(txtFName);
              pWork.add(new JLabel("Last :"));
              txtLName = new JTextField(15);
              txtLName.setText(contact.getLastName());
              txtLName.setPreferredSize(new Dimension(200,27));
              txtLName.setName("txtLName");     
              txtLName.addKeyListener(this);
              pWork.add(txtLName);
              pCenter.add(pWork);
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              pWest.add(new JLabel("Address :"));
              txtAddr1 = new JTextField(15);
              txtAddr1.setText(contact.getAddress1());
              txtAddr1.setPreferredSize(new Dimension(200,27));
              txtAddr1.addKeyListener(this);
              txtAddr1.setName("txtAddr1");
              pWork.add(txtAddr1);
              pWork.add(new JLabel(" "));
              txtAddr2 = new JTextField(15);
              txtAddr2.setText(contact.getAddress2());
              txtAddr2.setPreferredSize(new Dimension(200,27));
              txtAddr2.setName("txtAddr2");
              txtAddr2.addKeyListener(this);
              pWork.add(txtAddr2);
              pCenter.add(pWork);
              pWork = new JPanel();
              pWork.setLayout(new FlowLayout(FlowLayout.LEFT));
              btnUpd = new JButton("Update");
              btnUpd.addActionListener(new ButtonListener());
              btnDel = new JButton("Delete");
              btnDel.addActionListener(new ButtonListener());
              btnNew = new JButton(" Add ");
              btnNew.addActionListener(new ButtonListener());
              btnNext = new JButton(" Next ");
              btnNext.addActionListener(new ButtonListener());
              btnPrior = new JButton(" Prior ");
              btnPrior.addActionListener(new ButtonListener());
              btnSel = new JButton(" Select ");
              btnSel.addActionListener(new ButtonListener());
              pSouth.add(btnNew);
              pSouth.add(btnUpd);
              pSouth.add(btnDel);
              pSouth.add(btnNext);
              pSouth.add(btnPrior);
              pSouth.add(btnSel);
              cntct.add("West", pWest);
              cntct.add("Center", pCenter);
              cntct.add("South", pSouth);
              add(cntct);
         class ButtonListener implements ActionListener{
         public void actionPerformed(ActionEvent e){
    System.out.println("ButtonListener " + e.getActionCommand() + " " +
              contact.getString());
    // KeyListener Interface
         public void keyPressed(KeyEvent e){
         public void keyReleased(KeyEvent e){
              mgr = new DefaultFocusManager();
              Component comp = e.getComponent();
              Object obj = ((JTextField)e.getSource());
              if ((ColUtils.isMaxField(obj))){
              mgr.focusNextComponent(comp);
         } // end of KeyReleased
         public void keyTyped(KeyEvent e){
              char num = e.getKeyChar();
              Object obj = ((JTextField)e.getSource());
              if (ColUtils.isDataValid(num, obj)){
              else {
              e.consume();
              System.out.println(num + " Rejected Data");
         } // end of keyTyped
    } // end of Mgmt_Contact class

  • JTabbedPane with JScrollPane

    The application uses a JTabbedPane, each Tab contains a JScrollPane, the TopComponent contains the same Class with different Classes for the BottomComponent. Each BottomComponent is a separate class and relates to a different table. How can I interface with with the other classes without knowing which Tab is active?

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Property_Features extends JPanel implements ActionListener{
         private JTextArea txtFeature;
         private JLabel image;
         private JButton btnNew = null;
         private JButton btnUpd = null;
         private JButton btnDel = null;
         private JToolTip toolTip = null;
         private Prop_Header propHdr = null;
         private JPanel fPanel = null;
         private JPanel wPanel = null;
         private Box vertBox;     
         private Box topBox;     
         private Box midBox;     
         private Box botBox;     
    public Property_Features(){
         toolTip = new JToolTip();
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
         wPanel = new JPanel();
         wPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         txtFeature = new JTextArea(5,50);
         txtFeature.setFont(new Font("SansSerif", Font.PLAIN, 14));
         txtFeature.setLineWrap(true);
         txtFeature.setWrapStyleWord(true);
         txtFeature.setEditable(true);
         txtFeature.setBorder(BorderFactory.createTitledBorder(" Describe the Property Features"));
         toolTip.setComponent(txtFeature);
         txtFeature.setToolTipText("Enter Property Feature of Major Interest");
         wPanel.add(txtFeature);
         topBox.add(wPanel);
         wPanel = new JPanel();
         wPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         btnNew = new JButton(" Add ");
         btnNew.addActionListener(this);
         toolTip.setComponent(btnNew);
         btnNew.setToolTipText("Add Property Feature Information");
         btnUpd = new JButton("Update");
         btnUpd.addActionListener(this);
         toolTip.setComponent(btnUpd);
         btnUpd.setToolTipText("Update Property Feature Information");
         btnDel = new JButton("Delete");
         btnDel.addActionListener(this);
         toolTip.setComponent(btnDel);
         btnDel.setToolTipText("Delete Property Information");
         wPanel.add(btnNew);
         wPanel.add(btnUpd);
         wPanel.add(btnDel);
         midBox.add(wPanel);
         wPanel = new JPanel();
         wPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
         image = new JLabel("", new      ImageIcon("c:/ATC_Application/images/skiing.jpg"), JLabel.CENTER);
         wPanel.add(image);
         botBox.add(image);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         JSplitPane split = new JSplitPane();
         split.setOrientation(JSplitPane.VERTICAL_SPLIT);
         Prop_Header propHdr = new Prop_Header();
         split.setTopComponent(propHdr);
         split.setBottomComponent(vertBox);
         JScrollPane scrollPane = new JScrollPane(vertBox,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
         scrollPane.setPreferredSize(new Dimension(650,400));
         split.add(scrollPane);
         add(split);
    } // end of Property_Features constructor
    // ActionListener Interface
         public void actionPerformed(ActionEvent e){
              System.out.println("Action Listener " + e.getActionCommand());
    } // end of class
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Prop_Header extends JPanel implements ActionListener{
    private JComboBox cmbProp;
    private JTextField txtPropCode;
    private JTextField txtPropAddr1;
    private JTextField txtPropAddr2;
    private JTextField txtPropCity;
    private JTextField txtPropState;
    private JButton sel;
    private JLabel lblBlk;
    private JPanel pWork;
    private Box vertBox;     
    private Box topBox;     
    private Box midBox;     
    private Box botBox;     
    JToolTip toolTip = null;
    public Prop_Header(){
         vertBox = Box.createVerticalBox();
         topBox = Box.createHorizontalBox();
         midBox = Box.createHorizontalBox();
         botBox = Box.createHorizontalBox();
         cmbProp = new JComboBox();
         cmbProp.addItem(" ");
         cmbProp.setEditable(false);
         cmbProp.setBackground(Color.white);
         cmbProp.setPreferredSize(new Dimension(250,27));
         cmbProp.setFont(new Font("Times-Roman",Font.PLAIN,12));
         cmbProp.addActionListener(this);
         txtPropCode = new JTextField(5);
         txtPropCode.setFont(new Font("Times-Roman",Font.PLAIN,12));
         txtPropCode.setPreferredSize(new Dimension(5,27));
         txtPropCode.addActionListener(this);
         lblBlk = new JLabel(" ");
         sel = new JButton("Select");
         sel.addActionListener( this);
         toolTip = new JToolTip();
         toolTip.setComponent(cmbProp);
         cmbProp.setToolTipText("Select Property Name & Press
    Select button ");
         toolTip.setComponent(txtPropCode);
         txtPropCode.setToolTipText("Enter Property Code & Press
    Select Button ");
         toolTip.setComponent(sel);
         sel.setToolTipText("Display Property Information Based on
    Name or Code Entered ");
         pWork = new JPanel();
         pWork.setLayout(new FlowLayout(FlowLayout.CENTER));
         pWork.setBorder(BorderFactory.createTitledBorder(" Select
    Property Name or Enter Code "));
         pWork.add(new JLabel("Name: "));
         pWork.add(cmbProp);
         pWork.add(new JLabel(" Code: "));
         pWork.add(txtPropCode);
         pWork.add(lblBlk);
         pWork.add(sel);
         topBox.add(pWork);
         txtPropAddr1 = new JTextField("Address line 1",15);
         txtPropAddr1.setEditable(false);
         txtPropAddr2 = new JTextField("Address line 2",15);
         txtPropAddr2.setEditable(false);
         txtPropCity = new JTextField("City",15);
         txtPropCity.setEditable(false);
         txtPropState = new JTextField("State",3);
         txtPropState.setEditable(false);
         toolTip.setComponent(txtPropAddr1);
         txtPropAddr1.setToolTipText("First Address Line of Property");
         toolTip.setComponent(txtPropAddr2);
         txtPropAddr2.setToolTipText("Second Address Line of Property");
         toolTip.setComponent(txtPropCity);
         txtPropCity.setToolTipText("City Name of Property location");
         toolTip.setComponent(txtPropState);
         txtPropState.setToolTipText("State Code of Property location");
         midBox.add(midBox.createVerticalStrut(10));
         botBox.add(new JLabel("Address:"));
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropAddr1);
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropAddr2);
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropCity);
         botBox.add(topBox.createHorizontalStrut(10));
         botBox.add(txtPropState);
         vertBox.add(topBox);
         vertBox.add(midBox);
         vertBox.add(botBox);
         add(vertBox);
    } // end of constructor
         public void actionPerformed(ActionEvent evt){
         } // end of actionPerformed
    } // end of Prop_Header

  • Problem with ActionListener

    Hi
    i have coded a button and added a Actionlistner that when the button is pressed then it should repaint the dice.but I don't know why it is not working.
    here i my code
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.ImageIcon;
    public class Board {
    JFrame frame;
    //Image dice[] = new Image[2];
    //int stick1,stick2,stick3,stick4,stick5;
    //boolean begin = true;
    Stick st = new Stick();
    public static void main(String[] args) {
         Board b = new Board();
         b.go();
        public void go() {
            //Make sure we have nice window decorations.
           JFrame.setDefaultLookAndFeelDecorated(true);
            //Create and set up the window.
            JFrame frame = new JFrame("Senet");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel jp = new JPanel();
            JButton button = new JButton("Make Move");
            button.addActionListener((ActionListener) new Stick());
          Stick st = new Stick();
            //frame.getContentPane().add(BorderLayout.EAST,button);
           frame.getContentPane().add(BorderLayout.CENTER,jp);
           jp.setBackground(Color.DARK_GRAY);
           jp.setLayout(new BoxLayout(jp,BoxLayout.Y_AXIS));
           Check c = new Check();
           jp.add(c);
           jp.add(st);
           st.add(button);
          st.setBackground(Color.WHITE);
            //Display the window.
            frame.setSize(600,500);
            frame.setVisible(true);
       /* public void actionPerformed(ActionEvent event){
             st.repaint();
    import javax.swing.*;
    import java.awt.*;
    import java.awt.Graphics.*;
    import java.awt.event.*;
    * @author Kokil Bhalerao
    public class Stick extends JPanel implements ActionListener{
          Image dice[] = new Image[2];
          int stick1, stick2,stick3,stick4,stick5, result;
          boolean begin = true;
          public void actionPerformed(ActionEvent event){
                  repaint();
          public void paintComponent(Graphics g)
               super.paintComponent(g);
               Graphics2D g2 = (Graphics2D)g;
               dice = new Image[2];
                  dice[0] = new ImageIcon("C:/Program Files/Java/images/stick2.gif").getImage();
                    dice[1] = new ImageIcon("C:/Program Files/Java/images/stick1.gif").getImage();
                    begin = false;
                       stick1 = (int)(Math.random() * 2 + 1);
                      stick2 = (int)(Math.random() * 2 + 1);
                      stick3 = (int)(Math.random() * 2 + 1);
                      stick4 = (int)(Math.random() * 2 + 1);
                      stick5 = (int)(Math.random() * 2 + 1);
                     setAll(stick1,stick2,stick3,stick4,stick5,begin);
               // draw dice if they've clicked the roll button at least once
               if (!begin)
                   g2.drawImage(dice[stick1 - 1], 20, 40,100,50,this);
                  g2.drawImage(dice[stick2 - 1], 120, 40,100,50,this);
                  g2.drawImage(dice[stick3 - 1], 220, 40,100,50,this);
                  g2.drawImage(dice[stick4 - 1], 320, 40,100,50,this);
                  g2.drawImage(dice[stick5 - 1], 420,40,100,50,this);
               else
                  g2.drawString("Welcome to senet", 20, 60);
            public void setImages(Image s[])
               dice = s;
            public void setAll(int s1,int s2,int s3,int s4,int s5,boolean b)
                 stick1 = s1;
                 stick2 = s2;
                 stick3 = s3;
                 stick4 = s4;
                 stick5 = s5;
                 begin = b;
    public class Check extends JPanel{
         public void paint(Graphics g) {
            int row;   // Row number, from 0 to 7
            int col;   // Column number, from 0 to 7
            int x,y;   // Top-left corner of square
            Image bg = new ImageIcon("C:/Program Files/Java/images/piece1.gif").getImage();
            for ( row = 0;  row < 3;  row++ ) {
               for ( col = 0;  col < 10;  col++) {
                  x = col * 60;
                  y = row * 60;
                     g.setColor(Color.black);
                  g.drawRect(x, y, 60, 60);
                  g.setColor(Color.blue);
                 g.fillRect(x+1, y+1, 60, 60);
                  if( row == 0 )
                 g.drawImage(bg, x+5,y+5,40,40,Color.RED, this);
            } // end for row
         }  // end paint()Please somebody help me with this.
    Thanks

    thanks for the reply. but i don't know how i can do
    that.So the code above is not yours ?
    http://java.sun.com/docs/books/tutorial/java/index.html

  • JTabbedPane with FormLayout problems

    I created form which contain JTabbedPane within JPanel with FormLayout. In the JTabbedPane, I put JPanel with FormLayout. In Design Mode, there is nothing problem, I can put whatever item into the JPanel of JTabbedPane. But in Runtime Mode, JTabbedPane display nothing, many items I've put on it are not displayed. But when I change the Layout into another like XY Layout or FlowLayout, items are displayed correctly.
    any idea to solve this?
    and why JDeveloper doesn't implement SpringLayout?

    Hi user567546, i faced the same problem.
    Fortunately, I solved it by using PanelBuilder instead of Panel,
    take a look at this example:
    http://www.java2s.com/Code/Java/Swing-Components/DemonstratesthebasicFormLayoutsizesconstantminimumpreferred.htm
    Regards,
    Luis R.

  • Problem in subclass with ActionListener

    Hello,
    I need to program two forms which are identical except for the actions their buttons should do and some other minor differences, therefore I made a superclass for one of the forms and then extended it to build the other form. I messed up and wrote the ActionListener's as inner classes inside the superclass. Now, the buttons in the subclass react exactly the same as the buttons in the superclass. A solution I can think of is to forget about extending the class and making a different class for each form, but this would mean having two different classes with very similar code, therefore I'm sure there is a more elegant solution. Any ideas?
    Thank you,
    Alfredo

    I believe that writing the ActionListeners as separate classes won't fix the problem, since the same ActionListeners would be called for each of the forms. The problem is how do I make the buttons in the subclass call different ActionListeners from the ones in the superclass.

  • JTabbedPane with JTextField

    Can anyone provide me with an example on how to incorporate a JTextField into a JTabbedPane? There are many examples of creating JButtons as components of a JTabbedPanes but nothing for JTextFields. Can this be done? I get some wierd compiler errors when I try it?
    Any help will be much appreciated. Thanks.

    Thanks for the quick response but...
    My question was "how to incorporate these fields into a JTabbedPane."
    I'm new to Java so I have "borrowed" a Sun Tutorial JTabbedPane example which includes one JLable component per tab and tried to add a JTextField.
    Here is "my" code.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class TabbedPaneDemo extends JFrame {
    // Initialize Screen Text Fields
    private JTextField lastName = null;
    //Vector recordData = new Vector(20);
    public TabbedPaneDemo() {
    ImageIcon icon = new ImageIcon("images/middle.gif");
    JTabbedPane tabbedPane = new JTabbedPane();
    Component panel1 = makeRecordPanel("Teacher Record");
    tabbedPane.addTab("Teacher", icon, panel1, "Update Teacher Information");
    tabbedPane.setSelectedIndex(0);
    Component panel2 = makeRecordPanel("Parent Record");
    tabbedPane.addTab("Parent", icon, panel2, "Update Parent Information");
    Component panel3 = makeRecordPanel("Child Record");
    tabbedPane.addTab("Child", icon, panel3, "Update Child Information");
    //Add the tabbed pane to this panel.
    setLayout(new GridLayout(1, 1));
    add(tabbedPane);
    protected Component makeRecordPanel(String text) {
    JPanel panel = new JPanel(false);
    JLabel label1 = new JLabel("Last Name");
    JTextField lastName = new JTextField(20);
    label1.setHorizontalAlignment(JLabel.LEFT);
    panel.setLayout(new GridLayout(1, 1));
    panel.add(label1);
    panel.add(lastName);
    return panel;
    public static void main(String[] args) {
    JFrame frame = new JFrame("Maintain DayCare Records");
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {System.exit(0);}
    frame.getContentPane().add(new TabbedPaneDemo(),
    BorderLayout.CENTER);
    frame.setSize(800, 600);
    frame.setVisible(true);
    This compiles OK but when I try to run it I get the following run-time errors.
    java.lang.Error: Do not use TabbedPaneDemo.setLayout() use TabbedPaneDemo.getContentPane().setLayout() instead
         at javax.swing.JFrame.createRootPaneException(JFrame.java:333)
         at javax.swing.JFrame.setLayout(JFrame.java:394)
         at TabbedPaneDemo.<init>(TabbedPaneDemo.java:29)
         at TabbedPaneDemo.main(TabbedPaneDemo.java:53)
    Any thoughts?

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

  • Working with ActionListener

    i am working with a complex structured application where i have to invoke the ActionListener.processAction() before the PROCESS_VALIDATIONS phase.
    i have a set of code which is
    public class MyActionListener implements ActionListener{
    public PhaseId getPhaseId() {
         return PhaseId.PROCESS_VALIDATIONS;
    public void processAction(ActionEvent arg0) throws AbortProcessingException {
         // TODO Auto-generated method stub
         log.info("-- processAction --");
    <h:commandButton id="btnSubmit"
         action="#{bean.action}">
         <f:actionListener type="mypack.listener.MyActionListener" />
    </h:commandButton>but the processAction is called in INVOKE_APPLICATION phase.
    kindly help me to know how to invoke the listener before the Validation phase
    thanks in advance
    Subbhu

    Try using the immediate attribute on your commandLink
    or commandButton.immediate attribute will bypass the validation phase all the times, but i am in need to conditionally bypass the validation.
    is there any other means...
    thanks
    Subbhu

  • Open JTabbedPane with focus in tab

    I have a swing standalone app where general navigation is managed with something like this:
       private void addNewComponent(JComponent component) {
          JComponent panel = main.getDesktopComponent();
          main.setMainTittle(GlobalOptions.getTittle());
          panel.removeAll();
          panel.add(component, BorderLayout.CENTER);
          component.requestFocus();
          panel.validate();
          panel.repaint();
       } //EOF addNewComponentOne of this changed central panel's components is a JTabbedPane
    This pane has 3 tabs, each with full tree of containers and components.
    The problem is that when central app panel shows the JTabbedPane, the only way to focus in a component is by mouse click, after that i can use tab key to switch between components, including tabs from pane.
    I cant find a way to force focus so mouse click is not necesary.
    The component parameter in previous code has been a container in any part of app code I've seen it, so far, somewhere in each of this containers is a back button to mantain consistent the navigation. But I need to keep anytime the tab key navigation.
    Also while tab key is not working sometimes hot keys neither work, so fast keyboard navigation crashes completely.
    Is there a way I can fix this? tabs in JTabbedPane cant be selected as components, requestFocus in other components doesnt work, searching in the net shows posts with similar problems but says that it's a bug and need to change to jdk 1.5, I prefer to keep 1.4.2 version at least for a while since app is spreaded to many people and i dont control that.
    Thanks in advance for the help.

    You need to look into the new focus system. Focus always defaults the root of the default FocusTraversalPolicy. You need to define a policy. Then when the window opens focus will default to the tab if defined correctly.

Maybe you are looking for

  • IDOC Message coming from R/3 system to XI , but waits in Qeue

    <b>IDOC Message coming from R/3 system to XI , but waits in Qeue</b> XI doesn't send the message FTP receiver.In XI sxmb_moni  the "c" column contains green flags that mean "message scheduled on outbound side". In smq1 It writes "SYSFAIL" means "Pass

  • Camera raw conversion for photoshop elements 12 . Camera Nikon D4S

    Hi i have an apple Mac version 10.9 os.  I have Adobe photoshop Elements 12.  I just got a new camera Nikon D4S.  Photoshop Elements will not import my RAW phots (NEF) taken with the new D4S camera.  It gives me a message: Could not complete request

  • Calc manager error in EPM

    Hi, After connecting to Calc manager through workspace and trying to expand planning we are getting "could not connect to dimension server. Please make sure that the required servers are started"(its pointing to essbase server) error message. Can any

  • Reg parameter table

    Hi , plz check my below program and exaplain me how to make use of parameter table CLASS cl_abap_objectdescr DEFINITION LOAD. CLASS add DEFINITION.   PUBLIC SECTION.     METHODS add IMPORTING x TYPE i                           y TYPE i               

  • OS X Mountain Lion AirPlay Mirroring

    AirPlay Mirroring is advertised to work on ANY early 2011 or later MacBook Pro. I bought my MacBook Pro on 2-22-2011 yet I am unable to get AirPlay Mirroring working. I made sure that my MacBook Pro SHOULD be able to use AirPlay Mirroring BEFORE I bo