JComboBox Help!

Hi All,
can anyone show me some good examples of how to fill up one combo Box with all the table names in a database, and when I select a table display all the column names in the another combo Box.
Thanks
Dave

This is basically what you want, except it updates a table instead of a JComboBox:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class DatabaseInformation extends JFrame implements ActionListener
    DatabaseMetaData dmd;
    ResultSet rs;
    ResultSetMetaData md;
    int columns;
    JComboBox comboBox;
    JTable table;
    String catalog;
    public DatabaseInformation()
        Vector columnNames = new Vector();
        Vector data = new Vector();
        try
            //  Connect to the Database
            String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
//            String url = "jdbc:odbc:someDSN";  // if using ODBC Data Source name
            String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/somedirectory/somdatabase.mdb";
            String userid = "";
            String password = "";
            Class.forName( driver );
            Connection connection = DriverManager.getConnection( url, userid, password );
            dmd = connection.getMetaData();
            //  Get the first Catalog
            rs = dmd.getCatalogs();
            if (rs.next())
                catalog = rs.getObject(1).toString();
                System.out.println( catalog );
            rs.close();
            //  Get Tables
            comboBox = new JComboBox();
            rs = dmd.getTables(catalog, null, null, new String[] { "TABLE" });
            md = rs.getMetaData();
            columns = md.getColumnCount();
            while (rs.next())
                   comboBox.addItem( rs.getObject(3) );
            rs.close();
        catch(Exception e)
            System.out.println( e );
        comboBox.addActionListener( this );
        getContentPane().add(comboBox, BorderLayout.NORTH);
        //  Create table with database data
        table = new JTable();
        JScrollPane scrollPane = new JScrollPane( table );
        getContentPane().add( scrollPane );
    public void actionPerformed(ActionEvent e)
        String table = (String)comboBox.getSelectedItem();
        displayTableColumns( table );
    private void displayTableColumns(String tableName)
        try
            //  Get Columns
            rs = dmd.getColumns(catalog, null, tableName, null);
            md = rs.getMetaData();
            int columns = md.getColumnCount();
            Vector columnNames = new Vector(columns);
            Vector data = new Vector();
            //  Get column names
            for (int i = 1; i <= columns; i++)
                columnNames.addElement( md.getColumnName(i) );
            //  Get row data
            while (rs.next())
                Vector row = new Vector(columns);
                for (int i = 1; i <= columns; i++)
                    row.addElement( rs.getObject(i) );
                data.addElement( row );
            rs.close();
            //  Reset Table
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            table.setModel( model );
        catch(Exception e)
            System.out.println( e );
    public static void main(String[] args)
        DatabaseInformation frame = new DatabaseInformation();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.pack();
        frame.setVisible(true);
}

Similar Messages

  • Adding items in JComboBox - Help

    Hy, I have a JComboBox() and a JTextField().
    when I input a name in the JTextField and clicks on the "Ok" button
    the name is added in the JComboBox().
    What I want is when I click on the "Ok" button, a check is made to see
    whether the name input in the JTextField already exist in the JComboBox().
    If is exist a message is displayed else it is added.
    How to perform the check.
    PLease send me code for doing this.
    thanks

    Hi.
    The JComboBox uses a model to get its hands on the elements to be displayed. Thus you must search the model to see if the string is already contained.
    Use something like this:
        public boolean contains(JComboBox comboBox, String s) {
            int elementCount = comboBox.getModel().getSize();
            for (int i = 0; i < elementCount; i ++) {
                String t = (String)comboBox.getModel().getElementAt(i);
                if (t.equals(s))
                    return true;
            return false;
        }Hope this helps,
    Michael

  • Need JComboBox help

    I'm making app for working with database in SWING. And there is need in
    comboBoxes for some tables, e.g.
    table USER        .------------------.
            |id | name         |
            |------------------|
            | 1 | John         |
            | 2 | Alex         |
            |...| .........    |
            .------------------.I need to create JComboBox showing "John" and value sould be "1".
    Could you please gimme a link or paste here some sample code making this.

    You would have to implement your own ComboBoxModel that uses uses a map (the default model uses a list), which means you would have to implement all the methods in the javax.swing.ComboBoxModel interface (which consists of methods from javax.swing.ListModel as well). Your code might look like these:
    public class MapComboBoxModel implements ComboBoxModel {
        //--- some additional methods other than those stated in ComboBoxModel interface
        public int getValueAt(int index) {
            return ((Integer) data.get(getElementAt(index))).intValue();
        public void addData(int value, Object element) {
            data.put(new Integer(value), element);
        Map data = new HashMap();
    }Add more code as you deem fit. Of course, your only way to retrieve the value can only be done thru the custom data model. You cannot retrieve the data through the methods available in the JComboBox class. So in your app, you would have to use the following code to retrieve the value:
    // assuming combo box is named cbox
    int value = ((MapComboBoxModel) cbox.getModel()).getValueAt(cbox.getSelectedIndex());Hope this helps.

  • Looking For JComboBox Help

    (Sorry about the lack of rendered tags. I don't know how to use them in this forum.)
    I have a JComboBox (a drop menu) that when opened clears all its items and then adds new items from a list. Whenever the list is augmented (and is small), the JComboBox's display size is too small, and it creates a little scrollbar to accomodate. When the popmenu is closed and reopened, the menu is normal. The problem is that when I open the menu after adding a new item to a list, I have to triple click the JComboBox to make it display correctly.
    Numbers 2 and 4 are unwanted displays.
    <img src="http://img.photobucket.com/albums/v251/Trinithis/dynamicDrive/jcombobox.jpg" />
    I could fix it by having the button itself change the contents of the JComboBox (instead of popupMenuWillBecomeVisible()), but I want to have lazy evaluation for it because in my actual program the ArrayList will have to be sorted each time and the JComboBox will have to re-add all its contents. I suppose this is always an option, but I would like to know how to do it this or some other way.
    <pre>
    import javax.swing.*;
    import javax.swing.event.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    public class GUI extends JFrame implements ActionListener, PopupMenuListener {
         private JButton bAdd = new JButton("Add");
         private JComboBox jcb = new JComboBox();
         private ArrayList<String> items = new ArrayList<String>(10);
         private int addCount = 0;
         public GUI() {
              Container c = this.getContentPane();
              c.setLayout(new FlowLayout());
              bAdd.addActionListener(this);
              jcb.addPopupMenuListener(this);
              c.add(bAdd);
              c.add(jcb);
              this.setSize(200, 100);
              this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              this.setVisible(true);
         public void actionPerformed(ActionEvent e) {
              Object source = e.getSource();
              if(source==bAdd) items.add("Item #" + addCount++);
         public void popupMenuWillBecomeVisible(PopupMenuEvent e){
              Object source = e.getSource();
              if(source==jcb) {
                   jcb.removeAllItems();
                   for(int i=0; i<items.size(); ++i) jcb.addItem(items.get(i));
         public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}
         public void popupMenuCanceled(PopupMenuEvent e) {}
         public static void main(String[] args) {
              new GUI();
    </pre>
    Edited by: Trinithis on Sep 21, 2007 11:18 AM
    Edited by: Trinithis on Sep 21, 2007 11:29 AM
    Edited by: Trinithis on Sep 21, 2007 11:33 AM
    Edited by: Trinithis on Sep 21, 2007 11:34 AM

    try it a different way (not using the popupListener)
    public GUI() {
    Container c = this.getContentPane();
    c.setLayout(new FlowLayout());
    bAdd.addActionListener(this);
    jcb.setUI(new javax.swing.plaf.metal.MetalComboBoxUI(){
      protected JButton createArrowButton(){
        JButton btn = super.createArrowButton();
        btn.addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent me){
            if(jcb.getModel().getSize() < items.size()){
              DefaultComboBoxModel model = new DefaultComboBoxModel();
              for(int i=0; i<items.size(); ++i){
                model.addElement(items.get(i));
              jcb.setModel(model);
        return btn;
    //jcb.addPopupMenuListener(this);the tags you're looking for are
    [code]
    paste code here
    [/code]

  • The problem in JComboBox, help!

    Hi,
    My case is to forbid the users using Up and Down arrow key to access items in the list, but they can still use mouse to access items.
    But after I tried several ways, I still can't achieve that. I am using a editable comboBox. So, even my focus is in JTextField, when I press Up and Down arrow keys, the item list was still displayed on the screen. I don't want them appear, but only with mouse at that time.
    Does anybody know how to fix that?
    Many Thanks!
    Feng

    Try this code.
    regards,
    Stas
    JComboBox cb;
            KeyStroke ks = KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0);
            cb.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "MoveUp");
            cb.getActionMap().put("MoveUp", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("up key pressed");
            ks = KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0);
            cb.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks, "MoveDown");
            cb.getActionMap().put("MoveDown", new AbstractAction() {
                public void actionPerformed(ActionEvent e) {
                    System.out.println("down key pressed");
            });

  • The problem in using JComboBox. Need Help!

    HI,
    I am programming to make an address bar as IE? Now, I am using JComboBox as the address bar. I also read the article of "how to use JComboBox" in sun tutorial.
    The problem is I cann't make the icon and text together in the address bar. As in the tutorial article, I can make it there since the JComboBox is uneditable.
    My case is I still want the icon in the JTextField of JComboBox, but I am still able to input address into this JTextField as well.
    Is it able to add a JLabel into JTextField first, and then be able to input text exactly after this icon, then my problem is solved.
    Thanks!
    Feng

    Hi Feng,
    My suggestion is that you try out the JComboBox methods setEditor() and setRenderer(). They allow you to specify custom components that will be used to show the combo box items. You'll need to do a bit of work, but you'll probably be able to provide a custom component that will display your icon.
    Hope that helps!
    Shannon Hickey (Swing Team)

  • Help on Look-and-Feel of JComboBox

    Can anyone guide me on how to change the look-and-feel and style of a JComboBox? Is it possible? If yes, how?

    I was wondering about that myself... I want to change the look of a combobox, or any other component. I think I should do it with the following code
    public static void setLookAndFeel(String�className)
    but I don't know what className to use. If I am not mistaken it should be the name of the class that implements the Look and Feel, please help!

  • Help needed on JComboBox

    hi all ,
    I am curreently stuck up in handling a JComboBox
    Actually i need a editable JComboBox in which the user can select either from the drop down list or the user can type it in the text field
    Now if the user types few characters in the text field of JComboBox then if the user opens the drop down list, the drop down list should contain only the data which starts from the characters entered in the textfield
    Also user can select data directly from the drop down and on pressing ENTER the data will fill in the text field of JComboBox
    We can prune data from a Vector and populate the JCombobox as required but what i am not understanding and stuck up is on which Listener of JComboBox can i implement this type of Functionality
    I am new to Java Please help
    Thanking in advance
    Waiting in anticipation of help

    hi PhHein
    Actually i tried the suggested code in this manner but it didnt even call the selectionForKey() method
    i have a editable JcomboBox (non-editable doesnt work)
    jComboBoxModel.setKeySelectionManager(new MyKeySelectionManager());
    jComboBoxModel.addKeyListener(new java.awt.event.KeyAdapter() {
    public void keyPressed(KeyEvent e)
    MyKeySelectionManager manager = new MyKeySelectionManager();
    int found = 0;
    char chartyped = jtxtComboBoxModel.getText().charAt(0);
    found = manager.selectionForKey(chartyped,jComboBoxModel.getModel());
    System.out.println("FOUND "+found);
    Actually its not even going in the keyPressed event
    I tried by having a KeyListener on the textfield
    jtxtComboBoxModel = (JTextField)jComboBoxModel.getEditor().getEditorComponent();
    still of no use
    I am really badly stuck up
    someone please help
    I cant find a proper Listener which will do the work for me

  • JComboBox Problem !!!!!!!!!!!!!!!! PLzzzzzzzzzz Help me out frnds...

    Hiiiiiii frmdsss...........im n deep trouble and need ur help immediately......im havin this prob with JComboBox....heres d code.....
    public void actionPerformed(ActionEvent ae)
              JButton source=(JButton)ae.getSource();
              //JComboBox source1=(JComboBox)ae.getSource();
              if(b1.equals(source))
                   cb1.setEnabled(true);
                   try
                        cb1.removeActionListener(this);
                        cb1.removeAllItems();
                        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                        con=DriverManager.getConnection("jdbc:odbc:MyDataSource","sa","");
                        stmt=con.createStatement();
                        rs=stmt.executeQuery("select prod_model from product where prod_type LIKE 'Mobile'");
                        while(rs.next())
                             cb1.addItem(String.valueOf(rs.getString(1)));
                        con.close();
                   }catch(ClassNotFoundException c)
                        System.out.println("Error "+c);
                   catch(SQLException e)
                        System.out.println("Exception"+e.toString());
                   cb1.addActionListener(this);
    if(ae.getSource() == cb1)
                   /*try
                   {          //cb1.removeActionListener(this);
                             //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                             /*con=DriverManager.getConnection("jdbc:odbc:MyDataSource","sa","");
                             String selected_id=cb1.getSelectedItem().toString();
                             stmt=con.createStatement();
                             rs=stmt.executeQuery("SELECT * FROM PRODUCT WHERE prod_model LIKE 'S%'");
                             if(rs.next())
                                  JOptionPane.showMessageDialog(fr,"USER NAME IDENTIFIED","CONFIRMATION",JOptionPane.INFORMATION_MESSAGE);
                             con.close();          
                   /*catch(ClassNotFoundException c)
                        System.out.println("Error "+c);
                   catch(SQLException e)
                        System.out.println("EXception"+e.toString());
    It gives me a huge list of errors..........
    java.lang.ClassCastException
    at Order.actionPerformed(Order.java:86)
    at javax.swing.JComboBox.fireActionEvent(Unknown Source)
    at javax.swing.JComboBox.setSelectedItem(Unknown Source)
    at javax.swing.JComboBox.setSelectedIndex(Unknown Source)
    at javax.swing.plaf.basic.BasicComboPopup$ListMouseHandler.mouseReleased
    Source)
    at java.awt.AWTEventMulticaster.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.plaf.basic.BasicComboPopup$2.processMouseEvent(Unknown So
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)...
    PLzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz help me frnds.......i hve 2 submit this prjkt on Thursdy

    The forum is fore heping out othersAnd that is exactly what I did. You won't get much help in the future if you don't change your habbits. In fact I'm surprised you got help this time.
    It's your responsibility to make a question easy to read, not to make it difficult to read by (among other things):
    a) holding the repeat key down
    b) not spelling out words
    Heck you can't even post formatted code to make it easy for people to read. Do you write your code with every line left aligned? I doubt it and we don't want to read it either.
    So learn how to use the forum properly.

  • Help required on JComboBox

    Hi I have 500 customers in the database. I have to display the customer names in a JComboBox so that user will select the customer name. here i have a problem. pulling 500 customers at a time and displaying them in combobox will take time. the customers may even grow up to thousands. so i don't want to display all the customer names at once in the JComboBox. First i want to display 50 names and when customer pulls the scrollbar to the end of the JComboBox popup then i want to add another 50. How can i do this?
    kindly help me in this regard. Thanks in advance.

    I do not think users would normally prefer to scroll through thousands or more items in a combo box to pick their choice. You may want to redesign your GUI somewhat like splitting the data into categories and use two combos, one for categories and one for the data and populate the data one based on the value selected on the category one. In case splitting like this is not possible then you may consider to apply some filtering in your JComboBox/JTable so that users can select their choice as they type. I guess this may be of some help to you
    http://www.glazedlists.com/Home
    http://www.glazedlists.com/documentation/tutorial-100

  • Help with JcomboBoxes

    Hi,
    Im having trouble with a combobox
    I have created a bean class for an ftp site, that contains;
    - ftp site name
    - address
    - username
    - password
    I then create an array of these sites and add them to the jComboBox.
    I only want to display the ftp site name in the box, however, when i select a certain site, i then want to pass the rest of the info. (ie. address, username, and password) to a connect method i have in another class.
    I'm quite sure this is a reasonably simply task but i just cant get my head around it.
    can anybody please help me?
    Much Thanks!

    Check out this posting for a solution:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=613731

  • JComboBox is driving me crazy!!  Help,please??

    Hello!!
    The problem is that i have to get the MouseEvents whenever a user enters or exits or clicks mouse on an item inside JComboBox.
    Is there anyway to get the mouseEvents? I ve tried adding a lot of listeners but nothing works.
    Thanks a lot!

    Try this.
    When you click on the comboBox, the label is updated.
    Hope this help.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class ListDemo extends JFrame {
      JPanel jPanel1 = new JPanel();
      JLabel jLabel1 = new JLabel();
      JComboBox jComboBox1 = new JComboBox();
      public ListDemo() {
        for(int i = 0 ; i < 10 ; i++){
          jComboBox1.addItem("item n?"+i);
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      private void jbInit() throws Exception {
        jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
        jLabel1.setText("jLabel1");
        jComboBox1.addActionListener(new ListDemo_jComboBox1_actionAdapter(this));
        this.getContentPane().add(jPanel1, BorderLayout.NORTH);
        jPanel1.add(jComboBox1, null);
        this.getContentPane().add(jLabel1, BorderLayout.CENTER);
      void jComboBox1_actionPerformed(ActionEvent e) {
        this.jLabel1.setText(this.jComboBox1.getSelectedItem().toString());
        System.out.println("event for the comboBox");
      public static void main(String[] args){
           ListDemo temp = new ListDemo();
           temp.pack();
           temp.setVisible(true);
    * listener for the comboBox
    class ListDemo_jComboBox1_actionAdapter implements java.awt.event.ActionListener {
      ListDemo adaptee;
      ListDemo_jComboBox1_actionAdapter(ListDemo adaptee) {
        this.adaptee = adaptee;
      public void actionPerformed(ActionEvent e) {
        adaptee.jComboBox1_actionPerformed(e);
    [\code]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • JComboBox doesn't show data...help please

    I have created a JComboBox. I place an array of strings in that jcombobox. I'm sure the data is there, however, it is not shown.
    I traced the problem back to light/heavy weight problems.
    When i use a lightweight JComboBox it doesn't drop down at all.
    This is probably because there's a JLabel under it.
    However, when i mean it an heavyweight object
    (by calling PopupMenu.setLightWeightPopupEnabled(false) )
    the dropdown shows up but it is empty.
    Has anyone had the same problem or something similar?
    help would be appreciated...
    thanx.

    Well here's a code snippet:
    JPopupMenu.setDefaultLightWeightPopupEnabled(false);
    Calendar cal = Calendar.getInstance();
    Integer[] years = new Integer[21];
    Integer[] months = new Integer[13];
    Integer[] days = new Integer[32];
    for(int i = 0; i < 20; i++)
    years[i] = new Integer(cal.get(Calendar.YEAR) + i);
    startDateYear = new JComboBox(years);
    startDateYear.setMaximumRowCount(3);
    Now here you see how i fillup the JComboBoxes, i've already verified that there actually are objects in the JComboBox so that's not the problem.
    the first line of code is to make the JComboBoxes make a popupmenu that's heavyweight.
    so it should be in front of other lightweighted components (namely a JLabel underneath the JComboBox ) .
    Now i see it drop down, however it shows absolutely no data. It doesn't even show a scrollbar, you can just see gray space outline of where the dropdown menu of the JComboBox should be.
    does this help?

  • Web Guy Using Swing - Need Help With jComboBox

    I'm new to doing desktop Java development (come from a web application background) and am trying to accomplish migrating some of a web application's functionality to a desktop app for distribution. I'm already a bit stuck when it comes to using the jComboBox. What is intuitive to me in the web world would be to have one combo box/select box that after making a selection, it returns it's value so I could use that to run another query that would populate the next drop down menu. Populating the display of the combo box isn't the problem, that seems easy enough, but what I so far can't find is how I can attach a value to the combo box; that is for instance, having the drop down show a list of country names, and needing to have that list of country names correspond to a country code. For the web, you'd just have the option value tied to the code and the contents of the option be the name.
    Is this do-able? Am I completely thinking about this in the wrong way when working in desktop GUI things? I am using NetBeans 6.0 for my GUI layout and such, don't know if that helps or hurts matters. Also currently using Java 1.5.
    Any information or points in the right direction are greatly appreciated.
    Cheers.

    If I understand you correctly, you need to have a class that holds country name and country code, with a toString override method that returns just the country name (this is what the combobox shows). You then put an array of these objects in your jcombobox, obtain the selected object, get it's country code, and you're off and running.
    Edited by: Encephalopathic on Mar 31, 2008 3:26 PM

  • JComboBox tree like structure needed, help help help plz.

    I would like to create a JComboBox that display the filesystem
    in a tree format, much like the way the FileChooser class
    displays directories in its dropdown combobox. Is there any
    sample code around for doing this, I not getting very far with
    this and any help would be greatly appreciated.
    Thanks!

    Maybe your extension of the class TreeCellRenderer should return a combo box in the method getTreeCellRendererComponent(.....)

Maybe you are looking for

  • Facing error while running jsp page in jdev10g ADF

    Hi, I am not able to run pages of an application created in Jdev ADF.I am facing this error. can anybody help me out??? JBO-30003: The application pool (model.ChakDeTrackersLocal) failed to checkout an application module due to the following exceptio

  • HDD Formats - Other than 2GB limit, should FAT32 work OK with FCE4?

    I know about the 2GB filesize limit, but are there any other limitations when using FAT32 format for my external drive with FCE4? Have been using this setup for more than six months, but I've got a really weird problem going on with some AVCHD clips

  • Facing problem while unloading the SWF file in SWF Loader

    Facing problem with SWF Loader. Background: I've 4 SWF files (demo1.swf, demo1_skin.swf, demo2.swf and demo2_skin.swf). These swf files are created throgh Adobe Captivate. Playing demo1_skin, will play the demo1.swf with the controls at the button su

  • Date Formats (dd/mm/yyyy and mm/dd/yyyy)

    Is there anyway to change the date format from mm/dd/yyyy to dd/mm/yyyy? I'm using XP and have changed all settings I can to UK from US but nothing changes. It's quite frustrating as I am used to the UK system. Thanks.

  • Display Costs on Accounting Tab in Company Code (object / Project) curerncy

    Hello Forum Experts, We have this major issue whereas teh costs on the Accounting Tab are shown in Controlling Area Currency. It seems this is the standard cProjects behaviour. What changes / enhancement do we have to implement to ensure that the cos