JTabbedPane.setComponentAt() problem

I think I have come across a bug with JTabbedPane. If you have tabs with titles that are HTML strings if you call setComponentAt() on the pane the tab titles are redrawn incorrectly.
For example if you call setComponentAt(index, comp) where the tab at 'index' has HTML for the title the title at index + 1 is drawn as the title from 'index'.
Also, if you call setComponentAt(index, comp) where the tab at 'index' does not have an HTML title, but the tab at index + 1 does, the title at index + 1 is drawn to show the actual HTML code.
I have put together a small test program that shows the results.
import javax.swing.*;
public class TabTest extends JFrame {
    private JTabbedPane pane;
    public TabTest() {
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        pane = new JTabbedPane();
        pane.addTab("Test 1", new JPanel());
        pane.addTab("<HTML><b><font color = 'Red'>Test 2</font></b></HTML>", new JPanel());
        pane.addTab("<HTML><b>Test 3</b></HTML>", new JPanel());
        add(pane);              
    public void changeSecondTabTest() {
        pane.setComponentAt(1, new JPanel());
    public void changeFirstTabTest() {
        pane.setComponentAt(0, new JPanel());
    public static void main(String[] args) {
        TabTest frame = new TabTest();
        frame.pack();
        frame.setVisible(true);
        try {
            Thread.sleep(2000);
            frame.changeSecondTabTest();
            JOptionPane.showMessageDialog(frame, "Notice the tab title for the third tab is incorrect");
            Thread.sleep(2000);
            frame.changeFirstTabTest();
            JOptionPane.showMessageDialog(frame, "Please click on the second tab and notice the change");
        } catch (InterruptedException e) {
            e.printStackTrace();
}Sun Bug ID #5022375 seems like it might be related, but it is supposed to be fixed.
Does anyone know of a workaround for this or if this is a known bug? Or am I just doing something completely wrong?
Thank you,
Cameron

One thing that is obvious from your sample code is you are making Swing calls from outside the swing event thread. I don't know if changing that would solve your problem or not. Try this
   public static void main(String[] args) {
        TabTest frame = new TabTest();
        frame.pack();
        frame.setVisible(true);
Runnable r = new Runnable () {
public void run() {
        try {
            Thread.sleep(2000);
            frame.changeSecondTabTest();
            JOptionPane.showMessageDialog(frame, "Notice the tab title for the third tab is incorrect");
            Thread.sleep(2000);
            frame.changeFirstTabTest();
            JOptionPane.showMessageDialog(frame, "Please click on the second tab and notice the change");
        } catch (InterruptedException e) {
            e.printStackTrace();
SwingUtilities.invokeLater(r);
    }

Similar Messages

  • JTabbedPane, JPane PROBLEM

    Hi!, I have a several problem with JApplet, this is the code:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.io.*;
    import java.awt.*;
    public class NuevoApplet extends JApplet{
    JMenuBar menuBar;
    JMenu menuArchivo, submenu;
    JMenuItem menuNuevo;
    JTabbedPane Tabbed1 = new JTabbedPane();
    JPanel Panel = new JPanel();
    class EventHandler implements ActionListener
              public void actionPerformed(ActionEvent e)
                   //Si se elige salir en el menu
                   if (e.getSource() == menuNuevo)
                        CreaTab();
    ActionListener eventHandler = new EventHandler();
    public void start(){}
    public void init () {
    try {
    UIManager.setLookAndFeel(new com.sun.java.swing.plaf.windows.WindowsLookAndFeel());
    } catch (Exception e) { }
    Panel.setBorder(BorderFactory.createEtchedBorder());
    Panel.setLayout(new java.awt.BorderLayout());
    this.Panel.updateUI();
    this.setContentPane(this.Panel);
    this.CreaMenus();
    this.getContentPane().add(this.Tabbed1,java.awt.BorderLayout.CENTER);
    initConnections();
    private void CreaMenus(){
    //Creamos la barra de men�s
    menuBar = new JMenuBar();
    this.setJMenuBar(menuBar);
    //Creamos el men� de Archivo
    menuArchivo = new JMenu("Archivo");
    menuBar.add(menuArchivo);
    //Creamos los elementos del men� archivo
    menuNuevo = new JMenuItem("Abrir Archivo *.hex");
    menuArchivo.add(menuNuevo);     
    public void initConnections()
    //se suscriben todas las componentes que quieren escuchar los eventos
         menuNuevo.addActionListener(eventHandler);
    public void CreaTab(){
    JPanel a = new JPanel();
    Entorno1 b = new Entorno1();
    a.add(new JButton("BOTON1"),java.awt.BorderLayout.CENTER);
    a.add(new JButton("BOTON2"),java.awt.BorderLayout.EAST);
    this.Tabbed1.addTab("Primera Pesta�a", b); --> PROBLEM, not insert the JPanel b extends Entorno1
         b.repaint();
         Tabbed1.invalidate();
    Tabbed1.getParent().invalidate();
    Tabbed1.validate();
    Tabbed1.repaint();
         this.Tabbed1.updateUI();
         /*this.Tabbed1.validate();
         this.Tabbed1.updateUI();
         this.Tabbed1.revalidate();*/
    public class Entorno1 extends JPanel{
    public void Entorno1(){
         setLayout(new BorderLayout());
         Border raisedBevel = BorderFactory.createRaisedBevelBorder();
    Border loweredBevel = BorderFactory.createLoweredBevelBorder();
    Border compound = BorderFactory.createCompoundBorder
    (raisedBevel, loweredBevel);
    this.setBorder(compound);
    this.add(new JButton("Boton1"),java.awt.BorderLayout.CENTER);
    this.add(new JButton("Boton2"),java.awt.BorderLayout.EAST);
    this.updateUI();
    this.setVisible(true);
    this.revalidate();
    this.repaint();
    } //Fin de la clase Applet16F84
    When I use b extends Entorno1 and I insert as JPanel of JTabbedPane, not show it.
    this.Tabbed1.addTab("Primera Pesta�a", b);
    But this yes show it:
    this.Tabbed1.addTab("Primera Pesta�a", a);
    Why ? ..
    Thanks !

    Your constructor is actually a method and not a constructor.
    Therefore calling new Entorno1() returns you a blank panel.
    change this
    public void Entorno1(){
    ...to this.
    public Entorno1(){that should do it..
    nes

  • JSplitPane within JTabbedPane display problem

    What am I missing??? I have a JSplitPane in a TabbedPane.
    The topComponent contains a JComboBox with Key values, the
    Bottom Component will display details based on the key
    value passed from the TopComponent. The bottomComponent
    has 2 constructors: one default and one accepting an Argument.
    The default constructor instantiate the class that would
    represent the data and formats the bottomComponent. The second
    constructor retrieves the data from an Oracle database
    and formats the BottomComponent using the same method.
    I put System.out messages in the formatting method and the
    values are showing using the Second constructor.
    The problem is displaying the detail data after the Key is
    selected and passed from the Top Component. The Page is
    initially displayed with the BottomComponent without any
    values displayed. After the Key is selected from the
    topComponent, the value is passed to the bottomComponent
    (which is a Class). I access the data, issue setText(...)
    on the fields BUT the screen display does not reflex the
    values. I issue a System.out.print for the fields and
    there's data there.
    I don't understand why the page doesn't display the data.
    Your help is greatly appreciated

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

  • (Notice!)JTabbedPane Selection Problem!!!

    Hi,Everyone~
    Happy new year...^^
    I have a problem about JTabbedPane Component.
    Shortly says,
    if you made,
    JTabbedPane tab = new JTabbedPane();
    tab.add(A); --> A is panel or smothing like that..
    tab.add(B);
    tab.add(C);
    you can see 2 or 3 Tab row.
    when you select tab one of two row Tab,
    you want to see at front row and first index whiech selected tab.
    How could do it??
    Please, Give me the answer~~!!

    I'm not really sure what you need, but if you want to know which tab is selected just do:
    int tab = JTabPane.getSelectedIndex();

  • JTabbedPane display problems

    Can someone help me with this? I have a JTabbedPane in an applet with two tabs. Lately I have noticed that when I move the mouse pointer around on one tab, some components from the other tab start to show through and I can even click on them, resulting in other components showing through and a jumbled mess. Can anyone help me?
    Here is how I set up the layout in the init method:
    jPanelUI = new MyUIPanel();
    getContentPane().setLayout(new GridLayout(1,1,0,0));
    jPanelUI.setLayout(new GridLayout(1,1,0,0));
    // add look & feel panel to content pane
    getContentPane().add(jPanelUI);
    // add main panel to look & feel panel
    jPanelUI.add(administrationPanel);
    Here is MyUIPanel:
    public class MyUIPanel extends javax.swing.JPanel implements my.data.MyConstants
         public MyUIPanel()
         super();
         UIManager.put("TabbedPane.selected", CONTROL);
         UIManager.put("TableHeader.background", CONTROL);
         UIManager.put("ScrollBar.arrowColor", Color.green);
         UIManager.put("ScrollPane.background", CONTROL);
         UIManager.put("ScrollPane.foreground", CONTROL);
    I add the JTabbedPane to Administration panel like this...
    jTabbedPaneAdministration.setRequestFocusEnabled(false);
    jTabbedPaneAdministration.setOpaque(true);
    add(jTabbedPaneAdministration, new com.symantec.itools.awt.GridBagConstraintsD(0,2,6,10,0.5,0.5,java.awt.GridBagConstraints.WEST,java.awt.GridBagConstraints.BOTH,new Insets(15,20,20,20),0,0));
    jTabbedPaneAdministration.setBackground(new java.awt.Color(204,204,153));
    jTabbedPaneAdministration.setFont(new Font("Dialog", Font.PLAIN, 12));
    I add my two panels to administration panel like this...
    jTabbedPaneAdministration.add(jPanel1);
    jTabbedPaneAdministration.add(jPanel2);
    Any ideas?
    Thanks a bunch

    Found the problem. On the invisible tab, I was setting visibilities, depending on what components the user had permission to see. I assumed that those visibilities would only take effect on the tab that they were on, but instead they showed right through the selected tab. So it wasnt the resizing but your idea made me look to what I was doing with those panels after adding them, and I found it. Enjoy your duke $s
    Thanks

  • JTabbedPane addChangeListener problem

    My application uses a JTabbedPane. Whenever data has changed on one tab and the user navigates to another I will display a JOptionPane asking if the user wants to save the changed data. My problem is that I want the tab with unsaved data to remain selected until the user has answered yes or no. As is the tab will change and then display the JOptionPane. Strangely this works as intended on some Java versions, but I would like to find a more universal approach.
    is there another way of achieving the desired behaviour?
    My code:
    tabbedPane.addChangeListener(new ChangeListener() {
    public void stateChanged(ChangeEvent evt) {
    if (globalUpdateModel.isModelUpdated()) {
    if (userConfirmedSaveChanges()) {     //this is the metod displaying the JOptionPane
    saveAction.actionPerformed(null);
    } else {
    searchAction.actionPerformed(null);
    });

    tabbedPane.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent evt) {
                    if (globalUpdateModel.isModelUpdated()) {
                        if (userConfirmedSaveChanges()) {
                            saveAction.actionPerformed(null);
                        } else {
                            searchAction.actionPerformed(null);
            });

  • JTabbedPane layout problem

    I have a JTabbedPane as shown below:
    |                          |
    | ----- -----                         |
    |  |   | |   |                        |
    | ----------------------------------- |
    | | --------------- --------------- | |
    | | --------------- --------------- | |
    | | --------------- --------------- | |
    | | --------------- --------------- | |
    | | --------------- --------------- | |
    | | --------------- --------------- | |
    | |_________________________________| |
    |                                     |
    --------------------------------------|As you can see, each tab has two columns and with 5 rows each column. Each row is a horizontal javax.swing.Box of components.
    My problem sometimes I only have, for example, 2 rows in the second column. They become stretched to fill the remaining space and I don't like that.
    How do I resolve this so it doesn't do that?
    Thnks for any help!
    Liam

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.Random;
    public class Test extends JFrame {
      public Test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container content = getContentPane();
        JTabbedPane jtp = new JTabbedPane();
        content.add(jtp, BorderLayout.CENTER);
        Random r = new Random();
        for (int i=0; i<2; i++) {
          JPanel tab = new JPanel(new GridLayout(6,2));
          jtp.add("Tab "+i, tab);
          for (int j=0; j<6; j++) {
            tab.add(new JLabel("Label-"+i+","+j+":", JLabel.RIGHT));
            if (j==0 || r.nextBoolean()) tab.add(new JTextField("Text-"+i+","+j));
            else tab.add(Box.createHorizontalBox());
        setSize(300, 300);
        setVisible(true);
      public static void main(String args[]) { new Test(); }
    class MyCardLayout extends CardLayout {
      public void show();
    }

  • JTabbedPane setEnabled problem

    Hi,
    I have JTabbedPane with 3 tabs. In each tab there are few components like jSlider, jLabel, jButton, etc.
    The problem is that if I set that jTabbedPane disabled, it only disables the tabs (I cannot change the tab from one to another), but I can still control these sliders and buttons.
    AJ.

    Override the setEnabled() method of each of the Panels to enable or disable the components on it.
    The following might help, not very pretty though
        public static synchronized void setPanelStateEnabled(JComponent c, boolean enable){
            for(Component a:c.getComponents()){
                if(a instanceof JComponent){
                    setPanelStateEnabled((JComponent)a,enable);
                a.setEnabled(enable);
        } so for each of you panels you would call this static method
    setPanelStateEnabled(myPanel,false);

  • JTabbedPane setEnabledAt() problem

    Hi All,
    This is just a thought on how to deal with disabling tab in JTabbedPane.
    We had the problem where if the tab was selected when we call setEnabledAt() for this tab, the user was still able to modify data at the tab, until the tab was left. So, below is a subclass of JTabbedPane, which fixed the behaviour:
    import java.awt.Component;
    import javax.swing.JTabbedPane;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.OverlayLayout;
    public class LockableJTabbedPane extends JTabbedPane {
    /** Creates new LayeredJTabbedPane */
    public LockableJTabbedPane() {
    public void addTab(String title,Component component){
    JPanel frame = new JPanel();
    frame.setLayout(new OverlayLayout(frame));
    JPanel glassPanel = new JPanel(new java.awt.GridLayout (1, 1));
    glassPanel.setName("glassPanel");
    JButton jb = new JButton();
    jb.setOpaque(true);
    jb.setBackground(new java.awt.Color(204,204,204,128));
    jb.setEnabled(false);
    jb.setBorder(null);
    glassPanel.add(jb);
    glassPanel.setOpaque(false);
    glassPanel.setVisible(false);
    frame.add(glassPanel);
    frame.add(component);
    super.addTab(title, frame);
    public void setEnabledAt(int index, boolean enabled ){
    JPanel panel = (JPanel)super.getComponentAt(index);
    Component[] comps = panel.getComponents();
    for (int i=0; i<comps.length; i++){
    Component comp = comps;
    if (comp.getName()=="glassPanel")){
    comp.setVisible(!enabled);
    super.setEnabledAt(index, enabled);

    Override the setEnabled() method of each of the Panels to enable or disable the components on it.
    The following might help, not very pretty though
        public static synchronized void setPanelStateEnabled(JComponent c, boolean enable){
            for(Component a:c.getComponents()){
                if(a instanceof JComponent){
                    setPanelStateEnabled((JComponent)a,enable);
                a.setEnabled(enable);
        } so for each of you panels you would call this static method
    setPanelStateEnabled(myPanel,false);

  • JTabbedPane flashing problem

    I have a JTabbedPane with two tabs (JPanels) added to it. When the view comes up sometimes the second tab (the panel which is being added later) flashes and some of the fields in it are shown on the first tab. When I click on the second tab and then again click back on the first tab the view restores. And this happens sometimes. Is there a reason why this happens? Do I need to call any method on my pane or tabs? Any hints/help appreciated.
    Thanks.

    Override the setEnabled() method of each of the Panels to enable or disable the components on it.
    The following might help, not very pretty though
        public static synchronized void setPanelStateEnabled(JComponent c, boolean enable){
            for(Component a:c.getComponents()){
                if(a instanceof JComponent){
                    setPanelStateEnabled((JComponent)a,enable);
                a.setEnabled(enable);
        } so for each of you panels you would call this static method
    setPanelStateEnabled(myPanel,false);

  • JTabbedPane resize problem

    I have a JTabbedPane in a JPanel (BorderLayout.CENTER).
    That JPanel is the content component of a JOptionPane.
    The JOptionPane is in a JScrollPane which is in a JDialog.
    When the JDialog is resized (larger), the JTabbedPane enlarges too as desired.
    However, when the JDialog is resized (smaller), the JTabbedPane does not reduce in size consistently as one would wish.
    Any one know why, have a solution, etc.
    Any ideas appreciated.
    Thanks.

    I am using gl4java's GLAnimCanvas as the canvas based object in my application. Since
    the Swing based gl4java object is not hardware accellerated, it is way to too slow for my application
    (a 3D gui ).

  • JTabbedPan initialization problem

    Hi,
    I am using a JtabbedPan with 4 tabs whose one has itself 5 tabs.
    After initialization, If I try to click on the 3rd or 4th tab, then I will see the content of the second one.
    And the only way to see the 3rd or 4th tab 's content is to go through the second one.
    How can I avoid this?
    thanks

    I overloaded JPanel into Panel to add a state and description field.
              panelContribs = new Panel("Contribs");
              panelContribs.setBackground(mainColor);
              panelCaracs = new Panel("Caracs");
              panelCaracs.setBackground(mainColor);
              panelScenarios = new Panel("Scenarios");
              panelScenarios.setBackground(mainColor);
              panelLogs = new Panel("Logs");
              panelLogs.setBackground(mainColor);
              panelDeltas = new Panel("Delta");
              panelDeltas.setBackground(mainColor);
              panelVegas = new Panel("Vega");
              panelVegas.setBackground(mainColor);
              panelVegaSABR = new Panel("Vega SABR");
              panelVegas.setBackground(mainColor);
              panelDeltaVol = new Panel("DeltaVol");
              panelDeltaVol.setBackground(mainColor);
              panelCoeffDeltaVol = new Panel("Coeff Delta Vol");
              panelCoeffDeltaVol.setBackground(mainColor);
            JTabbedPane tab =   PanelDecorator.getInstance().getTab();
               tab.setBounds(0,300,500,800);
             frame.add(tab,  BorderLayout.CENTER);          
             JPanel jp4 =  gui.getPanelLogs();
             tab.add("Logs", jp4);
             JPanel jp = gui.getPanelContribs();
             tab.add("Contrib", jp);
             JPanel jp2 =  gui.getPanelScenarios();
             tab.add("Scénarios", jp2);
             JPanel jp3 =  gui.getPanelCaracs();
             tab.add("Caracs", jp3);Then for each Panel , I have an associated class that feeds it.
    For example, for the caracs, I have
    package tocheck;
    import entities.Carac;
    import entities.Indicator;
    import gui.Displayable;
    import gui.PanelDecorator;
    import java.awt.Color;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Iterator;
    import java.util.Map;
    import java.util.Observable;
    import java.util.Observer;
    import javax.swing.JLabel;
    import javax.swing.JTextArea;
    import org.apache.log4j.Logger;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;
    import org.w3c.dom.Node;
    import org.w3c.dom.NodeList;
    import utils.DataFileWatchdog;
    import xml.XMLInstance;
    public class CaracsToCheck extends ToCheck implements Displayable,Observer {
         private Logger logger = Logger.getLogger(CaracsToCheck.class);
         private Map<String,Integer> mapCaracs;
         private static CaracsToCheck     instance = null;
         public static CaracsToCheck     getInstance(){
              if (instance == null){
                   try {
                        instance = new CaracsToCheck();
                   } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                   } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              return instance;
         private CaracsToCheck() throws ClassNotFoundException, SQLException{
              PanelDecorator gui = PanelDecorator.getInstance();
              mapCaracs = new HashMap<String, Integer>();
              loopParameters("CARAC");
                  panelCaracs = gui.getPanelCaracs();
              checkCaracs();
              DataFileWatchdog  wd;
              // this watchdog (an Observable object)
              //   is monitoring any file change
              wd = new DataFileWatchdog("output.xml");
              wd.addObserver(this);
         public boolean areCaracsOK(){
                   panelCaracs.resetEtat();
                  Document doc = XMLInstance.getInstance().getDoc();
                  NodeList nList = doc.getElementsByTagName("Carac");
                  Node caracs = nList.item(0);
                  if(caracs.getNodeType() == Node.ELEMENT_NODE){
                       Element e = (Element)caracs;
                       NodeList nCaracs = e.getElementsByTagName("Item");
                       for (int temp = 0; temp < nCaracs.getLength(); temp++) {
                          Node nNode = nCaracs.item(temp);        
                          if (nNode.getNodeType() == Node.ELEMENT_NODE) {
                             Element eElement = (Element) nNode;
                             try{
                                   Carac carac = new Carac(eElement);
                                 handleCarac(carac);
                             }catch(Exception eee){
                 evaluateTab(panelCaracs, PanelDecorator.getInstance().getTab(), 3);
                 return true;
         private void handleCarac(Carac carac) {
              String     key = carac.getLocation();
              String     keydigit = "digit" + carac.getLocation();
              String keycarac = "caractime" + carac.getLocation();
              JLabel     lblDigit = PanelDecorator.getInstance().getLabel(keydigit);
              if(lblDigit != null){
                   lblDigit.setText(String.valueOf(carac.getNumber()));
              }else{
                   return ;
              JLabel     lblCaracTime = PanelDecorator.getInstance().getLabel(keycarac);
              SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss  dd/MM/yyyy");
              String time = carac.getLastInsertCaracIntradayTime();
              if(time == null || time.equals("") ){
                   lblCaracTime.setText("NONE");
                   if(carac.getLocation().equals("PARIS")){
                        colourJLabel(lblCaracTime, 3 , "Carac Intraday Import PARIS", panelCaracs);
              }else{
                   Timestamp dateTimeStamp = Timestamp.valueOf(time);
                   Timestamp          now = new Timestamp(new Date().getTime());
                   lblCaracTime.setText(formatter.format(Timestamp.valueOf(time)));
                   int status = 10;
                   long nb_msec = now.getTime() - dateTimeStamp.getTime();
                   int timeout = mapCaracs.get(carac.getLocation());
                   if (nb_msec > timeout ){
                        status = 2;
                   }else{
                        status = 5;
                   if(carac.getLocation().equals("PARIS")){
                        colourJLabel(lblCaracTime, status , "Last Carac Intraday Import Date PARIS", panelCaracs);
              colourJLabel(lblDigit, carac.getIndicator().getStatus() , carac.getIndicator().getKey(), panelCaracs);
              this.evaluateTab(panelCaracs, PanelDecorator.getInstance().getTab() , 3);
              JTextArea lblListe = PanelDecorator.getInstance().getTextArea("liste"+ key);
              if(carac.getNumber() == 0){
                   if(lblListe != null)
                   lblListe.setText("");
                   lblDigit.setBackground(Color.GREEN);
              }else{
                   if(lblListe != null){
                        lblListe.setText(carac.getList());
                        if(carac.getLocation() != null && carac.getLocation().equals("PARIS")){
                             lblDigit.setBackground(Color.RED);
                        }else{
                             lblDigit.setBackground(Color.YELLOW);
         public void loopParameters(String flag){
              panelCaracs.resetEtat();
              PanelDecorator.getInstance().createLabel("Caracs", 0, 0, panelCaracs);
              Iterator it = properties.keySet().iterator();
             while (it.hasNext()) {
                  String propertyKey = (String)it.next();
                 String[] values = propertyKey.split(";");
                 String type = values[3];
                 if(type != null && type.equals(flag) ){
                      String location = values[0];
                      String key = location ;
                      try{
                           Integer timeout= Integer.parseInt((String)properties.get(propertyKey));
                           mapCaracs.put(location, timeout);
                      }catch(Exception e){
                        PanelDecorator.getInstance().createLabel( key , 0, 0, panelCaracs);
                        PanelDecorator.getInstance().createLabel( "Carac Intraday Time:" , 1, 0, panelCaracs);
                        PanelDecorator.getInstance().createRegisteredLabel("caractime"+key, 0, panelCaracs);
                        PanelDecorator.getInstance().createDigitLabel( "digit" + key , 0 , 0, panelCaracs);
                      PanelDecorator.getInstance().createLabel(      "Liste " +  key  + ":", 1, 0, panelCaracs);
                      PanelDecorator.getInstance().createListArea( "liste" + key ,      "" , 0, panelCaracs);
                 PanelDecorator.getInstance().createLabel(      "", 0, 0, panelCaracs);
                 PanelDecorator.getInstance().createLabel(      "", 0, 0, panelCaracs);
                 PanelDecorator.getInstance().createLabel(      "", 0, 0, panelCaracs);
                 PanelDecorator.getInstance().createLabel(      "Query" , 1, 0, panelCaracs);
                PanelDecorator.getInstance().createListArea( "listequeryarea" ,      "  " , 2, panelCaracs);
         public boolean checkCaracs(){
              return areCaracsOK();
         public void update(Observable o, Object arg) {
              checkCaracs();
              PanelDecorator.getInstance().tabSelect();
         public void paint() {
              // TODO Auto-generated method stub
    } for the contrib , I have :
    public class ContribToCheck extends ToCheck implements Displayable,Observer {
       private Logger logger = Logger.getLogger(ContribToCheck.class);
       private Map thresholds ;
       private static ContribToCheck     instance = null;
       private String     expiries[];
         public static ContribToCheck     getInstance(){
              if (instance == null){
                   try {
                        instance = new ContribToCheck();
                   } catch (ClassNotFoundException e) {
                        e.printStackTrace();
                   } catch (SQLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
              return instance;
         private ContribToCheck() throws ClassNotFoundException, SQLException {
              super();
              PanelDecorator gui = PanelDecorator.getInstance();
              panelContrib = gui.getPanelContribs();
              thresholds = new LinkedHashMap<String,Integer>();
              DataFileWatchdog  wd;
              // this watchdog (an Observable object)
              //   is monitoring any file change
              wd = new DataFileWatchdog("output.xml");
              wd.addObserver(this);
         public void paint(){
              PanelDecorator.getInstance().createLabel("Rates", 0, 0, panelContrib);
              loopParameters("RATES");   
              PanelDecorator.getInstance().createLabel("Inflation", 0, 0, panelContrib);
              loopParameters("INF");
              PanelDecorator.getInstance().createLabel("Basis forward", 0, 1, panelContrib);
              Iterator it = Params.getInstance().getProperties().entrySet().iterator();
             while (it.hasNext()) {
                 Map.Entry pairs = (Map.Entry)it.next();
                 String[] values = ((String)pairs.getKey()).split(";");
                 String curveid = values[0];
                 String currency  = values[1];
                 String index = values[2];
                 String type = values[3];
                 if(type != null && type.equals("BASIS") ){
                      String key = currency + " " + curveid + " "+ index ;
                        PanelDecorator.getInstance().createLabel(  key , 1, 1 , panelContrib);
                        PanelDecorator.getInstance().createRegisteredLabel("BasisFwdContrib["+ key + "]", 1 , panelContrib);
                        for(String s : expiries) {
                                  String keyCompleted = key.concat(" "+s);
                                  PanelDecorator.getInstance().createLabel(s, 2, 1 , panelContrib);
                                  String chaine = "BasisFwdContrib[";
                                  chaine = chaine.concat(keyCompleted);
                                  chaine = chaine.concat("]");
                                  PanelDecorator.getInstance().createRegisteredLabel(chaine, 1 , panelContrib);
              logger.warn("RateContrib paint");     
         public void handleBasis(BasisForward r){
                   String     key = "BasisFwdContrib[" + r.getCurrency() + " " + r.getCurveid() + " " + r.getIndex() + " " + r.getTerm() + "]";
                   JLabel     lbl = PanelDecorator.getInstance().getLabel(key);
                   SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss  dd/MM/yyyy ");
                  lbl.setText(formatter.format(Timestamp.valueOf(r.getIndicator().getTime())));
                  this.colourJLabel(lbl, r.getIndicator().getStatus(), r.getIndicator().getKey() ,panelContrib );     
         public void loopParameters(String flag){
              Iterator it = properties.keySet().iterator();
             while (it.hasNext()) {
                 String[] values = ((String)it.next()).split(";");
                 String curveid = values[0];
                 String currency  = values[1];
                 String index = values[2];
                 String type = values[3];
                 if(type != null && type.equals(flag) ){
                      String key = currency + " " + curveid + " "+ index ;
                        PanelDecorator.getInstance().createLabel(  key , 2, 0 , panelContrib);
                        PanelDecorator.getInstance().createRegisteredLabel("RateContrib["+ key + "]", 0 , panelContrib);
         public void handleRate(Rate r){
              String     key = "RateContrib[" + r.getCurrency() + " " + r.getCurveid() + " " + r.getIndex() + "]";
              JLabel     lbl = PanelDecorator.getInstance().getLabel(key);
              SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss  dd/MM/yyyy ");
             lbl.setText(formatter.format(Timestamp.valueOf(r.getIndicator().getTime())));
             this.colourJLabel(lbl, r.getIndicator().getStatus(), r.getIndicator().getKey() ,panelContrib );                                             
         public boolean checkContrib(){     
              panelContrib.resetEtat();
                   Document doc = XMLInstance.getInstance().getDoc();
                   try{
                             NodeList nList = doc.getElementsByTagName("Rate");
                            Node rate = nList.item(0);
                            if(rate.getNodeType() == Node.ELEMENT_NODE){
                                 Element e = (Element)rate;
                                 NodeList nRates = e.getElementsByTagName("Item");
                                 for (int temp = 0; temp < nRates.getLength(); temp++) {
                                      Element element = (Element)nRates.item(temp);
                                      Rate r = new Rate(element);
                                      if(r.getCurveid().equals("HIC5")) continue;
                                      handleRate(r);
                   }catch(Exception e){
                        System.out.println(e.getMessage());
                   try{
                        NodeList nList = doc.getElementsByTagName("Inflation");
                       Node rate = nList.item(0);
                       if(rate.getNodeType() == Node.ELEMENT_NODE){
                            Element e = (Element)rate;
                            NodeList nRates = e.getElementsByTagName("Item");
                            for (int temp = 0; temp < nRates.getLength(); temp++) {
                                 Element element = (Element)nRates.item(temp);
                                 Rate r = new Rate(element);
                                 if(r.getCurveid().equals("HIC5")) continue;
                                 handleRate(r);
              }catch(Exception e){
                   System.out.println(e.getMessage());
              try{
                   NodeList nList = doc.getElementsByTagName("BasisForward");
                  Node rate = nList.item(0);
                  if(rate.getNodeType() == Node.ELEMENT_NODE){
                       Element e = (Element)rate;
                       NodeList nRates = e.getElementsByTagName("Item");
                       for (int temp = 0; temp < nRates.getLength(); temp++) {
                            Element element = (Element)nRates.item(temp); 
                            BasisForward b = new BasisForward(element);
                            handleBasis(b);
         }catch(Exception e){
              System.out.println(e.getMessage());
               evaluateTab(panelContrib, PanelDecorator.getInstance().getTab(), 1);
              return true;
         public void update(Observable arg0, Object arg1) {
              checkContrib();
              PanelDecorator.getInstance().tabSelect();
       public String[] getExpiries() {
              return expiries;
         public void setExpiries(String[] expiries) {
              this.expiries = expiries;
    }At First, it loops through the "ToCheck" class to build them and initialize Components.
    Thank you for your help.
    ...

  • JTabbedPane update problem

    Hi,
    I am using a JTabbedPane in an applet with two tabs, When I swap between them parts of the tab do not update. I have a mixture of two tabs. Is ther a way of updating so this does not happen??.
    Thanks for any help as I am a java beginner
    Joolz

    Hi,
    Just an update,
    I have noticed that when the applet starts the tab 0 is seleted but showing the items on tab 1???..
    Whay is it doing this.
    Thanks
    Joolz

  • JTabbedPane - How do I stop it from resizing?

    I am resizing a jTabbedPane. Problem is, when a tab is selected, jTabbedPane revalidates and repaints, causing it (and any other controls inside its container that were resized, moved) to go back to the original size; is there any way around this? why is it going back to its ORIGINAL size, eons after its been resized? I know how much SWING loves to be in control of the layout, but pllleeeeeeeeeaaaaaseeeeeeeee...
    ps: i am using the XYLayout manager, but this behaviour is evident in all layout managers..

    are you doing something squirrely with the layout? you are absolutely correct that Swing is obnoxious about resizing things after the fact. have you tried taking the components in the JTabbedPane and dropping them in a JPanel in a JFrame and resizing them from there? (i.e.: test that your layout mechanism is correct.)
    something else that might help is to use the setPreferredSize(), setMaximumSize() and setMinimumSize() methods.
    i recently laid out some JButtons with ImageIcons in them that were fixed 24x24 pixels. when i put them in a GridBagLayout, they were fine until i started resizing the parent JFrame. calling just the setPreferredSize() method was not enough to solve the problem, despite the fact that Swing often ignores the other setXXXSize methods. if you have static size components, this may do the trick.
    if that doesn't help, post the code.
    good luck,
    jon/hackerx

  • Loading images in an application

    hi guys hope you can help me, im currently indulge in application programming and i need to load images in an application, i use a JTabbedPane as my main component so i use 4 panels to differentiate the different sections of my the JTabbedPane my problem is i need to display different images on each panels(diff images on 4 diff panels of the JTabbedPane....how will i do this? ope you can give me an idea.....thank you very much and God Bless us All!

    You can load different images by using
    Image testImage = new ImageIcon("c:\testimage.gif").getImage();this.
    Hope this serves your needs.

Maybe you are looking for