Painting on JTabbedPanes

I have code which reads rectangle tags from an svg file and displays them on a canvas in a tabbed pane, when I first click on the tabbed pane the image appears but when I click on another tab then go back to this tab the rectangle is not there. It does not appear to be repainting. How do I set my tabbed pane up so that when a user clicks on a tab the canvas is repainted?

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Painting
    JTabbedPane tabbedPane;
    public Painting()
        double[][] coords = {
            { 1.0/4, 1.0/4, 1.0/2, 2.0/3 }, { 1.0/3, 1.0/4, 1.0/3, 3.0/8 }
        Color[] colors = { Color.blue, Color.red };
        tabbedPane = new JTabbedPane();
        tabbedPane.addTab("blue", getPanel(coords[0], colors[0]));
        tabbedPane.addTab("red",  getPanel(coords[1], colors[1]));
    private JPanel getPanel(final double[] d, final Color color)
        JPanel panel = new JPanel()
             * swing always calls this method when your component
             * needs to be rendered so whatever you want to paint
             * will always show up if you put the code in here
            protected void paintComponent(Graphics g)
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D)g;
                g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                    RenderingHints.VALUE_ANTIALIAS_ON);
                int w = getWidth();
                int h = getHeight();
                double x      = d[0] * w;
                double y      = d[1] * h;
                double width  = d[2] * w;
                double height = d[3] * h;
                g2.setPaint(color);
                g2.draw(new Rectangle2D.Double(x, y, width, height));
        return panel;
    public static void main(String[] args)
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new Painting().tabbedPane);
        f.setSize(400,400);
        f.setLocation(200,200);
        f.setVisible(true);
}

Similar Messages

  • JTabbedPane cause second paint

    I have a problem with JTabbedPane that has me stumped. When a TabbedPane is displayed, it causes it's parent component to repaint itself. This appears to happen because the TabbedPane wants to paint the contents of it's visible tab. If I don't add any tabs to the TabbedPane, the problem goes away. I have given a simple example to demonstrate.import java.awt.*;
    import javax.swing.*;
    class TabTest
      public static void main(String[] args)
        JFrame frame = new JFrame("TabTest");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("First Tab", new JPanel());
        tabbedPane.addTab("Second Tab", new JPanel());
        JPanel contentPane = new JPanel(new BorderLayout()){
          protected void paintComponent(Graphics g)
            try
              // sleep so we can watch the painting issue occur
              System.out.println("contentPane.paintComponent()");
              Thread.currentThread().sleep(1000);
            catch(Exception e){}
            super.paintComponent(g);
        contentPane.add(tabbedPane, BorderLayout.CENTER);
        frame.setContentPane(contentPane);
        frame.setBounds(300,300,300,300);
        frame.setVisible(true);
    }My only solution so far is to use a CardLayout and simulate a TabbedPane like interface. When the tabs have some components on them, you can see a flicker, which is my main problem with this.

    v1.4.2
    Yes that is what I mean. Only a TabbedPane requires a second paint of the frame. When the tabbedPane has some components on it, requiring more painting, you will notice a flicker when displaying the window. The flicker is gone if your remove all tabs from the tabbedPane. If you get rid of the tabbedPane and put a regular JPanel there, only one paint is performed. Or if you put a JPanel with a cardlayout only one paint is performed.
    In my application, it is actaully a modal JDialog with a borderlayout and the tabbedPane is put in the WEST region. If I do the little sleep(), I can see the borderlayouts CENTER, BOTTOM and NORTH regions painted and then the screen is wipped and finally get the WEST region...the tabbedPane. This requires a second paintComponent() call and several invalidates. This causes an annoying flicker which is only removed by removing all tabs from the tabbedPane or by using a CardLayout instead.

  • Background Painting of "Out of focus" tabbed Panel (JTabbedPane) ?

    Hi
    I would like to add a on going Bar Graph to a JTabbedPane, this works fine if the specific Tab is in Focus, but when the tab is switched, Painting stops!
    How can i ensure the painting continues in the background!
    Here is an example which demo's the problem! Also, watch the standard out...
    Any idea's how to solve this ?
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.util.*;
    public class TestPanel extends JPanel {
        // Define the height and width of the bars. Given by calling process.
        private int height [];
        private int width;
        // Define the starting point of the bar chart and base line.
        private int top = 5;
        private int base = 100 + top;
        private int middle = (base/2)+(top/2);
        private int baseOffset = 3;
        private int indent = 45;
        private int step = (base - top)/10;
        private int baseLen = 0;
        private int tpsArray[];
        private int maxValue;
        private int counter = 0;
        private int value;
        public TestPanel(String server, String file ) {
            tpsArray = new int[32768];
            JFrame f =  new JFrame();
            JTabbedPane t = new JTabbedPane();
            // Set the Content and Window layout
            f.setLayout( new BorderLayout() );
            t.add( panel(), "Tab A");
            t.add( new JLabel("I AM TAB B"), "Tab B");
            f.add( t, BorderLayout.CENTER);
            //f.setExtendedState( Frame.MAXIMIZED_BOTH );
            f.setSize(400,400);
            f.setVisible(true);
        public JPanel panel() {
            // Define the JPanel to hold the graphic
            JPanel panel = new JPanel( new BorderLayout());
            panel.setBackground( Color.white );
            AnnimationModel annimationModel = new AnnimationModel();
            AnimationView animationView = new AnimationView(annimationModel);
            panel.add(animationView, BorderLayout.CENTER);
            return panel;
        private class AnimationView extends JPanel {
            private Dimension d = new Dimension();
            AnimationView(AnnimationModel annimationModel) {
                // Save a reference to the model for use
                // when the view is updated
                annimationModel_ = annimationModel;
                // Listen for the events indicating that the model has changed
                annimationModel_.addObserver(new Observer() {
                    public void update(Observable o, Object arg) {
                        // All we need to do is to get the view to repaint
                        AnimationView.this.repaint();
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = ( Graphics2D ) g;
                baseLen = getPanelWidth() - indent * 2 ;
                System.out.println("Painting Again.... Counter = " + counter  );
                int pos = ( indent + 6 );
                addOutLine(g2d);
                // Update the view based on the information in the model.
                g.setColor(Color.green);
                for ( int i=counter;i>0;i--) {
                    if ( pos > ( baseLen + indent )  ) break;
                    g.fill3DRect( pos, (base-tpsArray), 2, tpsArray[i], true );
    pos = pos + 2;
    tpsArray[counter] = value;
    public int getPanelWidth() {
    d.width = getWidth();
    return d.width;
    public void addOutLine(Graphics2D g2d) {
    // Setup the percentage markings on left vertical bar
    g2d.setColor( Color.GRAY );
    g2d.setFont( new Font("Sanserif", Font.PLAIN, 10));
    g2d.drawString( "0", (indent - 14), base + baseOffset );
    // Display the last TPS rate
    g2d.drawString( "" + maxValue, (indent - 20 ) , top+baseOffset );
    // Display the last TPS rate
    g2d.drawString( "(" + value + ")", 3, base + baseOffset );
    // Draw vertical line from top of bar chart to base line
    g2d.drawLine( indent, top, indent, base + baseOffset );
    // Draw horizontal base line
    g2d.drawLine( indent, base, indent+baseLen, base);
    // Draw horizontal top tick mark
    g2d.drawLine( (indent)-5, top, (indent)+5, top);
    // Draw horizontal tick line at 50% or middle point
    g2d.drawLine( (indent)-5, middle, (indent)+5, middle);
    // Draw horizontal tick at bottom base line
    g2d.drawLine( (indent)-5, base, (indent)+5, base);
    // Draw the dotted lines across the bar chart.
    g2d.setColor( new Color( 160,223,233));
    float dashes[] = { 1 };
    g2d.setStroke( new BasicStroke( 1, BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, 0, dashes, 0));
    for (int i=base; i>=top ;i=i-step) {
    g2d.drawLine( indent + 6, i, (indent+baseLen), i );
    // The saved reference to the model
    private AnnimationModel annimationModel_;
    private class AnnimationModel extends Observable {
    // private Shared sharedRef = new Shared();
    AnnimationModel() {
    Thread annimationThread = new Thread() {
    public void run() {
    while(true) {
    try {
    Thread.sleep(1000);
    } catch ( Exception e ) {
    value = 1 + (int) (Math.random() * 100 );
    counter++;
    // Notify the observers
    setChanged();
    notifyObservers();
    annimationThread.start();
    // Simple test main
    static public void main(String[] args) {
    TestPanel app = new TestPanel(null,null);
    Thanks,
    Rob

    How can i ensure the painting continues in the background! Well, I don't think you force painting since Swing appears to be smart enough to not paint a component that isn't visible.
    However, you should be able to do your painting on an offscreen image. So your offscreen image will be continually update. Then your paintComponent(...) method simply paints this offscreen image.
    This posting should get your started using this approach:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607073

  • Underlying JTabbedPane paints through

    I have a problem where i'm updating some Components on a tab and when that tab is not the currently selected tab the components paint through onto whatever tab is selected. I've tried setting the visibility of the JPanels that are changing to false and then true when that tab is selected but that doesn't seem to work. Any ideas?

    The tab where I'm updating the components is made up of 3 Jpanels, each one is updated with a chart component (the chart is removed, a new one is created and then added to the JPanel). I am using absolute positioning (I calculate the x,y coords based on the chart size and center it in the JPanel). It only occurs when the charts are being updated and a different tab is selected and as soon as I switch to a diferent tab everything redraws fine.

  • JTabbedPane: Exception occurred during event dispatching:

    Hi,
    I have a JTabbedPane where the tabs can be added dynamically by the method:
    private void addNewTab(JTable aTable) throws java.lang.NullPointerException
    final JTable t = aTable;
    Thread addTab = new Thread()
    public void run()
    JScrollPane scroller = new JScrollPane();
    JTable table;
    if (t==null)
    table = new JTable(columns, 0);
    else
    table = t;
    table.setColumnsEditable(colEditable);
    cachedTables.addElement(table);
    scroller.getViewport().setView(table);
    jtp.insertTab("Tab " + cachedTables.size(), null, scroller, "Tab", cachedTables.size()-1);
    jtp.updateUI();
    SwingUtilities.invokeLater(new Runnable()
    public void run()
    jtp.setSelectedIndex(cachedTables.size()-1);
    jtp.validate();
    addTab.start();
    The problem is that occasionally (20% of the times) I receive this exception:
    Exception occurred during event dispatching:
    java.lang.NullPointerException
         at javax.swing.plaf.basic.BasicTabbedPaneUI.rotateInsets(BasicTabbedPaneUI.java:1159)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.getTabAreaInsets(BasicTabbedPaneUI.java:951)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.calculateTabAreaHeight(BasicTabbedPaneUI.java:924)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.paintContentBorder(BasicTabbedPaneUI.java:637)
         at javax.swing.plaf.basic.BasicTabbedPaneUI.paint(BasicTabbedPaneUI.java:358)
         at javax.swing.plaf.ComponentUI.update(ComponentUI.java:39)
         at javax.swing.JComponent.paintComponent(JComponent.java:395)
         at javax.swing.JComponent.paint(JComponent.java:687)
         at javax.swing.JComponent.paintChildren(JComponent.java:498)
         at javax.swing.JComponent.paint(JComponent.java:696)
         at javax.swing.JComponent.paintWithBuffer(JComponent.java:3878)
         at javax.swing.JComponent._paintImmediately(JComponent.java:3821)
         at javax.swing.JComponent.paintImmediately(JComponent.java:3672)
         at javax.swing.RepaintManager.paintDirtyRegions(RepaintManager.java:370)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:124)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:154)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:337)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:131)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:98)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:85)
    Does none know, how I can solve the problem?
    Thanks,
    Diego.

    Fix the NullPointerException. The stack trace tells you the line that caused the problem.

  • Painting in the backgroung

    all,
    I'm having a problem with drawing an image in a JTabbedPane.
    Consider a JTabbedPane with two JPanel as tabs.
    in first tab I have a text field in the second a JComboBox and a small JPanel
    (let's call it the picturePanel)
    Items selected in the JComboBox trigger the painting of an image in the
    picturePanel.
    At init :
    JComboBox is disabled and picturePanel does not contain anything.
    JTextField is empty
    When a user types a value in the text field it enables the JComboBox
    in second tab.
    The user then goes to second tab and selects a picture which is correctly drawn.
    Now lets consider that the user goes back to first tab and modifies the value in the textfield.
    I then want to restore the state of the components of second tab as they were at the init.
    No problem for the JComboBox, the problem is for the picturePanel.
    How do I remove the picture in the Graphics object of the picturePanel ?
    I simply tryed to fill a rectangle in place of the picture but as the selected tab is the first one,
    the rectangle is displayed on this first tab !!!
    I tried to integrate the condition isVisible() to the picturePanel before filling the rectangle
    but it did not change anything.
    I have an ugly way which is to remove the picturePanel and add a new one but
    I'd prefer to implement one of your suggestions.
    thx.

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import javax.swing.event.*;
    public class TabTalk
        public static void main(String[] args)
            JTextField textField = new JTextField(16);
            final JPanel fieldPanel = new JPanel();
            fieldPanel.add(textField);
            String[] fileNames = {
                "cougar.jpg", "redfox.jpg", "bclynx.jpg", "greathornedowl.jpg"
            final ImageTabComponent imageComponent = new ImageTabComponent();
            final JComboBox comboBox = new JComboBox(fileNames);
            comboBox.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    String fileName = (String)comboBox.getSelectedItem();
                    imageComponent.setImage(fileName);
            JPanel imagePanel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(5,5,5,5);
            gbc.weightx = 1.0;
            gbc.gridwidth = gbc.REMAINDER;
            imagePanel.add(comboBox, gbc);
            gbc.weighty = 1.0;
            gbc.fill = gbc.BOTH;
            imagePanel.add(new JScrollPane(imageComponent), gbc);
            final JTabbedPane tabbedPane = new JTabbedPane();
            tabbedPane.addTab("textfield", fieldPanel);
            tabbedPane.addTab("image", imagePanel);
            tabbedPane.addChangeListener(new ChangeListener()
                public void stateChanged(ChangeEvent e)
                    Component c = tabbedPane.getSelectedComponent();
                    if(c.equals(fieldPanel))
                        imageComponent.setImage(null);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(tabbedPane);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    class ImageTabComponent extends JPanel
        BufferedImage image;
        public ImageTabComponent()
            image = null;
            setBackground(Color.black);
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                                RenderingHints.VALUE_INTERPOLATION_BICUBIC);
            int w = getWidth();
            int h = getHeight();
            if(image != null)
                int imageWidth = image.getWidth();
                int imageHeight = image.getHeight();
                int x = (w - imageWidth)/2;
                int y = (h - imageHeight)/2;
                AffineTransform at = AffineTransform.getTranslateInstance(x, y);
                g2.drawRenderedImage(image, at);
        public Dimension getPreferredSize()
            Dimension d = new Dimension(10,10);
            if(image != null)
                d = new Dimension(image.getWidth(), image.getHeight());
            return d;
        public void setImage(String fileName)
            if(fileName != null)
                loadImage(fileName);
            else
                image = null;
            revalidate();
            repaint();
        private void loadImage(String fileName)
            String prefix = "images/";
            try
                URL url = getClass().getResource(prefix + fileName);
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.out.println("url: " + mue.getMessage());
            catch(IOException ioe)
               System.out.println("read: " + ioe.getMessage());
    }

  • How to make individual tabs on a JTabbedPane, a different colour?

    Hi,
    Is there a way to set the background colour to INDIVIDUAL tabs on a tabbed pane so that I can have a nice range of colours across my tabs?
    DLawton.

    hey D,
    I've got two ideas for you:
    1. Swing has implementable L&F (skins) for all components. You could create one for you JTabbedPane as a subclass from some existing UI L&F
    2. you can always do this in your paint method. Might be tough though

  • 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 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.

  • A few questions regarding BorderLayout, JTabbedPane and JFrame.

    Hello,
    I'm after a little help. I want to know the following:
    1)
    How to you add a gap on the far left and far right so that the components at PAGE_START and PAGE_END when using BorderLayout have visible borders. I have tried the Constructor which lets you specific hGap and vGap but this does not work, I assume it is only when butting components together.
    2)
    When using JTabbedPanes with option
    setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT );is there a way to control painting of the Scroller which scrolls through the tabs? I am currently using a custom UI (subclassing BasicTabbedPaneUI) to paint my tabs however I can not work out how to paint the Scroller.
    3)
    How to I add a custom JFrame Border and remove the blue XP border? Do I need to setUndectored and add my own Icons? I want to achieve something along the lines of what you can see here
    https://substance.dev.java.net/images/screenshots/themes/skins/business1.png
    I will be using a custom L&F although not Substance and currently my L&F does not paint the border/Decorations on the Frame.
    Here is a picture of my app, outlining my problems.
    http://img91.imageshack.us/my.php?image=exampletz1.jpg
    A nudge in the right direction on any of these would be great.
    Thanks

    Hello,
    I'm after a little help. I want to know the
    following:
    1)
    How to you add a gap on the far left and far right so
    that the components at PAGE_START and PAGE_END when
    using BorderLayout have visible borders. I have
    tried the Constructor which lets you specific hGap
    and vGap but this does not work, I assume it is only
    when butting components together. agree vgap and hgap increase the vertical and horizontal distances between objects added to the panel that uses border layout.
    Why not do setBorder(BorderFactory.createEmptyBorder(.....) to do this for you?

  • Replacing Panels in JTabbedPane

    I'll try to explain this coherently... hopefully it makes sense.
    - I have a Jtabbedpane with multiple tabs. Tab1 and Tab2.
    - Panel1 and Panel2 are associted with Tab1 and Tab2 respectively.
    - I have a button on Panel2 and when it's pressed I call setcomponentat() to set Panel3 to be displayed on Tab2. Panel2 goes away.
    That works great.
    - Then if you click on Tab1 and then back to Tab2, I have a change listener that listens for the click back to Tab2 and "resets" the tab to again show Panel2 (again with setcomponentat())
    Which also works great.
    However, at this point the button on Panel2 that sets Tab2 to display Panel3.... no longer works. Well, to be more accurate, it works, the function is called (verified by system.out ouput) and Panel2 is no longer "interactive" but Panel3 is not painted.
    Any idea why it works at first, but not after the panels are switched out a few times?

    Hmm.... I don't think that is my problem. I was trying to avoid posting all the code.... but whatever.
    Much of this is Netbeans generated, so I apologize for any readability issues:
    public class TheBox extends javax.swing.JFrame implements ChangeListener {
        // Implement custom change listener
        public void stateChanged(ChangeEvent evt)
            JTabbedPane tabbedPane = (JTabbedPane)evt.getSource();
            // Get current tab
         int tab = tabbedPane.getSelectedIndex();
            System.out.println("Tab is: " + (tab+1));
            if (tab == 1)
                {TheBoxTabbedPane.setComponentAt(1,SellTicketsPanel);}
            if (tab == 2)
                {TheBoxTabbedPane.setComponentAt(2,ManageProductionsPanel);}
            if (tab == 3)
                TheBoxTabbedPane.setComponentAt(3,ReportsPanel);
                jPanel1.setVisible(false);
                ReportsPanel.repaint();
                ReportsPanel.revalidate();
        /** Creates new form TheBox */
        public TheBox()
            initComponents();
            jPanel1.setVisible(false);
            // Register a change listener
            TheBoxTabbedPane.addChangeListener(this);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            TheBoxTabbedPane = new javax.swing.JTabbedPane();
            HomePanel = new javax.swing.JPanel();
            Stage = new javax.swing.JButton();
            WelcomBanner = new javax.swing.JButton();
            ExitButton = new javax.swing.JButton();
            SellTicketsPanel = new javax.swing.JPanel();
            ManageProductionsPanel = new javax.swing.JPanel();
            ManageProductionsHeading = new javax.swing.JButton();
            CreateProductionButton = new javax.swing.JButton();
            DeleteProductionButton = new javax.swing.JButton();
            SearchProductionButton = new javax.swing.JButton();
            ReleaseTicketsButton = new javax.swing.JButton();
            ReportsPanel = new javax.swing.JPanel();
            PrintReportsHeading = new javax.swing.JButton();
            TicketReportsButton = new javax.swing.JButton();
            AddressReportsButton = new javax.swing.JButton();
            PhoneReportsButton = new javax.swing.JButton();
            jPanel1 = new javax.swing.JPanel();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            TheBoxTabbedPane.setBackground(new java.awt.Color(255, 255, 255));
            HomePanel.setBackground(new java.awt.Color(0, 0, 0));
            Stage.setBackground(new java.awt.Color(0, 0, 0));
            Stage.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/stage.jpg"));
            Stage.setBorderPainted(false);
            WelcomBanner.setBackground(new java.awt.Color(0, 0, 0));
            WelcomBanner.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/welcome.gif"));
            WelcomBanner.setBorderPainted(false);
            ExitButton.setBackground(new java.awt.Color(255, 255, 255));
            ExitButton.setText("Exit");
            ExitButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    ExitButtonActionPerformed(evt);
            org.jdesktop.layout.GroupLayout HomePanelLayout = new org.jdesktop.layout.GroupLayout(HomePanel);
            HomePanel.setLayout(HomePanelLayout);
            HomePanelLayout.setHorizontalGroup(
                HomePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(HomePanelLayout.createSequentialGroup()
                    .addContainerGap(145, Short.MAX_VALUE)
                    .add(HomePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, HomePanelLayout.createSequentialGroup()
                            .add(Stage)
                            .add(127, 127, 127))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, HomePanelLayout.createSequentialGroup()
                            .add(WelcomBanner)
                            .add(112, 112, 112))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, HomePanelLayout.createSequentialGroup()
                            .add(ExitButton)
                            .add(282, 282, 282))))
            HomePanelLayout.setVerticalGroup(
                HomePanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(HomePanelLayout.createSequentialGroup()
                    .add(111, 111, 111)
                    .add(Stage)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(WelcomBanner)
                    .add(54, 54, 54)
                    .add(ExitButton)
                    .addContainerGap(45, Short.MAX_VALUE))
            TheBoxTabbedPane.addTab("Home", HomePanel);
            SellTicketsPanel.setBackground(new java.awt.Color(0, 0, 0));
            org.jdesktop.layout.GroupLayout SellTicketsPanelLayout = new org.jdesktop.layout.GroupLayout(SellTicketsPanel);
            SellTicketsPanel.setLayout(SellTicketsPanelLayout);
            SellTicketsPanelLayout.setHorizontalGroup(
                SellTicketsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 641, Short.MAX_VALUE)
            SellTicketsPanelLayout.setVerticalGroup(
                SellTicketsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 464, Short.MAX_VALUE)
            TheBoxTabbedPane.addTab("Sell Tickets", SellTicketsPanel);
            ManageProductionsPanel.setBackground(new java.awt.Color(0, 0, 0));
            ManageProductionsHeading.setBackground(new java.awt.Color(0, 0, 0));
            ManageProductionsHeading.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/manage_productions_heading.gif"));
            ManageProductionsHeading.setBorderPainted(false);
            CreateProductionButton.setBackground(new java.awt.Color(0, 0, 0));
            CreateProductionButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_create_a_new_pro.gif"));
            CreateProductionButton.setBorderPainted(false);
            CreateProductionButton.setRolloverEnabled(true);
            CreateProductionButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_create_a_new_pro.gif"));
            DeleteProductionButton.setBackground(new java.awt.Color(0, 0, 0));
            DeleteProductionButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_delete_a_pro.gif"));
            DeleteProductionButton.setBorderPainted(false);
            DeleteProductionButton.setRolloverEnabled(true);
            DeleteProductionButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_delete_a_pro.gif"));
            SearchProductionButton.setBackground(new java.awt.Color(0, 0, 0));
            SearchProductionButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_search_pro.gif"));
            SearchProductionButton.setBorderPainted(false);
            SearchProductionButton.setRolloverEnabled(true);
            SearchProductionButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_search_pro.gif"));
            ReleaseTicketsButton.setBackground(new java.awt.Color(0, 0, 0));
            ReleaseTicketsButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_release_a_ticket.gif"));
            ReleaseTicketsButton.setBorderPainted(false);
            ReleaseTicketsButton.setRolloverEnabled(true);
            ReleaseTicketsButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_release_a_ticket.gif"));
            org.jdesktop.layout.GroupLayout ManageProductionsPanelLayout = new org.jdesktop.layout.GroupLayout(ManageProductionsPanel);
            ManageProductionsPanel.setLayout(ManageProductionsPanelLayout);
            ManageProductionsPanelLayout.setHorizontalGroup(
                ManageProductionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, ManageProductionsPanelLayout.createSequentialGroup()
                    .addContainerGap(164, Short.MAX_VALUE)
                    .add(ManageProductionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(ManageProductionsHeading)
                        .add(ManageProductionsPanelLayout.createSequentialGroup()
                            .add(12, 12, 12)
                            .add(ManageProductionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                .add(DeleteProductionButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 240, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(CreateProductionButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 240, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(SearchProductionButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 240, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                .add(ReleaseTicketsButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 240, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))))
                    .add(193, 193, 193))
            ManageProductionsPanelLayout.setVerticalGroup(
                ManageProductionsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(ManageProductionsPanelLayout.createSequentialGroup()
                    .add(48, 48, 48)
                    .add(ManageProductionsHeading)
                    .add(15, 15, 15)
                    .add(CreateProductionButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(DeleteProductionButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(SearchProductionButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(ReleaseTicketsButton)
                    .addContainerGap(116, Short.MAX_VALUE))
            TheBoxTabbedPane.addTab("Manage Productions", ManageProductionsPanel);
            ReportsPanel.setBackground(new java.awt.Color(0, 0, 0));
            PrintReportsHeading.setBackground(new java.awt.Color(0, 0, 0));
            PrintReportsHeading.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/print_reports_heading.gif"));
            PrintReportsHeading.setBorderPainted(false);
            TicketReportsButton.setBackground(new java.awt.Color(0, 0, 0));
            TicketReportsButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_ticket_reports.gif"));
            TicketReportsButton.setBorderPainted(false);
            TicketReportsButton.setRolloverEnabled(true);
            TicketReportsButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_ticket_reports.gif"));
            TicketReportsButton.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    TicketReportsButtonActionPerformed(evt);
            AddressReportsButton.setBackground(new java.awt.Color(0, 0, 0));
            AddressReportsButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_address_reports.gif"));
            AddressReportsButton.setBorderPainted(false);
            AddressReportsButton.setRolloverEnabled(true);
            AddressReportsButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_address_reports.gif"));
            PhoneReportsButton.setBackground(new java.awt.Color(0, 0, 0));
            PhoneReportsButton.setIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/off_phone_reports.gif"));
            PhoneReportsButton.setBorderPainted(false);
            PhoneReportsButton.setRolloverEnabled(true);
            PhoneReportsButton.setRolloverIcon(new javax.swing.ImageIcon("/home/bvs/java_projects/JavaApplication1/src/javaapplication1/Box Images/on_phone_reports.gif"));
            org.jdesktop.layout.GroupLayout ReportsPanelLayout = new org.jdesktop.layout.GroupLayout(ReportsPanel);
            ReportsPanel.setLayout(ReportsPanelLayout);
            ReportsPanelLayout.setHorizontalGroup(
                ReportsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(ReportsPanelLayout.createSequentialGroup()
                    .add(149, 149, 149)
                    .add(ReportsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(PhoneReportsButton)
                        .add(AddressReportsButton)
                        .add(TicketReportsButton)
                        .add(PrintReportsHeading))
                    .addContainerGap(208, Short.MAX_VALUE))
            ReportsPanelLayout.setVerticalGroup(
                ReportsPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(ReportsPanelLayout.createSequentialGroup()
                    .add(49, 49, 49)
                    .add(PrintReportsHeading)
                    .add(24, 24, 24)
                    .add(TicketReportsButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(AddressReportsButton)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(PhoneReportsButton)
                    .addContainerGap(165, Short.MAX_VALUE))
            TheBoxTabbedPane.addTab("Reports", ReportsPanel);
            jPanel1.setBackground(new java.awt.Color(255, 0, 204));
            jPanel1.setVisible(false);
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 629, Short.MAX_VALUE)
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(0, 56, Short.MAX_VALUE)
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(TheBoxTabbedPane)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(TheBoxTabbedPane, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 491, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
            pack();
        }// </editor-fold>                       
        private void TicketReportsButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        System.out.println("working");
        jPanel1.setVisible(true);
        TheBoxTabbedPane.setComponentAt(3,jPanel1);
        ReportsPanel.repaint();
        ReportsPanel.revalidate();
        private void ExitButtonActionPerformed(java.awt.event.ActionEvent evt) {                                          
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TheBox().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JButton AddressReportsButton;
        private javax.swing.JButton CreateProductionButton;
        private javax.swing.JButton DeleteProductionButton;
        private javax.swing.JButton ExitButton;
        private javax.swing.JPanel HomePanel;
        private javax.swing.JButton ManageProductionsHeading;
        private javax.swing.JPanel ManageProductionsPanel;
        private javax.swing.JButton PhoneReportsButton;
        private javax.swing.JButton PrintReportsHeading;
        private javax.swing.JButton ReleaseTicketsButton;
        private javax.swing.JPanel ReportsPanel;
        private javax.swing.JButton SearchProductionButton;
        private javax.swing.JPanel SellTicketsPanel;
        private javax.swing.JButton Stage;
        private javax.swing.JTabbedPane TheBoxTabbedPane;
        private javax.swing.JButton TicketReportsButton;
        private javax.swing.JButton WelcomBanner;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                  
    }

  • Repaint problems with canavses in JTabbedPane

    Basically I have a JTabbedPane with Canvases in the tabs, and when I select a tab I want the appropriate canvas to draw itself. At the moment I have a simple grid set up to be displayed, which appears on the selected canvas when I start the program, but then when I change tabs only flashes up briefly before disappearing. Heres the code, imports left out:
    Creates the window
    public class GUI {
         public static final int WIDTH=900;
         public static final int HEIGHT=600;
         public GUI() {
              JFrame frame = new JFrame("MapMaker");
              frame.setVisible(true);
              frame.setIgnoreRepaint(true);
              CanvasTab tabbedPane = new CanvasTab();
              MapCanvas mc1 = new MapCanvas();
              tabbedPane.addTab("Layer 1", mc1);
              MapCanvas mc2 = new MapCanvas();
              tabbedPane.addTab("Layer 2", mc2);               
              JPanel leftPanel = new JPanel();
              leftPanel.setBackground(Color.RED);
              leftPanel.setPreferredSize(new Dimension(200, HEIGHT));
              JPanel rightPanel = new JPanel();
              rightPanel.setBackground(Color.BLUE);
              rightPanel.setPreferredSize(new Dimension(WIDTH-200, HEIGHT));          
              rightPanel.add(tabbedPane, BorderLayout.CENTER);
              rightPanel.setIgnoreRepaint(true);
              frame.add(leftPanel, BorderLayout.WEST);
              frame.add(rightPanel, BorderLayout.EAST);     
              frame.pack();
              mc1.makeBuffers(2);
              mc1.drawContent();          
              mc2.makeBuffers(2);
              tabbedPane.addChangeListener(new TabChangeListener(tabbedPane));
         public static void main(String[] args) {
              GUI g = new GUI();
    }The tabbed pane
    public class CanvasTab extends JTabbedPane {
         public CanvasTab() {
              setIgnoreRepaint(true);
    }The canvas
    public class MapCanvas extends Canvas {
         private BufferStrategy strategy;
         public MapCanvas() {
              setPreferredSize(new Dimension(640, 480));
         public void drawGrid() {
              Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
              g.setColor(Color.blue);
              for (int i=1; i<20; i++) {
                   g.drawLine(i*32, 0, i*32, 480);
              for (int i=1; i<15; i++) {
                   g.drawLine(0, i*32, 640, i*32);
         public void drawContent() {
              drawGrid();
              strategy.show();
         public void makeBuffers(int noBuffs) {
              createBufferStrategy(noBuffs);
              strategy = getBufferStrategy();
              setIgnoreRepaint(true);
    }The change listener
    public class TabChangeListener implements ChangeListener{
         private JTabbedPane tabPane;
         public TabChangeListener(JTabbedPane pane) {
              tabPane = pane;
         public void stateChanged(ChangeEvent e) {
              //doesn't work at all, this is the functionality I want eventually
                    //get the tab just selected
              //MapCanvas c = (MapCanvas) tabPane.getSelectedComponent();
              //c.drawContent();
              //grid only flashes up for a split second
              MapCanvas c = (MapCanvas) tabPane.getComponent(0);
              c.drawContent();
              MapCanvas d = (MapCanvas) tabPane.getComponent(1);
              d.drawContent();
    }Thanks

    General rule is don't mix AWT component with Swing components.
    Use a JComponent instead of a Canvas for custom painting.

  • JButton in jTabbedPane

    Hi everyone,
    I just wanna know if there is pain-less manner to add an exit button to the title of each tab in a jtabbedPane or not. Just like the tabs that are available in browsers with tab browsing feature, like Firefox an IE 6+, which contain a small button at the right side of each tab that closes the corresponding tab.
    I think that if there isn't such feature included in jTabbedPane, one solution might be to use a set of jLables as tabs and use a panel with box layout as the panes, so that i could add some buttons to the labels. But I hope the jtabbedPane already gives us the ability to do so.
    Please tell me if U have any other info,
    thx in advance,
    Capitan Haddock

    I believe JDK6 allows you to add components to each tab.
    Otherwise you can search the forum. There are examples of painting an "X" to represent a close icon.

  • Button in JTabbedPane Title

    Hi all
    I am Using JTabbedPane I need to include button for close within every tab. How I Do this one using swings

    hi!
    for that you need to use the javax.swing.plaf.basic.BasicTabbedPaneUI class. i wrote
    package una.common.file.vc.gui.control;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Event;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Insets;
    import java.awt.LayoutManager;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.Shape;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ContainerEvent;
    import java.awt.event.ContainerListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.awt.image.BufferedImage;
    import java.util.EventListener;
    import java.util.Hashtable;
    import java.util.Vector;
    import javax.swing.AbstractAction;
    import javax.swing.ActionMap;
    import javax.swing.Icon;
    import javax.swing.InputMap;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JTabbedPane;
    import javax.swing.JViewport;
    import javax.swing.KeyStroke;
    import javax.swing.SwingConstants;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.border.Border;
    import javax.swing.border.SoftBevelBorder;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    import javax.swing.plaf.ActionMapUIResource;
    import javax.swing.plaf.ComponentUI;
    import javax.swing.plaf.InputMapUIResource;
    import javax.swing.plaf.UIResource;
    import javax.swing.plaf.basic.BasicArrowButton;
    import javax.swing.plaf.basic.BasicHTML;
    import javax.swing.plaf.basic.BasicTabbedPaneUI;
    import javax.swing.text.View;
    import una.common.file.vc.gui.VCResource;
    * UI for <code>VCTabbedPane</code>.
    * <p>
    * Credits to:
    public class VCTabPaneUI extends BasicTabbedPaneUI implements ActionListener
         // Instance variables initialized at installation
         private ContainerListener          containerListener;
         private Vector                         htmlViews;
         private Hashtable                    mnemonicToIndexMap;
          * InputMap used for mnemonics. Only non-null if the JTabbedPane has
          * mnemonics associated with it. Lazily created in initMnemonics.
         private InputMap                    mnemonicInputMap;
         // For use when tabLayoutPolicy = SCROLL_TAB_LAYOUT
         protected ScrollableTabSupport     tabScroller;
         private int                              tabCount;
         protected MyMouseMotionListener     motionListener;
         // UI creation
         private static final int          INACTIVE                    = 0;
         private static final int          OVER                         = 1;
         private static final int          PRESSED                         = 2;
         protected static final int          BUTTONSIZE                    = 15;
         protected static final int          WIDTHDELTA                    = 5;
         private static final Border          PRESSEDBORDER               = new SoftBevelBorder(
                                                                                         SoftBevelBorder.LOWERED);
         private static final Border          OVERBORDER                    = new SoftBevelBorder(
                                                                                         SoftBevelBorder.RAISED);
         private BufferedImage               closeImgB;
         private BufferedImage               closeImgI;
         private JButton                         closeB;
         private int                              overTabIndex               = -1;
         private int                              closeIndexStatus          = INACTIVE;
         private int                              maxIndexStatus               = INACTIVE;
         private boolean                         mousePressed               = false;
         private boolean                         isCloseButtonEnabled     = true;
         private JPopupMenu                    actionPopupMenu               = null;
         private JMenuItem                    closeItem                    = null;
         private JMenuItem                    closeOthers                    = null;
         private JMenuItem                    closeAll                    = null;
         public VCTabPaneUI()
              super();
              closeImgB = new BufferedImage(BUTTONSIZE, BUTTONSIZE,
                        BufferedImage.TYPE_4BYTE_ABGR);
              closeImgI = new BufferedImage(BUTTONSIZE, BUTTONSIZE,
                        BufferedImage.TYPE_4BYTE_ABGR);
              closeB = new JButton("X");
              closeB.setSize(BUTTONSIZE, BUTTONSIZE);
              actionPopupMenu = new JPopupMenu();
              closeItem = new JMenuItem(VCResource.getString("CLOSE"));
              closeOthers = new JMenuItem(VCResource.getString("CLOSE_OTHERS"));
              closeAll = new JMenuItem(VCResource.getString("CLOSE_ALL"));
              actionPopupMenu.add(closeItem);
              actionPopupMenu.add(closeOthers);
              actionPopupMenu.add(closeAll);
              closeItem.addActionListener(this);
              closeOthers.addActionListener(this);
              closeAll.addActionListener(this);
         protected boolean isOneActionButtonEnabled()
              return isCloseButtonEnabled;
         public boolean isCloseEnabled()
              return isCloseButtonEnabled;
         public void setCloseIcon(boolean b)
              isCloseButtonEnabled = b;
         protected int calculateTabWidth(int tabPlacement, int tabIndex,
                   FontMetrics metrics)
              int delta = 2;
              if (!isOneActionButtonEnabled())
                   delta += 6;
              else
                   if (isCloseButtonEnabled)
                        delta += BUTTONSIZE + WIDTHDELTA;
              return super.calculateTabWidth(tabPlacement, tabIndex, metrics) + delta;
         protected int calculateTabHeight(int tabPlacement, int tabIndex,
                   int fontHeight)
              return super.calculateTabHeight(tabPlacement, tabIndex, fontHeight) + 5;
         protected void layoutLabel(int tabPlacement, FontMetrics metrics,
                   int tabIndex, String title, Icon icon, Rectangle tabRect,
                   Rectangle iconRect, Rectangle textRect, boolean isSelected)
              textRect.x = textRect.y = iconRect.x = iconRect.y = 0;
              View v = getTextViewForTab(tabIndex);
              if (v != null)
                   tabPane.putClientProperty("html", v);
              SwingUtilities.layoutCompoundLabel((JComponent) tabPane, metrics,
                        title, icon, SwingUtilities.CENTER, SwingUtilities.LEFT,
                        SwingUtilities.CENTER, SwingUtilities.CENTER, tabRect,
                        iconRect, textRect, textIconGap);
              tabPane.putClientProperty("html", null);
              iconRect.x = tabRect.x + 8;
              textRect.x = iconRect.x + iconRect.width + textIconGap;
         protected MouseListener createMouseListener()
              return new MyMouseHandler();
         protected ScrollableTabButton createScrollableTabButton(int direction)
              return new ScrollableTabButton(direction);
         protected Rectangle newCloseRect(Rectangle rect)
              int dx = rect.x + rect.width;
              int dy = (rect.y + rect.height) / 2 - 6;
              return new Rectangle(dx - BUTTONSIZE - WIDTHDELTA, dy, BUTTONSIZE,
                        BUTTONSIZE);
         protected Rectangle newMaxRect(Rectangle rect)
              int dx = rect.x + rect.width;
              int dy = (rect.y + rect.height) / 2 - 6;
              if (isCloseButtonEnabled)
                   dx -= BUTTONSIZE;
              return new Rectangle(dx - BUTTONSIZE - WIDTHDELTA, dy, BUTTONSIZE,
                        BUTTONSIZE);
         protected void updateOverTab(int x, int y)
              if (overTabIndex != (overTabIndex = getTabAtLocation(x, y)))
                   tabScroller.tabPanel.repaint();
         protected void updateCloseIcon(int x, int y)
              if (overTabIndex != -1)
                   int newCloseIndexStatus = INACTIVE;
                   Rectangle closeRect = newCloseRect(rects[overTabIndex]);
                   if (closeRect.contains(x, y))
                        newCloseIndexStatus = mousePressed ? PRESSED : OVER;
                   if (closeIndexStatus != (closeIndexStatus = newCloseIndexStatus))
                        tabScroller.tabPanel.repaint();
    //     protected void updateMaxIcon(int x, int y)
    //          if (overTabIndex != -1)
    //               int newMaxIndexStatus = INACTIVE;
    //               Rectangle maxRect = newMaxRect(rects[overTabIndex]);
    //               if (maxRect.contains(x, y))
    //                    newMaxIndexStatus = mousePressed ? PRESSED : OVER;
    //               if (maxIndexStatus != (maxIndexStatus = newMaxIndexStatus))
    //                    tabScroller.tabPanel.repaint();
         private void setTabIcons(int x, int y)
              // if the mouse isPressed
              if (!mousePressed)
                   updateOverTab(x, y);
              if (isCloseButtonEnabled)
                   updateCloseIcon(x, y);
         public static ComponentUI createUI(JComponent c)
              return new VCTabPaneUI();
          * Invoked by <code>installUI</code> to create a layout manager object to
          * manage the <code>JTabbedPane</code>.
          * @return a layout manager object
          * @see TabbedPaneLayout
          * @see javax.swing.JTabbedPane#getTabLayoutPolicy
         protected LayoutManager createLayoutManager()
              return new TabbedPaneScrollLayout();
          * In an attempt to preserve backward compatibility for programs which have
          * extended BasicTabbedPaneUI to do their own layout, the UI uses the
          * installed layoutManager (and not tabLayoutPolicy) to determine if
          * scrollTabLayout is enabled.
          * Creates and installs any required subcomponents for the JTabbedPane.
          * Invoked by installUI.
          * @since 1.4
         protected void installComponents()
              if (tabScroller == null)
                   tabScroller = new ScrollableTabSupport(tabPane.getTabPlacement());
                   tabPane.add(tabScroller.viewport);
                   tabPane.add(tabScroller.scrollForwardButton);
                   tabPane.add(tabScroller.scrollBackwardButton);
          * Removes any installed subcomponents from the JTabbedPane. Invoked by
          * uninstallUI.
          * @since 1.4
         protected void uninstallComponents()
              tabPane.remove(tabScroller.viewport);
              tabPane.remove(tabScroller.scrollForwardButton);
              tabPane.remove(tabScroller.scrollBackwardButton);
              tabScroller = null;
         protected void installListeners()
              if ((propertyChangeListener = createPropertyChangeListener()) != null)
                   tabPane.addPropertyChangeListener(propertyChangeListener);
              if ((tabChangeListener = createChangeListener()) != null)
                   tabPane.addChangeListener(tabChangeListener);
              if ((mouseListener = createMouseListener()) != null)
                   tabScroller.tabPanel.addMouseListener(mouseListener);
              if ((focusListener = createFocusListener()) != null)
                   tabPane.addFocusListener(focusListener);
              // PENDING(api) : See comment for ContainerHandler
              if ((containerListener = new ContainerHandler()) != null)
                   tabPane.addContainerListener(containerListener);
                   if (tabPane.getTabCount() > 0)
                        htmlViews = createHTMLVector();
              if ((motionListener = new MyMouseMotionListener()) != null)
                   tabScroller.tabPanel.addMouseMotionListener(motionListener);
         protected void uninstallListeners()
              if (mouseListener != null)
                   tabScroller.tabPanel.removeMouseListener(mouseListener);
                   mouseListener = null;
              if (motionListener != null)
                   tabScroller.tabPanel.removeMouseMotionListener(motionListener);
                   motionListener = null;
              if (focusListener != null)
                   tabPane.removeFocusListener(focusListener);
                   focusListener = null;
              // PENDING(api): See comment for ContainerHandler
              if (containerListener != null)
                   tabPane.removeContainerListener(containerListener);
                   containerListener = null;
                   if (htmlViews != null)
                        htmlViews.removeAllElements();
                        htmlViews = null;
              if (tabChangeListener != null)
                   tabPane.removeChangeListener(tabChangeListener);
                   tabChangeListener = null;
              if (propertyChangeListener != null)
                   tabPane.removePropertyChangeListener(propertyChangeListener);
                   propertyChangeListener = null;
         protected ChangeListener createChangeListener()
              return new TabSelectionHandler();
         protected void installKeyboardActions()
              InputMap km = getMyInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
              SwingUtilities.replaceUIInputMap(tabPane,
                        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, km);
              km = getMyInputMap(JComponent.WHEN_FOCUSED);
              SwingUtilities.replaceUIInputMap(tabPane, JComponent.WHEN_FOCUSED, km);
              ActionMap am = createMyActionMap();
              SwingUtilities.replaceUIActionMap(tabPane, am);
              tabScroller.scrollForwardButton.setAction(am
                        .get("scrollTabsForwardAction"));
              tabScroller.scrollBackwardButton.setAction(am
                        .get("scrollTabsBackwardAction"));
         InputMap getMyInputMap(int condition)
              if (condition == JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)
                   return (InputMap) UIManager.get("TabbedPane.ancestorInputMap");
              } else if (condition == JComponent.WHEN_FOCUSED)
                   return (InputMap) UIManager.get("TabbedPane.focusInputMap");
              return null;
         ActionMap createMyActionMap()
              ActionMap map = new ActionMapUIResource();
              map.put("navigateNext", new NextAction());
              map.put("navigatePrevious", new PreviousAction());
              map.put("navigateRight", new RightAction());
              map.put("navigateLeft", new LeftAction());
              map.put("navigateUp", new UpAction());
              map.put("navigateDown", new DownAction());
              map.put("navigatePageUp", new PageUpAction());
              map.put("navigatePageDown", new PageDownAction());
              map.put("requestFocus", new RequestFocusAction());
              map.put("requestFocusForVisibleComponent",
                        new RequestFocusForVisibleAction());
              map.put("setSelectedIndex", new SetSelectedIndexAction());
              map.put("scrollTabsForwardAction", new ScrollTabsForwardAction());
              map.put("scrollTabsBackwardAction", new ScrollTabsBackwardAction());
              return map;
         protected void uninstallKeyboardActions()
              SwingUtilities.replaceUIActionMap(tabPane, null);
              SwingUtilities.replaceUIInputMap(tabPane,
                        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, null);
              SwingUtilities
                        .replaceUIInputMap(tabPane, JComponent.WHEN_FOCUSED, null);
          * Reloads the mnemonics. This should be invoked when a memonic changes,
          * when the title of a mnemonic changes, or when tabs are added/removed.
         private void updateMnemonics()
              resetMnemonics();
              for (int counter = tabPane.getTabCount() - 1; counter >= 0; counter--)
                   int mnemonic = tabPane.getMnemonicAt(counter);
                   if (mnemonic > 0)
                        addMnemonic(counter, mnemonic);
          * Resets the mnemonics bindings to an empty state.
         private void resetMnemonics()
              if (mnemonicToIndexMap != null)
                   mnemonicToIndexMap.clear();
                   mnemonicInputMap.clear();
          * Adds the specified mnemonic at the specified index.
         private void addMnemonic(int index, int mnemonic)
              if (mnemonicToIndexMap == null)
                   initMnemonics();
              mnemonicInputMap.put(KeyStroke.getKeyStroke(mnemonic, Event.ALT_MASK),
                        "setSelectedIndex");
              mnemonicToIndexMap.put(new Integer(mnemonic), new Integer(index));
          * Installs the state needed for mnemonics.
         private void initMnemonics()
              mnemonicToIndexMap = new Hashtable();
              mnemonicInputMap = new InputMapUIResource();
              mnemonicInputMap.setParent(SwingUtilities.getUIInputMap(tabPane,
                        JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
              SwingUtilities
                        .replaceUIInputMap(tabPane,
                                  JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT,
                                  mnemonicInputMap);
         // UI Rendering
         public void paint(Graphics g, JComponent c)
              int tc = tabPane.getTabCount();
              if (tabCount != tc)
                   tabCount = tc;
                   updateMnemonics();
              int selectedIndex = tabPane.getSelectedIndex();
              int tabPlacement = tabPane.getTabPlacement();
              ensureCurrentLayout();
              // Paint content border
              paintContentBorder(g, tabPlacement, selectedIndex);
         protected void paintTab(Graphics g, int tabPlacement, Rectangle[] rects,
                   int tabIndex, Rectangle iconRect, Rectangle textRect)
              Rectangle tabRect = rects[tabIndex];
              int selectedIndex = tabPane.getSelectedIndex();
              boolean isSelected = selectedIndex == tabIndex;
              boolean isOver = overTabIndex == tabIndex;
              Graphics2D g2 = null;
              Shape save = null;
              boolean cropShape = false;
              int cropx = 0;
              int cropy = 0;
              if (g instanceof Graphics2D)
                   g2 = (Graphics2D) g;
                   // Render visual for cropped tab edge...
                   Rectangle viewRect = tabScroller.viewport.getViewRect();
                   int cropline;
                   cropline = viewRect.x + viewRect.width;
                   if ((tabRect.x < cropline)
                             && (tabRect.x + tabRect.width > cropline))
                        cropx = cropline - 1;
                        cropy = tabRect.y;
                        cropShape = true;
                   if (cropShape)
                        save = g2.getClip();
                        g2
                                  .clipRect(tabRect.x, tabRect.y, tabRect.width,
                                            tabRect.height);
              paintTabBackground(g, tabPlacement, tabIndex, tabRect.x, tabRect.y,
                        tabRect.width, tabRect.height, isSelected);
              paintTabBorder(g, tabPlacement, tabIndex, tabRect.x, tabRect.y,
                        tabRect.width, tabRect.height, isSelected);
              String title = tabPane.getTitleAt(tabIndex);
              Font font = tabPane.getFont();
              FontMetrics metrics = g.getFontMetrics(font);
              Icon icon = getIconForTab(tabIndex);
              layoutLabel(tabPlacement, metrics, tabIndex, title, icon, tabRect,
                        iconRect, textRect, isSelected);
              paintText(g, tabPlacement, font, metrics, tabIndex, title, textRect,
                        isSelected);
              paintIcon(g, tabPlacement, tabIndex, icon, iconRect, isSelected);
              paintFocusIndicator(g, tabPlacement, rects, tabIndex, iconRect,
                        textRect, isSelected);
              if (cropShape)
                   paintCroppedTabEdge(g, tabPlacement, tabIndex, isSelected, cropx,
                             cropy);
                   g2.setClip(save);
              } else if (isOver || isSelected)
                   int dx = tabRect.x + tabRect.width - BUTTONSIZE - WIDTHDELTA;
                   int dy = (tabRect.y + tabRect.height) / 2 - 6;
                   if (isCloseButtonEnabled)
                        paintCloseIcon(g2, dx, dy, isOver);
         protected void paintCloseIcon(Graphics g, int dx, int dy, boolean isOver)
              paintActionButton(g, dx, dy, closeIndexStatus, isOver, closeB,
                        closeImgB);
              g.drawImage(closeImgI, dx, dy + 1, null);
         protected void paintActionButton(Graphics g, int dx, int dy, int status,
                   boolean isOver, JButton button, BufferedImage image)
              button.setBorder(null);
              if (isOver)
                   switch (status)
                   case OVER:
                        button.setBorder(OVERBORDER);
                        break;
                   case PRESSED:
                        button.setBorder(PRESSEDBORDER);
                        break;
              button.setBackground(tabScroller.tabPanel.getBackground());
              button.paint(image.getGraphics());
              g.drawImage(image, dx, dy, null);
          * This method will create and return a polygon shape for the given tab
          * rectangle which has been cropped at the specified cropline with a torn
          * edge visual. e.g. A "File" tab which has cropped been cropped just after
          * the "i": ------------- | ..... | | . | | ... . | | . . | | . . | | . . |
          * The x, y arrays below define the pattern used to create a "torn" edge
          * segment which is repeated to fill the edge of the tab. For tabs placed on
          * TOP and BOTTOM, this righthand torn edge is created by line segments
          * which are defined by coordinates obtained by subtracting xCropLen[i] from
          * (tab.x + tab.width) and adding yCroplen[i] to (tab.y). For tabs placed on
          * LEFT or RIGHT, the bottom torn edge is created by subtracting xCropLen[i]
          * from (tab.y + tab.height) and adding yCropLen[i] to (tab.x).
         private static final int     CROP_SEGMENT     = 12;
         private void paintCroppedTabEdge(Graphics g, int tabPlacement,
                   int tabIndex, boolean isSelected, int x, int y)
              g.setColor(shadow);
              g.drawLine(x, y, x, y + rects[tabIndex].height);
         private void ensureCurrentLayout()
              if (!tabPane.isValid())
                   tabPane.validate();
               * If tabPane doesn't have a peer yet, the validate() call will silently
               * fail. We handle that by forcing a layout if tabPane is still invalid.
               * See bug 4237677.
              if (!tabPane.isValid())
                   TabbedPaneLayout layout = (TabbedPaneLayout) tabPane.getLayout();
                   layout.calculateLayoutInfo();
          * Returns the bounds of the specified tab in the coordinate space of the
          * JTabbedPane component. This is required because the tab rects are by
          * default defined in the coordinate space of the component where they are
          * rendered, which could be the JTabbedPane (for WRAP_TAB_LAYOUT) or a
          * ScrollableTabPanel (SCROLL_TAB_LAYOUT). This method should be used
          * whenever the tab rectangle must be relative to the JTabbedPane itself and
          * the result should be placed in a designated Rectangle object (rather than
          * instantiating and returning a new Rectangle each time). The tab index
          * parameter must be a valid tabbed pane tab index (0 to tab count - 1,
          * inclusive). The destination rectangle parameter must be a valid
          * <code>Rectangle</code> instance. The handling of invalid parameters is
          * unspecified.
          * @param tabIndex
          *            the index of the tab
          * @param dest
          *            the rectangle where the result should be placed
          * @return the resulting rectangle
          * @since 1.4
         protected Rectangle getTabBounds(int tabIndex, Rectangle dest)
              try{
                   dest.width = rects[tabIndex].width;
                   dest.height = rects[tabIndex].height;
                   Point vpp = tabScroller.viewport.getLocation();
                   Point viewp = tabScroller.viewport.getViewPosition();
                   dest.x = rects[tabIndex].x + vpp.x - viewp.x;
                   dest.y = rects[tabIndex].y + vpp.y - viewp.y;
              }catch(Throwable a_th){}
              return dest;
         private int getTabAtLocation(int x, int y)
              ensureCurrentLayout();
              int tabCount = tabPane.getTabCount();
              for (int i = 0; i < tabCount; i++)
                   if (rects.contains(x, y))
                        return i;
              return -1;
         public int getOverTabIndex()
              return overTabIndex;
         * Returns the index of the tab closest to the passed in location, note that
         * the returned tab may not contain the location x,y.
         private int getClosestTab(int x, int y)
              int min = 0;
              int tabCount = Math.min(rects.length, tabPane.getTabCount());
              int max = tabCount;
              int tabPlacement = tabPane.getTabPlacement();
              boolean useX = (tabPlacement == TOP || tabPlacement == BOTTOM);
              int want = (useX) ? x : y;
              while (min != max)
                   int current = (max + min) / 2;
                   int minLoc;
                   int maxLoc;
                   if (useX)
                        minLoc = rects[current].x;
                        maxLoc = minLoc + rects[current].width;
                   } else
                        minLoc = rects[current].y;
                        maxLoc = minLoc + rects[current].height;
                   if (want < minLoc)
                        max = current;
                        if (min == max)
                             return Math.max(0, current - 1);
                   } else if (want >= maxLoc)
                        min = current;
                        if (max - min <= 1)
                             return Math.max(current + 1, tabCount - 1);
                   } else
                        return current;
              return min;
         * Returns a point which is translated from the specified point in the
         * JTabbedPane's coordinate space to the coordinate space of the
         * ScrollableTabPanel. This is used for SCROLL_TAB_LAYOUT ONLY.
         private Point translatePointToTabPanel(int srcx, int srcy, Point dest)
              Point vpp = tabScroller.viewport.getLocation();
              Point viewp = tabScroller.viewport.getViewPosition();
              dest.x = srcx + vpp.x + viewp.x;
              dest.y = srcy + vpp.y + viewp.y;
              return dest;
         // BasicTabbedPaneUI methods
         // Tab Navigation methods
         // REMIND(ADC,7/29/98): This method should be made
         // protected in the next release where
         // API changes are allowed
         boolean requestMyFocusForVisibleComponent()
              Component visibleComponent = getVisibleComponent();
              if (visibleComponent.isFocusTraversable())
                   visibleComponent.requestFocus();
                   return true;
              } else if (visibleComponent instanceof JComponent)
                   if (((JComponent) visibleComponent).requestDefaultFocus())
                        return true;
              return false;
         private static class RightAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.navigateSelectedTab(EAST);
         private static class LeftAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.navigateSelectedTab(WEST);
         private static class UpAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.navigateSelectedTab(NORTH);
         private static class DownAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.navigateSelectedTab(SOUTH);
         private static class NextAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.navigateSelectedTab(NEXT);
         private static class PreviousAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.navigateSelectedTab(PREVIOUS);
         private static class PageUpAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   int tabPlacement = pane.getTabPlacement();
                   if (tabPlacement == TOP || tabPlacement == BOTTOM)
                        ui.navigateSelectedTab(WEST);
                   } else
                        ui.navigateSelectedTab(NORTH);
         private static class PageDownAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   int tabPlacement = pane.getTabPlacement();
                   if (tabPlacement == TOP || tabPlacement == BOTTOM)
                        ui.navigateSelectedTab(EAST);
                   } else
                        ui.navigateSelectedTab(SOUTH);
         private static class RequestFocusAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   pane.requestFocus();
         private static class RequestFocusForVisibleAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.requestMyFocusForVisibleComponent();
         * Selects a tab in the JTabbedPane based on the String of the action
         * command. The tab selected is based on the first tab that has a mnemonic
         * matching the first character of the action command.
         private static class SetSelectedIndexAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = (JTabbedPane) e.getSource();
                   if (pane != null && (pane.getUI() instanceof VCTabPaneUI))
                        VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                        String command = e.getActionCommand();
                        if (command != null && command.length() > 0)
                             int mnemonic = (int) e.getActionCommand().charAt(0);
                             if (mnemonic >= 'a' && mnemonic <= 'z')
                                  mnemonic -= ('a' - 'A');
                             Integer index = (Integer) ui.mnemonicToIndexMap
                                       .get(new Integer(mnemonic));
                             if (index != null && pane.isEnabledAt(index.intValue()))
                                  pane.setSelectedIndex(index.intValue());
         private static class ScrollTabsForwardAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = null;
                   Object src = e.getSource();
                   if (src instanceof JTabbedPane)
                        pane = (JTabbedPane) src;
                   } else if (src instanceof ScrollableTabButton)
                        pane = (JTabbedPane) ((ScrollableTabButton) src).getParent();
                   } else
                        return; // shouldn't happen
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.tabScroller.scrollForward(pane.getTabPlacement());
         private static class ScrollTabsBackwardAction extends AbstractAction
              public void actionPerformed(ActionEvent e)
                   JTabbedPane pane = null;
                   Object src = e.getSource();
                   if (src instanceof JTabbedPane)
                        pane = (JTabbedPane) src;
                   } else if (src instanceof ScrollableTabButton)
                        pane = (JTabbedPane) ((ScrollableTabButton) src).getParent();
                   } else
                        return; // shouldn't happen
                   VCTabPaneUI ui = (VCTabPaneUI) pane.getUI();
                   ui.tabScroller.scrollBackward(pane.getTabPlacement());
         * This inner class is marked "public" due to a compiler bug. This
         * class should be treated as a "protected" inner class.
         * Instantiate it only within subclasses of BasicTabbedPaneUI.
         private class TabbedPaneScrollLayout extends TabbedPaneLayout
              protected int preferredTabAreaHeight(int tabPlacement, int width)
                   return calculateMaxTabHeight(tabPlacement);
              protected int preferredTabAreaWidth(int tabPlacement, int height)
                   return calculateMaxTabWidth(tabPlacement);
              public void layoutContainer(Container parent)
                   int tabPlacement = tabPane.getTabPlacement();
                   int tabCount = tabPane.getTabCount();
                   Insets insets = tabPane.getInsets();
                   int selectedIndex = tabPane.getSelectedIndex();
                   Component visibleComponent = getVisibleComponent();
                   calculateLayoutInfo();
                   if (selectedIndex < 0)
                        if (visibleComponent != null)
                             // The last tab was removed, so remove the component
                             setVisibleComponent(null);
                   } else
                        Component selectedComponent = tabPane
                                  .getComponentAt(selectedIndex);
                        boolean shouldChangeFocus = false;
                        // In order to allow programs to use a single component
                        // as the display for multiple tabs, we will not change
                        // the visible compnent if the currently selected tab
                        // has a null component. This is a bit dicey, as we don't
                        // explicitly state we support this in the spec, but since
                        // programs are now depending on this, we're making it work.
                        if (selectedComponent != null)
                             if (selectedComponent != visibleComponent
                                       && visibleComponent != null)
                                  if (SwingUtilities.findFocusOwner(visibleComponent) != null)
                                       shouldChangeFocus = true;
                             setVisibleComponent(selectedComponent);
                        int tx, ty, tw, th; // tab area bounds
                        int cx, cy, cw, ch; // content area bounds
                        Insets contentInsets = getContentBorderInsets(tabPlacement);
                        Rectangle bounds = tabPane.getBounds();
                        int numChildren = tabPane.getComponentCount();
                        if (numChildren > 0)
                             // calculate tab area bounds
                             tw = bounds.width - insets.left - insets.right;
                             th = calculateTabAreaHeight(tabPlacement, runCount,
                                       maxTabHeight);
                             tx = insets.left;
                             ty =

  • JTabbedPane - Switching tabs erases drawn graphics2d.

    We are using JPanes in a JTabbedPane for a web interface application.
    When switching to a tab in the JTabbedPane that already has Graphics2D components drawn on a JPane (lines, etc.), the drawn information disappears.
    We currently have the paint() method overrided in the JPane where we are actually drawing graphics.
    One work around we have tried was to place code in the JTabbedPane's componentlistener to run when it detects we've switched tabs. That didn't work as the code that runs is done prior to the final refresh of the JTabbedPane, which removes any drawn information.
    We had to place a refresh button on the JPane for the user to click (or any other even trigger) to re-draw the information in order for the image/graphics to be seen.
    How can we avoid this event-only displaying of our graphics? Is there another tab-switching trigger we are unaware of?

    You might have misunderstood how painting works: The information will NOT be retained after being drawn - there is not an "image" for each JPanels that keep the information drawn onto it. If you minimize the application, then restore it, you need to paint it again. If the user have put another window on top of your application, and then moves it, you will have to paint again. If you switch tabs or similar internally in your application, you will also have to paint again. This style is called "immediate mode"-type painting (Which can be compared to "retained mode" painting, whereby there actually is an image that will keep the information between changes. "Scene graph" approaches (which is what JavaFX does AFAIK, and also Java3D) is another "retained mode"-like mode.).
    Thus, one will have to paint everything for every display (The "clip area" in the graphics object defines how much you need to draw - e.g. if the user had a window partially over the application). You accomplish this by overriding paintComponent(Graphics g) on the component, which will be invoked every time the component needs to be redrawn.

Maybe you are looking for

  • File encoded with x264 takes forever to load in Encore CS 5.5

    I use Encore mostly because it takes h.264 video encoded with the x264 compressor, which provides much higher quality than any other compressor. The problem is that these files take forever to load. For example, right now I'm trying to load a video t

  • Set document root for Tomcat

    Hello I want Tomcat to use another document root (where index.html typically resides in). I set <Host name="localhost" debug="0" appBase="" docBase="d:\WWW" unpackWARs="true"> but I got error MAPPING configuration error for request URI Unfortunately,

  • OS 10.4 Server on Latest Mac Mini

    Can OS 10.4 server be installed on the latest generation Mac mini ... or does it require a newer OS? Thanks, Tom

  • Fireworks slide show to dreamweaver

    Hi, at present I have created a slideshow in fireworks cs3. i was wondering is it posible to import the slideshow to my dreaweaver home page. I was looking to have a slideshow with images changing every so often to appear centered on my homepage, wit

  • Mediasource doesn't recognize Creative Zen 8gb

    I recently purchased a 8gb Creative Zen and was surpised to find the enlosed CD didn't contain Mediasource. I downloaded Mediasource 5 from the creative website but then after installing it, it'skept saying it didn't recognize my Zen or Zen wasn't co