Tabbed Pane help

Thanks everyone for the help in the past. I am on to a new section of the program that i am writing and after searching the web and these forums for several hours i am still at a loss. I have a jtabbedpane that i want to add and remove tabs when the user clicks a button. I have the buttons working and can add tabs and delete them at will. My issue is that when i add a new tab, the previous tabs lose thier content. When i create the new tabs i add them to an ArrayList so that i can get at the information later but can only get the newest tab to display the information. If i make a simple test that adds a new tab with a textbox, or a label things work fine. All the tabs have new content in them but when i try to add a panel that is more than a single element the early tabs lose everything. Here is my sample code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import com.jgoodies.forms.factories.*;
import com.jgoodies.forms.layout.*;
import info.clearthought.layout.*;
public class TryMain {
     public static void main(String[] args) {
          RunMe();
     private static void RunMe() {
          TryMain Test = new TryMain();
     private TryMain() {
          MainWindow = new JFrame();
          mainWindowToolBar = new JToolBar();
          newWeekButton = new JButton();
          deleteWeekButton = new JButton();
          mainTabs = new JTabbedPane();
          weekTabs = new JPanel();
          sortByLabel = new JLabel();
          sortByChooser = new JComboBox();
          playerNameLabel = new JLabel();
          averageScoreLabel = new JLabel();
          averageRankLabel = new JLabel();
          playerName1 = new JLabel();
          playerAvgRank1 = new JLabel();
          playerAvgScrore1 = new JLabel();
          CellConstraints cc = new CellConstraints();
          TabsList = new ArrayList();
          WeekNum = 0;
          //======== MainWindow ========
               MainWindow.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
               MainWindow.setTitle("test");
               MainWindow.setSize(700, 575);
               MainWindow.setLocation(100, 100);
               MainWindow.setVisible(true);
               mainTabs.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
               Container MainWindowContentPane = MainWindow.getContentPane();
               MainWindowContentPane.setLayout(new FormLayout(
                    ColumnSpec.decodeSpecs("default:grow"),
                    new RowSpec[] {
                         FormFactory.DEFAULT_ROWSPEC,
                         FormFactory.LINE_GAP_ROWSPEC,
                         new RowSpec(RowSpec.FILL, Sizes.DEFAULT, FormSpec.DEFAULT_GROW)
               //======== mainWindowToolBar ========
                    mainWindowToolBar.setFloatable(false);
                    mainWindowToolBar.setOpaque(false);
                    //---- newWeekButton ----
                    Action newTabAction = new AbstractAction("New Week") {
                    public void actionPerformed(ActionEvent evt) {
                         mainTabs.addTab("Week-"+(WeekNum+1), new JScrollPane(addTabbedPaneTab(WeekNum)));
                           mainTabs.setSelectedIndex(WeekNum);
                           WeekNum = WeekNum + 1;
                    newWeekButton.setAction(newTabAction);
                    mainWindowToolBar.add(newWeekButton);
                    //---- deleteWeekButton ----
                    Action RemoveTabAction = new AbstractAction("Delete Week") {
                    public void actionPerformed(ActionEvent evt) {
                         if (WeekNum != 0) {
                              WeekNum = (mainTabs.getTabCount() - 1);     
                             mainTabs.removeTabAt(mainTabs.getSelectedIndex());
                             TabsList.remove(mainTabs.getSelectedIndex());
                    deleteWeekButton.setAction(RemoveTabAction);
                    mainWindowToolBar.add(deleteWeekButton);
               MainWindowContentPane.add(mainWindowToolBar, cc.xy(1, 1));
               //======== mainTabs ========
               for (int i = 0; i < 4; i++) {
                    mainTabs.addTab("Week-"+(WeekNum+1), new JScrollPane(addTabbedPaneTab(WeekNum)));
                    mainTabs.setSelectedIndex(WeekNum);
                    WeekNum = WeekNum + 1;
               MainWindowContentPane.add(mainTabs, cc.xy(1, 3));
               mainTabs.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent evt) {     
                     setFocus();
     private static JFrame MainWindow;
     private static JToolBar mainWindowToolBar;
     private static JButton newWeekButton;
     private static JButton deleteWeekButton;
     private static JTabbedPane mainTabs;
     private static JPanel weekTabs;
     private static JLabel sortByLabel;
     private static JComboBox sortByChooser;
     private static JLabel playerNameLabel;
     private static JLabel averageScoreLabel;
     private static JLabel averageRankLabel;
     private static JLabel playerName1;
     private static JLabel playerAvgRank1;
     private static JLabel playerAvgScrore1;
     private static ArrayList TabsList;
     private static int WeekNum;
     public JPanel addTabbedPaneTab(int wnum) {
          TabsList.add(new JPanel());
          ((JPanel)TabsList.get(wnum)).setLayout(new TableLayout(new double[][] {
                    {TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED},
                    {TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED, TableLayout.PREFERRED}}));
               ((TableLayout)((JPanel)TabsList.get(wnum)).getLayout()).setHGap(5);
               ((TableLayout)((JPanel)TabsList.get(wnum)).getLayout()).setVGap(5);
               //---- sortByLabel ----
               sortByLabel.setText("Sort By:");
               ((JPanel)TabsList.get(wnum)).add(sortByLabel, new TableLayoutConstraints(0, 0, 0, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- sortByChooser ----
               sortByChooser.setModel(new DefaultComboBoxModel(new String[] {
                    "Name",
                    "Average Rank",
               sortByChooser.setOpaque(false);
               ((JPanel)TabsList.get(wnum)).add(sortByChooser, new TableLayoutConstraints(1, 0, 2, 0, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- playerNameLabel ----
               playerNameLabel.setText("Name");
               ((JPanel)TabsList.get(wnum)).add(playerNameLabel, new TableLayoutConstraints(1, 1, 1, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- averageScoreLabel ----
               averageScoreLabel.setText("Average Score");
               ((JPanel)TabsList.get(wnum)).add(averageScoreLabel, new TableLayoutConstraints(5, 1, 5, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- averageRankLabel ----
               averageRankLabel.setText("Avg. Rank");
               ((JPanel)TabsList.get(wnum)).add(averageRankLabel, new TableLayoutConstraints(6, 1, 6, 1, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- playerName1 ----
               playerName1.setText("Joe Smith");
               ((JPanel)TabsList.get(wnum)).add(playerName1, new TableLayoutConstraints(1, 2, 1, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- playerAvgRank1 ----
               playerAvgRank1.setText("1");
               ((JPanel)TabsList.get(wnum)).add(playerAvgRank1, new TableLayoutConstraints(6, 2, 6, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               //---- playerAvgScrore1 ----
               playerAvgScrore1.setText("32.8");
               ((JPanel)TabsList.get(wnum)).add(playerAvgScrore1, new TableLayoutConstraints(5, 2, 5, 2, TableLayoutConstraints.FULL, TableLayoutConstraints.FULL));
               return ((JPanel)TabsList.get(wnum));
     public static void setFocus() {
        ((JPanel)TabsList.get(mainTabs.getSelectedIndex())).revalidate();
}thanks for the help in advance.

You are trying to re-use the same component to be two different things.You create a bunch of statics, like "static JLabel playerName1", then you do a setText on it and add it to a JPanel. But then the next time around you do a setText on the SAME instance and try to add it to a different JPanel. A component can't be on two different panels at the same time. You must create a new instance for each panel. It would probably be a lot simpler if you just dumped all the statics, and instead wrote more conventional code like:
JLabel name=new JLabel("Name");
panel.add(name,whatever_constraints);And by the way, I think the code in addTabbedPaneTab would be a whole lot more readable if you created a variable to hold a reference to the panel, rather than going back to the get every time, like
public JPanel addTabbedPaneTab(int wnum) {
  JPanel week=new JPanel();
  week.setLayout(... whatever ...);
  JLabel sortByLabel=new JLabel("Sort By");
  week.add(sortByLabel,... constraints ...);
  JComboBox sortByChooser=new JComboBox(new DefaultComboBoxModel(... whatever ...));
  sortByChooser.setOpaque(false);
  week.add(sortByChooser,... constraints...);
  JLabel playerNameLabel=new JLabel("Name");
  week.add(playerNameLabel,... constraints ...);          
  JLabel averageScoreLabel=new JLabel("Average Score");
  week.add(averageScoreLabel,... constraints ...);          
  JLabel averageRankLabel=new JLabel("Avg Rank");
  week.add(averageRankLabel,... constraints ...);          
  JLabel playerName1=new JLabel("Joe Smith");
  week.add(playerName1,... constraints ...);               
  JLabel playerAvgRank1=new JLabel("1");
  week.add(playerAvgRank1,... constraints ...);
  JLabel playerAvgScrore1=new JLabel("32.8");
  week.add(playerAvgScrore1,... constraints ...);
  TabsList.add(week);
  return week;               
}I also don't see why you need TabsList, it's just a duplicate of the list of tabs that you could pull out of the JTabbedPane itself anyway.

Similar Messages

  • Help with tabbed pane

    hello!
    i have a tabbed pane with two tabs.
    in tab1 i have a button(for example), how can i do that when i press the button in tab1 it will draw something in tab2?
    i tried to do this but it draw what i want in tab1(the tab with the button)
    if the source code will help i will post it here
    sorry for my bad english

    here's something to play around with
    (I've simplified it by putting it all in paintComponent, but it should be changed
    to get the image, if not null then repaint)
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.net.URL;
    import javax.imageio.ImageIO;
    class Testing extends JFrame
      JTabbedPane tp = new JTabbedPane();
      JPanel p1 = new JPanel();
      MyJPanel p2 = new MyJPanel();
      public Testing()
        setSize(400,400);
        setLocation(300,200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JButton btn = new JButton("Set image");
        btn.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            p2.imageFile = "Test.gif";
            p2.repaint();}});
        p1.add(btn);
        tp.addTab("Tab 1",p1);
        tp.addTab("Tab 2",p2);
        getContentPane().add(tp);
      public static void main(String[] args){new Testing().setVisible(true);}
    class MyJPanel extends JPanel
      String imageFile = null;
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        if(imageFile != null)
          try
            URL url = new URL(getClass().getResource(imageFile), imageFile);
            Image img = ImageIO.read(url);
            g.drawImage(img, 50,50,this);
          catch(Exception e){JOptionPane.showMessageDialog(null,"Image error");}
    }

  • Need help with tabbed panes

    I am creating an App that uses tabbed pane.
    The first tab is for loggin in.
    What I want to do is make all the other tabs invisible until the user has successfully logged in.
    How do I make the other tabs invisible?

    Hi,
    One way is to add them after the user has logged in. Another way is to disable them so that the user can't use them.
    Btw. I have to say that what you want to do sounds weird. Normally you use a modal login dialog instead.
    /Kaj

  • Help w/tabbed pane -- URGENT!

    i'm developing a program that will open up documents and put them in a tabbed pane. One thing that i have learned is that setting the text of a component inside of a tabbed pane is easier than getting the text back from it when the user goes to save.
    public void addDoc(String text, String title, String toolTipTab) {
    textArea = new JTextArea();
    textArea.setTabSize(2);
    textArea.setText(text);
    JScrollPane scrollPane = new JScrollPane(textArea);
    tabbedPane.addTab(title, scrollPane);
    tabbedPane.setSelectedComponent(scrollPane);
    what i would like to do is to get the text from the JTextArea() and save it. I have tried the follwoing
    tabbedPane.getSelectedComponent().textArea.getText();
    but that doesn't work. Also just using textArea.getText(); doesn't work because it will only get the newly opened document. Also if i can solve this, then i can implement Cut Copy Paste and Select All
    thanks

    i'm developing a program that will open up documents
    and put them in a tabbed pane. One thing that i have
    learned is that setting the text of a component inside
    of a tabbed pane is easier than getting the text back
    from it when the user goes to save.
    public void addDoc(String text, String title, String
    toolTipTab) {
    textArea = new JTextArea();
    textArea.setTabSize(2);
    textArea.setText(text);
    JScrollPane scrollPane = new JScrollPane(textArea);
    tabbedPane.addTab(title, scrollPane);
    tabbedPane.setSelectedComponent(scrollPane);
    what i would like to do is to get the text from the
    JTextArea() and save it. I have tried the follwoing
    tabbedPane.getSelectedComponent().textArea.getText();
    but that doesn't work. Also just using
    textArea.getText(); doesn't work because it will only
    get the newly opened document. Also if i can solve
    this, then i can implement Cut Copy Paste and Select
    All
    thanksWhy not keep one copy of the text area in class scope, so for example:
    public class MyClass {
    private JTextArea textArea = null;
      public void addDoc(String text, String title, String
      toolTipTab) {
      textArea = new JTextArea();
      textArea.setTabSize(2);
      textArea.setText(text);
      JScrollPane scrollPane = new JScrollPane(textArea);
      tabbedPane.addTab(title, scrollPane);
      tabbedPane.setSelectedComponent(scrollPane);
      public String getText() throws BadLocationException {
       return textArea.getDocument().getText(0,textArea.getDocument().getLength());
    }Am I understanding your problem correctly?
    I think this should return what you need.
    Dan Hughes

  • How can I make a tabbed pane transparent ?

    I have a tabbed pane placed on a JPanel with an image background. I added a tabbed pane with tabbedPane.setOpaque (false), however I still can't see the image behind the components that were added as tabs in the tabbedpane. Any help will be greatly appreciated.
    Here's a simplified version of the code:
    public class Example extends JPanel {
         public Example() {
              tabs = new JTabbedPane();
              tabs.setOpaque (false);
              JPanel tp1 = new JPanel();
              tp1.setOpaque(false);
              tabs.addTab ("panel 1", tp1);
              this.add (tabs);
         public void paintComponent(Graphics g) {
              // Paint background image
              g.drawImage(...);
    }

    Perhaps the opaque property is internally overset by the tab pane.
    Try this:
       public class Example extends JPanel {
          public Example() {
             JTabbedPane tabs = new JTabbedPane() {
                public boolean isOpaque() {
                   return false;
             JPanel tp1 = new JPanel() {
                public boolean isOpaque() {
                   return false;
             tabs.addTab("panel 1", tp1);
             this.add (tabs);
          public void paintComponent(Graphics g) {
             // Paint background image
             g.drawImage(...);
       } Regards.

  • How can i place button on top right hand corner of the tabbed pane

    Hi all,
    i want to place button on top right hand corner of the tabbed pane, just run the code below, i have add button(it going to insert tab into tabbedpane), i want to place that tab into top right hand corner of the tabbedpane (not inside the tab itself). if i set tab policy setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT), it will give two button at right hand corner along with those buttons i want to and one more add button.
    please suggest so that i can move forward.
    Thanks in advance
    import java.awt.Dimension;
    import java.util.HashMap;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    * @author  Dayananda.BV
    public class TabpaneDemo extends javax.swing.JFrame {
        /** Creates new form TabpaneDemo */
        HashMap<Integer, tabpanel> panelMap = new HashMap<Integer, tabpanel>();
        public TabpaneDemo() {
            initComponents();
            createFloorPlan();
            getContentPane().setPreferredSize(new Dimension(400,400));
            jTabbedPane1.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
        /** 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() {
            jTabbedPane1 = new javax.swing.JTabbedPane();
            add_tab_button = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            add_tab_button.setText("+");
            add_tab_button.setMargin(new java.awt.Insets(0, 0, 0, 0));
            add_tab_button.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    add_tab_buttonActionPerformed(evt);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(308, Short.MAX_VALUE)
                    .addComponent(add_tab_button, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(67, 67, 67))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(add_tab_button)
                    .addGap(8, 8, 8)
                    .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 292, Short.MAX_VALUE))
            pack();
        }// </editor-fold>                       
        private void createFloorPlan(){
            tabpanel floorplan_Panel = new tabpanel(panelMap.size()+1);
            panelMap.put(floorplan_Panel.getTabIndex(), floorplan_Panel);
            jTabbedPane1.add(floorplan_Panel, floorplan_Panel.getTabName());
            jTabbedPane1.setSelectedIndex(jTabbedPane1.getTabCount()-1);
        private void add_tab_buttonActionPerformed(java.awt.event.ActionEvent evt) {                                              
            createFloorPlan();
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TabpaneDemo().setVisible(true);
        // Variables declaration - do not modify                    
        private javax.swing.JButton add_tab_button;
        private javax.swing.JTabbedPane jTabbedPane1;
        // End of variables declaration                  
        class tabpanel extends JPanel{
            private int tabIndex = 0;
            private String tabName ;
            public tabpanel(int tabIndex) {
                this.tabIndex = tabIndex;
                if(tabIndex >= 10) {
                    tabName = "Floor Map"+tabIndex;
                } else{
                    tabName = "Floor Map"+tabIndex+"  ";
            public int getTabIndex(){
                return tabIndex;
            public String getTabName(){
                return tabName;
    }Thanks
    Dayananda B V

    This part of tabbed pane is not customizable as it lies in the ComponentUI(TabbedpaneUI) portion of the tabbedpane.
    But I can point out the place u can change to bring the desired feature into effect.
    U can find an Inner class called ScrollableTabSupport
    Look for the methods createButtons where u can create extra buttons and add to the tabbed pane.
    The Inner class also implements actionListener where u can implement the action for the button u added.
    By this method U have to use your own extended TabbedPaneUI which u cant escape from.
    Hope this will help u.

  • How to a particular panel in a tabbed pane to the front?

    Hello
    I have a small application that uses a tabbed pane. At some point I want to press a button in one of the panels of the tabbed pane and then another panel in the same tabbed pane to show up, as if I had clicked on that tab to bring it to the front.
    Only difference is I don't want to click on the tab to do it but on another button, so I can do some more stuff through the button before I bring the other panel to the front
    I thought I could do this by getting focus, but it seems not to be the case. Getting focus does not mean coming to the front as I originally thought.
    I hope this is clear. Here is an example that you can compile and run. I want to get jpanel2 to the front by clicking jbutton1 and vice versa.
    Any help appreciated.
    (Frame1.java)
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Frame1 extends JFrame {
        private JTabbedPane jTabbedPane1 = new JTabbedPane();
        private JPanel jPanel1 = new JPanel();
        private JPanel jPanel2 = new JPanel();
        private JButton jButton1 = new JButton();
        private JButton jButton2 = new JButton();
        private JTextField jTextField1 = new JTextField();
        private JTextField jTextField2 = new JTextField();
        public Frame1() {
            try {
                jbInit();
                this.setDefaultCloseOperation(EXIT_ON_CLOSE);
                setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
        private void jbInit() throws Exception {
            this.getContentPane().setLayout( null );
            this.setSize( new Dimension(400, 300) );
            jTabbedPane1.setBounds(new Rectangle(0, 0, 395, 270));
            jPanel1.setLayout(null);
            jPanel2.setLayout(null);
            jButton1.setText("jButton1");
            jButton1.setBounds(new Rectangle(20, 170, 160, 25));
            jButton1.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            jButton1_actionPerformed(e);
            jButton2.setText("jButton2");
            jButton2.setBounds(new Rectangle(20, 135, 160, 25));
            jButton2.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent e) {
                            jButton2_actionPerformed(e);
            jTextField1.setBounds(new Rectangle(55, 45, 210, 20));
            jTextField2.setBounds(new Rectangle(95, 50, 180, 20));
            jPanel1.add(jTextField1, null);
            jPanel1.add(jButton1, null);
            jTabbedPane1.addTab("jPanel1", jPanel1);
            jPanel2.add(jTextField2, null);
            jPanel2.add(jButton2, null);
            jTabbedPane1.addTab("jPanel2", jPanel2);
            this.getContentPane().add(jTabbedPane1, null);
        private void jButton1_actionPerformed(ActionEvent e) {
        private void jButton2_actionPerformed(ActionEvent e) {
        public static void main(String[] args) {
            new Frame1();
    }

    tabbedPane.setSelectedIndex(...);

  • Ideas for a "virtually" tabbed pane

    I'm developing on this application for keeping information about products and customers in a shop.
    In my "product manager" window I would like to have tabbed pane with an input interface for different types of goods in each tab respectively. But since the interface is more or less the same for different products (with fields like product name beeing persistent), it would be better to just alter the input components programmatically (in the pane's stateChanged event), rather than having to duplicate components for 7 different tabs... Hope my point gets through. This is strictly a matter of Look & Feel -- this is the most neat sollution i could think of :)

    mannamann wrote:
    I appreciate your commitment to ridding the forums of the "by getters". I know that my question was probably a little superficial, and something that I could have figured out myself. My goal is not to get rid of get byers, but I will want to expend more of my free time and effort helping those where the paybacks for me are greatest -- the highly motivated. It is truly amazing and gratifying to see those of this kind progress.
    But since the primary focus of our project is not GUI-programming, isn't it fair to post a "quicky" here, to draw some knowledge from experts like you? So that I don't have to spend my entire day working out UI, when I prefered to focus on the data model of my program. After all, isn't that what the forum is all about?It's about sharing knowledge, of course, but having said that, you can't ignore the human component either. We're all volunteers, and given our druthers, we'll put in more effort towards those who do likewise. You really can't expect otherwise, right?

  • How to drag and drop tab nodes between tab panes

    I'm working on example from this tutorial( Drag-and-Drop Feature in JavaFX Applications | JavaFX 2 Tutorials and Documentation ). Based on the tutorial I want to drag tabs between two tabs. So far I managed to create this code but I need some help in order to finish the code.
    Source
    tabPane = new TabPane();
    Tab tabA = new Tab();
       Label tabALabel = new Label("Main Component");
    tabPane.setOnDragDetected(new EventHandler<MouseEvent>()
                @Override
                public void handle(MouseEvent event)
                    /* drag was detected, start drag-and-drop gesture*/
                    System.out.println("onDragDetected");
                    /* allow any transfer mode */
                    Dragboard db = tabPane.startDragAndDrop(TransferMode.ANY);
                    /* put a string on dragboard */
                    ClipboardContent content = new ClipboardContent();
                    content.put(DataFormat.PLAIN_TEXT, tabPane);
                    db.setContent(content);
                    event.consume();
    What is the proper way to insert the content of the tab as object? Into the tutorial simple text is transferred. How I must modify this line content.put(DataFormat.PLAIN_TEXT, tabPane);?
    And what is the proper way to insert the tab after I drag the tab:
    Destination
    tabPane.setOnDragDropped(new EventHandler<DragEvent>()
                @Override
                public void handle(DragEvent event)
                    /* data dropped */
                    /* if there is a string data on dragboard, read it and use it */
                    Dragboard db = event.getDragboard();
                    boolean success = false;
                    if (db.hasString())
                        //tabPane.setText(db.getString());
                        Tab tabC = new Tab();
                        tabPane.getTabs().add(tabC);
                        success = true;
                    /* let the source know whether the string was successfully
                     * transferred and used */
                    event.setDropCompleted(success);
                    event.consume();
    I suppose that this transfer can be accomplished?
    Ref javafx 2 - How to drag and drop tab nodes between tab panes - Stack Overflow

    I would use a graphic (instead of text) for the Tabs and call setOnDragDetected on that graphic. That way you know which tab is being dragged. There's no nice way to put the Tab itself into the dragboard as it's not serializable (see https://javafx-jira.kenai.com/browse/RT-29082), so you probably just want to store the tab currently being dragged in a property.
    Here's a quick example; it just adds the tab to the end of the current tabs in the dropped pane. If you wanted to insert it into the nearest location to the actual drop you could probably iterate through the tabs and figure the coordinates of each tab's graphic, or something.
    import java.util.Random;
    import javafx.application.Application;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Label;
    import javafx.scene.control.Tab;
    import javafx.scene.control.TabPane;
    import javafx.scene.input.ClipboardContent;
    import javafx.scene.input.DragEvent;
    import javafx.scene.input.Dragboard;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.input.TransferMode;
    import javafx.scene.layout.StackPane;
    import javafx.scene.layout.VBox;
    import javafx.stage.Stage;
    public class DraggingTabPane extends Application {
      private static final String TAB_DRAG_KEY = "tab" ;
      private ObjectProperty<Tab> draggingTab ;
    @Override
      public void start(Stage primaryStage) {
      draggingTab = new SimpleObjectProperty<>();
      TabPane tabPane1 = createTabPane();
      TabPane tabPane2 = createTabPane();
      VBox root = new VBox(10);
      root.getChildren().addAll(tabPane1, tabPane2);
      final Random rng = new Random();
      for (int i=1; i<=8; i++) {
        final Tab tab = createTab("Tab "+i);
        final StackPane pane = new StackPane();
          int red = rng.nextInt(256);
          int green = rng.nextInt(256);
          int blue = rng.nextInt(256);
        String style = String.format("-fx-background-color: rgb(%d, %d, %d);", red, green, blue);
        pane.setStyle(style);
        final Label label = new Label("This is tab "+i);
        label.setStyle(String.format("-fx-text-fill: rgb(%d, %d, %d);", 256-red, 256-green, 256-blue));
        pane.getChildren().add(label);
        pane.setMinWidth(600);
        pane.setMinHeight(250);
        tab.setContent(pane);
        if (i<=4) {
          tabPane1.getTabs().add(tab);
        } else {
          tabPane2.getTabs().add(tab);
      primaryStage.setScene(new Scene(root, 600, 600));
      primaryStage.show();
      public static void main(String[] args) {
      launch(args);
      private TabPane createTabPane() {
        final TabPane tabPane = new TabPane();
        tabPane.setOnDragOver(new EventHandler<DragEvent>() {
          @Override
          public void handle(DragEvent event) {
            final Dragboard dragboard = event.getDragboard();
            if (dragboard.hasString()
                && TAB_DRAG_KEY.equals(dragboard.getString())
                && draggingTab.get() != null
                && draggingTab.get().getTabPane() != tabPane) {
              event.acceptTransferModes(TransferMode.MOVE);
              event.consume();
        tabPane.setOnDragDropped(new EventHandler<DragEvent>() {
          @Override
          public void handle(DragEvent event) {
            final Dragboard dragboard = event.getDragboard();
            if (dragboard.hasString()
                && TAB_DRAG_KEY.equals(dragboard.getString())
                && draggingTab.get() != null
                && draggingTab.get().getTabPane() != tabPane) {
              final Tab tab = draggingTab.get();
              tab.getTabPane().getTabs().remove(tab);
              tabPane.getTabs().add(tab);
              event.setDropCompleted(true);
              draggingTab.set(null);
              event.consume();
        return tabPane ;
      private Tab createTab(String text) {
        final Tab tab = new Tab();
        final Label label = new Label(text);
        tab.setGraphic(label);
        label.setOnDragDetected(new EventHandler<MouseEvent>() {
          @Override
          public void handle(MouseEvent event) {
            Dragboard dragboard = label.startDragAndDrop(TransferMode.MOVE);
            ClipboardContent clipboardContent = new ClipboardContent();
            clipboardContent.putString(TAB_DRAG_KEY);
            dragboard.setContent(clipboardContent);
            draggingTab.set(tab);
            event.consume();
        return tab ;

  • Disposable tabbed pane redrawing

    Hi, i'm using disposable tabbed panes (with close button) in my program and i'm using following method to update their titles according to what user entered:
    //this is class extending JPanel
    public void updatePanelTitle(String newTitle) {
            MainPanel panel = (MainPanel) getParent(); //MainPanel extends JTabbedPane
            panel.setTitleAt(panel.getComponentZOrder(this)-1, newTitle);
            repaint();
        }Point is the title gets changed but the size of panel label does not. However, when i mouse-over the close button there, it gets changed to the size of the text.
    @Override
            public void mouseEntered(MouseEvent e) {
                Component component = e.getComponent();
                if (component instanceof AbstractButton) {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(true);
            }setBorderPainted calls inside the repaint method.
    Can anyone give a clue why it is not working or how to fix it?
    Regards,
    Marek

    Well its quite big but if it helps, this is the panel class:
    package presentationTier.view;
    import com.bbgroup.ui.Console;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.border.Border;
    import javax.swing.text.BadLocationException;
    import presentationTier.Model.Properties;
    import presentationTier.Model.PropertyInterface;
    import presentationTier.Model.StandardInputOutput;
    import presentationTier.controller.ConfirmListGeneratorAction;
    import presentationTier.controller.ConfirmSearchReplaceAction;
    import presentationTier.controller.OpenBrowseDialogAction;
    * @author marek
    public class ListGeneratorPanel extends JPanel implements StandardInputOutput, PropertyInterface {
        private JLabel labStartPath,  labExtensions;
        private JTextField txtStartPath,  txtExtensions;
        private JButton butBrowse,  butGo;
        private Console console;
        private GridBagConstraints c;
        private Insets labelInsets,  normalInsets;
        public ListGeneratorPanel() {
            super(new GridBagLayout());
            initComponents();
            borderCompononets(BorderFactory.createLoweredBevelBorder());
            resetConstraints();
            c.gridx = 0;
            c.gridy = 0;
            c.insets = labelInsets;
            add(labStartPath, c);
            c.gridx = 1;
            //c.gridwidth = 1;
            c.weightx = 1;
            c.insets = normalInsets;
            add(txtStartPath, c);
            c.gridx = 2;
            //c.gridwidth = 1;
            c.weightx = 0;
            add(butBrowse, c);
            c.gridx = 0;
            c.gridy = 1;
            c.weightx = 0;
            c.insets = labelInsets;
            add(labExtensions, c);
            c.gridx = 1;
            //c.gridwidth = 3;
            c.weightx = 1;
            c.insets = normalInsets;
            add(txtExtensions, c);
            c.gridx = 2;
            c.gridwidth = 1;
            //c.gridheight = 1;
            c.weightx = 0;
            add(butGo, c);
            c.gridx = 0;
            c.gridy = 2;
            c.gridwidth = 5;
            c.weighty = 1;
            add(new JScrollPane(console), c);
            resetConstraints();
        private void initComponents() {
            c = new GridBagConstraints();
            console = new Console(true);
            labelInsets = new Insets(5, 5, 0, 0);
            normalInsets = new Insets(5, 5, 0, 5);
            labStartPath = new JLabel("Search under:");
            labExtensions = new JLabel("File types:");
            txtStartPath = new JTextField();
            txtExtensions = new JTextField();
            butBrowse = new JButton(new OpenBrowseDialogAction(this));
            butGo = new JButton(new ConfirmListGeneratorAction(this));
        private void borderCompononets(Border b) {
            getTxtStartPath().setBorder(b);
            getTxtExtensions().setBorder(b);
        private void resetConstraints() {
            c.ipadx = 0;
            c.ipady = 0;
            c.gridwidth = 1;
            c.gridheight = 1;
            c.weightx = 0;
            c.weighty = 0;
            c.fill = GridBagConstraints.BOTH;
            c.anchor = GridBagConstraints.FIRST_LINE_START;
            c.insets = normalInsets;
        public Properties createProperties() {
            Properties p = new Properties();
            p.setSout(this);
            p.setStartPath(getTxtStartPath().getText());
            p.setExtensions(getTxtExtensions().getText());
            return p;
         * @param line
         * @throws BadLocationException
        public void echo(String line) throws BadLocationException {
            getConsole().echo(line);
         * @param line
         * @param style
         * @throws BadLocationException
        public void echo(String line, String style) throws BadLocationException {
            getConsole().echo(line, style);
        public void drawSeparator() throws BadLocationException {
            getConsole().drawSeparator();
        public void passBrowsedFilePath(String browsedFilePath) {
            getTxtStartPath().setText(browsedFilePath);
        public void updatePanelTitle(String newTitle) {
            MainPanel panel = (MainPanel) getParent();
            panel.setTitleAt(panel.getComponentZOrder(this) - 1, "Generate: " + newTitle);
            updateUI();
            repaint();
        public Console getConsole() {
            return console;
        public JTextField getTxtStartPath() {
            return txtStartPath;
        public JTextField getTxtExtensions() {
            return txtExtensions;
    }When you add instance of this to your JTabbedPane, you will get closeable Tabbed Pane with title you specified in addTab(title, component);
    I implement method updatePanelTitle(String newTitle); to change the title of this tab when suer submits the data. These action controllers that call submitting and updating title are in controller package. Problem is that the title itself is changed when data are submitted but the <b>size of the tab is not adjusted to newTitles length.</b> It is just adjusted when i pull my mouse over the close button that implements action from previous post. It's in this class:
    package com.bbgroup.ui;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicButtonUI;
    import java.awt.*;
    import java.awt.event.*;
    * Component to be used as tabComponent;
    * Contains a JLabel to show the text and
    * a JButton to close the tab it belongs to
    public class DisposableTabPanel extends JPanel {
        private final JTabbedPane pane;
        public DisposableTabPanel(final JTabbedPane pane) {
            //unset default FlowLayout' gaps
            super(new FlowLayout(FlowLayout.LEFT, 0, 0));
            if (pane == null) {
                throw new NullPointerException("TabbedPane is null");
            this.pane = pane;
            setOpaque(false);
            //make JLabel read titles from JTabbedPane
            JLabel label = new JLabel() {
                @Override
                public String getText() {
                    int i = pane.indexOfTabComponent(DisposableTabPanel.this);
                    if (i != -1) {
                        return pane.getTitleAt(i);
                    return null;
            add(label);
            //add more space between the label and the button
            label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5));
            //tab button
            JButton button = new TabButton();
            add(button);
            //add more space to the top of the component
            setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0));
        private class TabButton extends JButton implements ActionListener {
            public TabButton() {
                int size = 17;
                setPreferredSize(new Dimension(size, size));
                setToolTipText("Close this tab");
                //Make the button looks the same for all Laf's
                setUI(new BasicButtonUI());
                //Make it transparent
                setContentAreaFilled(false);
                //No need to be focusable
                setFocusable(false);
                setBorder(BorderFactory.createEtchedBorder());
                setBorderPainted(false);
                //Making nice rollover effect
                //we use the same listener for all buttons
                addMouseListener(buttonMouseListener);
                setRolloverEnabled(true);
                //Close the proper tab by clicking the button
                addActionListener(this);
            public void actionPerformed(ActionEvent e) {
                int i = pane.indexOfTabComponent(DisposableTabPanel.this);
                if (i != -1) {
                    pane.remove(i);
            //we don't want to update UI for this button
            public void updateUI() {
            //paint the cross
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g.create();
                //shift the image for pressed buttons
                if (getModel().isPressed()) {
                    g2.translate(1, 1);
                g2.setStroke(new BasicStroke(2));
                g2.setColor(Color.BLACK);
                if (getModel().isRollover()) {
                    g2.setColor(Color.MAGENTA);
                int delta = 6;
                g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
                g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
                g2.dispose();
        private final static MouseListener buttonMouseListener = new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                Component component = e.getComponent();
                if (component instanceof AbstractButton) {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(true);
            @Override
            public void mouseExited(MouseEvent e) {
                Component component = e.getComponent();
                if (component instanceof AbstractButton) {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(false);
    }I cant possibly post a running code as it uses third party libraries and implements bunch of interfaces, it would require whole nearly whole view-controller part of the project.
    Another problem is that method getComponentZOrder(this) - 1, works for retrieving all tabs except the first one (it returns fine indexes for any tab but -1 for the first one) but sadly there is no such method like getIndex(Component) which would be useful for getting <b>this</b> components index.
    Thanks in advance for ideas.
    Regards, Marek

  • How To use JFile Chooser in a Tabbed Pane Dialog

    I have created a tabbed pane dialog. In one of the tabs I want to add a JFile Chooser.
    How can I approach this problem. also Do I have to use a JDialog with a frame or can I create a JDialog without using a frame and create a instance from the main function.

    I have created a tabbed pane dialog. In one of the
    tabs I want to add a JFile Chooser. Since JFileChooser is a JComponent you could add it to any Container like any other JComponent.
    Maybe you have to do some init by hand which is done normally by the show*() methods of JFileChooser. Taking a look at the source of showDialog() should help.
    Hope that helps,
    Alex

  • Multiple Views of Same Rows from a Tabbed Pane

    I have a Tabbed Pane with several Tabs that access Different Tables. One Table is the child of two different Tables, ie one foreign key on the child that that points to Table A and a second foreign key on the child that points to Table B. I am trying to have a tabbed pane that will show the childs rows one based on the Table A Foreign Key and the second based on the Table B Foreign Key.
    No matter what I have tried, I get only one view from both Tabs. (NOTE: Both of the Tabbed pane that I instantiate from look completly different, ie a different sequence of fields.)
    I have two distinct rowsetinfo's for each tab each with it own distinct Query. I have each MasterLink pointing to the appropriate Master, either Table A or Table B and it doesn't work.
    I have tried to create additional Business components for the second view, but don't know how to link the rowset to the appropriate Business Component, if that's the problem.
    Any help or suggestion would be greatly appreciated, because I'm Lost.

    hi
    i've tried to do that some time ago and i had to give up... unfortunately i think java3D can't use various rendering modes for the same universe
    regards
    GnG

  • Make a component invisible after all tabs in a tabbed pane are closed

    Hi,
    I am using a tabbed pane and open images in tabs. I want to disable a comonent after i find all the tabs of the tabbed pane closed and when all the tabs are closed the tab pane should also be closed.
    Please help me.

        TabPane tabPane = new TabPane();
        tabPane.getTabs().addListener(new ListChangeListener<Tab>() {
          @Override
          public void onChanged(
              javafx.collections.ListChangeListener.Change<? extends Tab> c) {
            if (tabPane.getTabs().isEmpty()) {
             // whatever you need here:
             // somePane.getChildren().remove(tabPane);
             // someControl.setDisable(true);
        });

  • Tabbed Panes

    Dear All,
    I have to create a form with tabbed panes. How can i do this using JFC as i m new to JFC. Then i have to submit the form data in the database using JSP. Please help me to solve this.
    Some Code Please
    Thanks & Regards
    Gagan

    gaganarora77,
    This does seem a case of RTFM:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tabbedpane.html
    Please repost if you have specific problems
    --A                                                                                                                                                                                                                                                                                                                                                           

  • Changin tabbed pane using a JButton

    Hi all,
    I'm trying to include a button on a tabbed page that will enable you to switch to
    another page.
    I'm using the following code:
    FlyProGen.addActionListener( new ActionListener()
         public void actionPerformed( ActionEvent e )
              tabbedpane.setSelectedComponent( container );
    However, I get the following error: "Cannot refer to a non-final variable tabbed pane inside
    an inner class defined in a different method".
    Help!
    best wishes
    Paul

    Paul,
    This discussion seems to pertain to your issue:
    http://oldlook.experts-exchange.com:8080/Programming/Programming_Languages/Java/Q_20718075.html
    Chip McCormick

Maybe you are looking for