associate a JComboBox to JTabbedPane component


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 5 of 5

Thread: associate a JComboBox to JTabbedPane component

Hybrid View

  1. #1
    Join Date
    Aug 2004
    Posts
    37

    associate a JComboBox to JTabbedPane component

    Hi guys;
    in my java program i'm trying to implement the following functionality :

    I have a JTabbedPane to which i'm adding components dynamically (at runtime).
    I have a JComboBox that i want to associate each time to the JTabbedPane selected component:
    i.e. each time i select a component i want to fill the comboBox with items that are related to this selected JTabbedPane component.

    can u tell me how to do this ?

    please help !

    thanks.

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Hoe this can give you a clue

    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.ChangeEvent;
    import javax.swing.event.ChangeListener;
    
    /**
     * <p>Title: Gym</p>
     * <p>Description: program snippets for exercise</p>
     * <p>Copyright: Copyright (c) 2004</p>
     * <p>Company: sjallejavamanscomany</p>
     * @author sjalle
     * @version 1.0
     */
    
    public class TabbedPaneListener extends JFrame implements ChangeListener {
      BorderLayout borderLayout1 = new BorderLayout();
      JTabbedPane tabPane = new JTabbedPane();
      JPanel panelOne = new JPanel();
      JPanel panelTwo = new JPanel();
      JPanel jPanel2 = new JPanel();
      JComboBox tabCombo = new JComboBox();
      JLabel jLabel1 = new JLabel();
      JLabel jLabel2 = new JLabel();
      JButton aBtn = new JButton();
      JTextField aTExtF = new JTextField();
    
      public TabbedPaneListener() {
        try {
          jbInit();
          tabPane.addChangeListener(this);
          addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
            }
          });
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
      public static void main (String [] args) {
        TabbedPaneListener tpl=new TabbedPaneListener();
        tpl.setBounds(40,40,400,300);
        tpl.setVisible(true);
      }
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        tabCombo.setPreferredSize(new Dimension(200, 22));
        jLabel1.setText("Some text in first flap");
        jLabel2.setText("This is text in first flap");
        aBtn.setText("SecondFlapButton");
        aTExtF.setPreferredSize(new Dimension(100, 22));
        aTExtF.setText("");
        this.getContentPane().add(tabPane, BorderLayout.CENTER);
        tabPane.add(panelOne,   "First Flap");
        panelOne.add(jLabel1, null);
        panelOne.add(jLabel2, null);
        tabPane.add(panelTwo,   "Second Flap");
        panelTwo.add(aBtn, null);
        panelTwo.add(aTExtF, null);
        this.getContentPane().add(jPanel2, BorderLayout.SOUTH);
        jPanel2.add(tabCombo, null);
      }
      public void stateChanged(ChangeEvent e) {
        System.out.println(e.toString());
        JTabbedPane aTabbedPane=(JTabbedPane)e.getSource();
        JPanel pan=(JPanel)aTabbedPane.getSelectedComponent();
        Component [] cmp=null;
        if (pan==panelOne) {
          cmp=panelOne.getComponents();
        } else if (pan==panelTwo) {
          cmp=panelTwo.getComponents();
        }
        tabCombo.removeAllItems();
        for (int i=0; i<cmp.length; i++) {
          if (cmp[i] instanceof JLabel) {
            tabCombo.addItem(((JLabel)cmp[i]).getText());
          } else if (cmp[i] instanceof JButton) {
            tabCombo.addItem(((JButton)cmp[i]).getText());
          } else if (cmp[i] instanceof JTextField) {
            tabCombo.addItem(((JTextField)cmp[i]).getText());
          }
        }
    
      }
    }
    eschew obfuscation

  3. #3
    Join Date
    Aug 2004
    Posts
    37
    Your solution is definitly great !

    I did managed to solve the problem : my program is now working fine

    thanks for your interest .

  4. #4
    Join Date
    Aug 2004
    Posts
    37
    oops !
    guys : i'm still having a little problem...here is the description:

    when i create a new panel and add it to tabbedpane i register a changeListener on tabbedPane. the stateChange() method calls a method fill() which removes old values of combobox and fill it with new ones. In fill() method i add an ActionListener to comboBox which gets the selected element and do some work...
    now the problem is that when i select an elemt this fires a changeState for the tabbedPane which in turn refills the comboBox and the combo text is always the first element of the combobox...
    this problem is probably because the events on combo and tabbedPane are related.
    How can i fix this ?

    thanks for helping !

  5. #5
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    This is a well knows situation but, it is difficult to tell exactly what this is without your code. You may have wired the listeners and callbacks wrong.
    Here is my modified example, but I fail to see a behavious like you mention.
    Code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import java.util.*;
    
    
    public class TabbedPanes extends JFrame implements ChangeListener, ActionListener {
    
      public final static int INITIAL_NO_OF_PANELS=4;
    
      public ArrayList panList=new ArrayList(); // not utilized in this code
    
      private JTabbedPane tabPane=new JTabbedPane(JTabbedPane.BOTTOM);
      private JPanel mainCtrlButtonPan = new JPanel();
      private JComboBox tabCombo = new JComboBox();
      private JButton newPanelBtn = new JButton("New Panel");
    
      public TabbedPanes() {
        try {
          initializeGUI();
          addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
              System.exit(0);
            }
          });
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
    
      /**
       * Create main frame contents
       */
      private void initializeGUI() {
    
        try {
          setupFrameGUI();
        } catch (Exception ex) {
          ex.printStackTrace();
          return;
        }
        /**
         * Add an initial set of panels to tabbed pane
         */
        for (int i=0; i<INITIAL_NO_OF_PANELS; i++) {
          JPanel pan=getNewTabPanel();
          tabPane.add(pan,pan.getName());
        }
      }
      /**
       * Application Frame GUI setup
       */
      private void setupFrameGUI()  {
    
        createMainControlsPanel();
    
        this.getContentPane().setLayout(new BorderLayout());
        this.getContentPane().add(tabPane, BorderLayout.CENTER);
        this.getContentPane().add(mainCtrlButtonPan, BorderLayout.SOUTH);
    
        newPanelBtn.addActionListener(this);
        tabPane.addChangeListener(this);
      }
      /**
       * Set up application-global controls
       */
      private void createMainControlsPanel() {
        tabCombo.setPreferredSize(new Dimension(200, 22));
        mainCtrlButtonPan.add(tabCombo, null);
        mainCtrlButtonPan.add(newPanelBtn, null);
      }
      /**
       * Create a new panel and at the same time add it to the tablist
       */
      public TabPanePanel getNewTabPanel () {
        TabPanePanel pan=new TabPanePanel(this);
    
        return pan;
      }
    
      /**
       * Handle button clicks & combox actions
       * @param ae
       */
      public void actionPerformed(ActionEvent ae) {
        System.out.println(ae);
    
        if (ae.getSource()==newPanelBtn) { // new panel
    
          TabPanePanel pan=getNewTabPanel();
          tabPane.add(pan,pan.getName());
    
        } else {
          /**
           * The action is from a panel in the tabbed pane, find out
           * which panel is active
           */
          TabPanePanel activePan=(TabPanePanel)tabPane.getSelectedComponent();
    
          if (ae.getActionCommand().equals("Kill")) { // delete panel
    
            killTab(activePan);
    
          } else if (ae.getActionCommand().equals("Add To Combo")) {
            /* get info from current panel */
            String s=activePan.getEnteredText();
            tabCombo.addItem(s);
          }
        }
      }
      /**
       * delete the currently active panel in the tabbedpane, but
       * ask the user first, do not allow all panels to be deleted.
       * @param activePan
       */
      private void killTab(JPanel activePan) {
        if (tabPane.getTabCount() == 1) {
    
          JOptionPane.showMessageDialog(this, "Cannot Kill all",
                                        "Close down instead",
                                        JOptionPane.ERROR_MESSAGE);
        } else {
    
          String tabTitle = tabPane.getTitleAt(tabPane.getSelectedIndex());
    
          int rep = JOptionPane.showConfirmDialog(this,
                                                  "Shall we kill off: "+
                                                  tabTitle + " ??");
    
          if (rep == JOptionPane.YES_OPTION) {
            tabPane.remove(activePan);
          }
    
        }
      }
      /**
       * Handle changes in the tabbed pane
       * @param e
       */
      public void stateChanged(ChangeEvent e) {
        System.out.println(e);
        JTabbedPane aTabbedPane=(JTabbedPane)e.getSource();
        JPanel pan=(JPanel)aTabbedPane.getSelectedComponent();
    
        System.out.println("name; "+pan.getName());
        System.out.println(pan.getLayout().toString());
        tabCombo.removeAllItems();
    
        getAllComponents(pan);
    
      }
      /**
       * Recursive method for finding all buttons, fields etc.
       * inside a Container
       * @param cont
       */
      private void getAllComponents(Container cont) {
        Component [] cmp=cont.getComponents();
        for (int i=0; i<cmp.length; i++) {
          /**
           * recurse if it is a container
           */
          if (cmp[i] instanceof Container) {
            getAllComponents( (Container) cmp[i]);
          }
          /**
           * put stuff of interest into the combobox
           */
          if (cmp[i] instanceof JLabel) {
            tabCombo.addItem(((JLabel)cmp[i]).getText());
          } else if (cmp[i] instanceof JButton) {
            tabCombo.addItem(((JButton)cmp[i]).getText());
          } else if (cmp[i] instanceof JTextField) {
            tabCombo.addItem(((JTextField)cmp[i]).getText());
          } else if (cmp[i] instanceof JTextArea) {
            tabCombo.addItem("Chars written: "+((JTextArea)cmp[i]).getText().length());
          }
    
        }
      }
      /****************************** MAIN *************************
       *
       * @param args
       */
      public static void main (String [] args) {
        TabbedPanes tpl=new TabbedPanes();
        tpl.setBounds(40,40,400,300);
        tpl.setVisible(true);
      }
    
    }
    /******************************************************************************
     * A little JPanel extension for stuffing into a JTabbedPane
     *
     *****************************************************************************
     */
    class TabPanePanel extends JPanel {
    
      JTextField tf=new JTextField("add this text");
      TabbedPanes tabPanes=null;
      String name=null;
    
      public TabPanePanel (TabbedPanes tabPanes) {
    
        this.tabPanes=tabPanes;
        tabPanes.panList.add(this);
    
    
        name="Flap #"+(tabPanes.panList.size());
    
        setLayout(new BorderLayout());
        JLabel lbl=new JLabel("This is pane: "+name);
        JTextArea ta=new JTextArea("Store "+name+" text here",
                                   20,60);
    
        add(lbl,BorderLayout.NORTH);
        add(ta,BorderLayout.CENTER);
    
        JPanel aTxtPan=getTextFieldPanel();
    
        add(aTxtPan,BorderLayout.SOUTH);
    
      }
      public String getName() {
        return name;
      }
      /**
       * Hand out the text entered by the user
       * @return
       */
      public String getEnteredText() {
        return tf.getText().trim();
      }
      /**
       * Create a new textfield panel with panel delete button
       * @return
       */
      private JPanel getTextFieldPanel() {
    
        JPanel pan=new JPanel(new BorderLayout());
        JButton btnHide=new JButton("Kill");
        JButton btnAdd=new JButton ("Add To combo");
    
        pan.add(btnAdd,BorderLayout.WEST);
        pan.add(btnHide,BorderLayout.EAST);
        pan.add(tf,BorderLayout.CENTER);
        btnHide.addActionListener(tabPanes);
        btnAdd.addActionListener(tabPanes);
    
        return pan;
      }
    }
    Last edited by sjalle; 03-27-2005 at 02:10 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center