user592704
user592704

Reputation: 3704

JTabbedPane - dynamic tabs control

I've faced an interesting thing... All goes fine with null object When I add tabs in constructor as

public class TPane extends JTabbedPane
{

public TPane(ImageIcon iconA,ImageIcon iconB)
{
  this.addTab("A",iconA,null);
  this.addTab("B",iconB,null);

}

}

But when I try to add tab within another object like

public class AClass
{

public void addNewTab(TPane tp, ImageIcon icon)
{

  tp.addTab("C",icon,null);//<-- contains null
}

}

... it doesn't add tab because of null. OK if I change null to lets say a new JLabel() code works fine :S

Here is both previous object usage...

public class BClass extends JPanel
{


  private AClass a=new AClass();
  private TPane tp=new TPane();
  JButton addTabButton=new JButton("add tab");
  ImageIcon icon;

  public BClass(Image image)
{

icon=new ImageIcon(image);
...
this.add(tp);
...
addTabButton.addMouseListener(new MouseAdapter()
{

  public void mousePressed(MouseEvent e)
{

   a.addNewTab(tp,icon);

}

});

}
}

So my question is how to add null object to JTabbedPane dynamically?

Any useful comment is appreciated

Upvotes: 0

Views: 2793

Answers (1)

MByD
MByD

Reputation: 137422

I am not sure this is the problem. I have tried it successfully, see the example below and its code(although this is a pathological example):

enter image description here

package so;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;

public class JTabbedEx extends JTabbedPane {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                ImageIcon icon = new ImageIcon();
                JTabbedPane tabs = new JTabbedPane();
                tabs.addTab("Tab1", icon,null);
                new AnotherClass().addTab(tabs, icon);
                JFrame frame  = new JFrame();
                frame.add(tabs);
                frame.pack();
                frame.setVisible(true);
            }
        });         
    }
}

class AnotherClass {
    public void addTab(JTabbedPane tabs, ImageIcon icon) {
        tabs.addTab("Another tab", icon, null);
    }
}

Upvotes: 3

Related Questions