Loading a JComboBox

B

bruce

I am using NetBeans for my development.

I want to load a combobox with two pieces of information, namely the
data from a SELECT of a primary key and a datafield. How can I do
this?

I thought about creating an Object containing the Key and the
datafield, but couldn't figure out how to display the "datafield" in
the dropdown list.

Appreciate any help.

Thanks...

Bruce
 
E

Eric Sosman

I am using NetBeans for my development.

I want to load a combobox with two pieces of information, namely the
data from a SELECT of a primary key and a datafield. How can I do
this?

I thought about creating an Object containing the Key and the
datafield, but couldn't figure out how to display the "datafield" in
the dropdown list.

It's pretty straightforward. There are several ways to do
it; here's one:

Object[] items = new Object[] { theKey, theDataField };
JComboBox cbox = new JComboBox(items);

Then add the combo box to your JPanel or whatever, and eventually to
a JFrame, pack() and setVisible(true).

Or if the combo box already exists in the GUI and you want to
change the list of items it displays and selects from:

Object[] items = ...as above...;
JComboBox cbox = ...the existing combo box...;
cbox.setModel(new DefaultComboBoxModel(items));

There are additional variations, too, but these should get you
started. If they don't, please explain your difficulty in more detail
than "couldn't figure out" and show us what you've tried.
 
B

bruce

I am using NetBeans for my development.
I want to load a combobox with two pieces of information, namely the
data from a SELECT of a primary key and a datafield.  How can I do
this?
I thought about creating an Object containing the Key and the
datafield, but couldn't figure out how to display the "datafield" in
the dropdown list.

     It's pretty straightforward.  There are several ways to do
it; here's one:

        Object[] items = new Object[] { theKey, theDataField };
        JComboBox cbox = new JComboBox(items);

Then add the combo box to your JPanel or whatever, and eventually to
a JFrame, pack() and setVisible(true).

     Or if the combo box already exists in the GUI and you want to
change the list of items it displays and selects from:

        Object[] items = ...as above...;
        JComboBox cbox = ...the existing combo box...;
        cbox.setModel(new DefaultComboBoxModel(items));

     There are additional variations, too, but these should get you
started.  If they don't, please explain your difficulty in more detail
than "couldn't figure out" and show us what you've tried.

I think I don't know how to do line 2
JComboBox cbox = ...the existing combo box...;

Here is what I have

Object[][] items = new Object[][]{
{1, "BridgeMill Family Medical Associates, PC"},
{4, "Diagnostic and Imaging Services",},
{3, "Northside Hospital - Cherokee"}};

JComboBox cbox = cboTestLoad;
cbox.setModel(new DefaultComboBoxModel(items));

I'm getting [Ljava.lang.Object;@f9f9d8, [Ljava.lang.Object;@87816d and
[Ljava.lang.Object;@422ede
loaded into the combobox..

So it's obvious I'm doing something wrong. Suggestions on what it is!!

Thanks for the help....

Bruce
 
M

markspace

Object[][] items = new Object[][]{
{1, "BridgeMill Family Medical Associates, PC"},
{4, "Diagnostic and Imaging Services",},
{3, "Northside Hospital - Cherokee"}};

JComboBox cbox = cboTestLoad;
cbox.setModel(new DefaultComboBoxModel(items));


The DefaultComboBoxModel takes a single dimensioned array as it's
parameter, not a two dimensional array. That's why you are seeing
arrays as the items in your box model.

Remove the 2nd array for this to work. What do 1,4,3, represent? If
it's some sort of internal coding you'll have to make a new type to
cache it.

E.g.:

class ComboHolder {
final private String display;
final private int num;

public ComboHolder( String display, int num )
{
this.display = display;
this.num = num;
}

@Override
public String toString()
{
return display;
}

public int getNum()
{
return num;
}

}

Here's an example:


package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JCoboboxTest {

public static void main( String[] args )
{
SwingUtilities.invokeLater( new Runnable()
{

public void run()
{
initGui();
}
} );
}

private static void initGui() {
JFrame jf = new JFrame("ComboTest");
JPanel jp = new JPanel();
ComboHolder[] model = {
new ComboHolder( "String 1", 1),
new ComboHolder( "String 4", 4),
new ComboHolder( "String 3", 3),
};
JComboBox combo = new JComboBox( model );
jp.add( combo );
jf.add( jp );
combo.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println( ((ComboHolder)((JComboBox)e.getSource())
.getSelectedItem()).getNum() );
}
} );

jf.pack();
jf.setLocationRelativeTo( null );
jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
jf.setSize( 300, 300 );
jf.setVisible( true );
}
}
 
B

bruce

Object[][] items = new Object[][]{
             {1, "BridgeMill Family Medical Associates, PC"},
             {4, "Diagnostic and Imaging Services",},
             {3, "Northside Hospital - Cherokee"}};
         JComboBox cbox = cboTestLoad;
         cbox.setModel(new DefaultComboBoxModel(items));

The DefaultComboBoxModel takes a single dimensioned array as it's
parameter, not a two dimensional array.  That's why you are seeing
arrays as the items in your box model.

Remove the 2nd array for this to work.  What do 1,4,3, represent?  If
it's some sort of internal coding you'll have to make a new type to
cache it.

E.g.:

class ComboHolder {
    final private String display;
    final private int num;

    public ComboHolder( String display, int num )
    {
       this.display = display;
       this.num = num;
    }

    @Override
    public String toString()
    {
       return display;
    }

    public int getNum()
    {
       return num;
    }

}

Here's an example:

package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JCoboboxTest {

    public static void main( String[] args )
    {
       SwingUtilities.invokeLater( new Runnable()
       {

          public void run()
          {
             initGui();
          }
       } );
    }

    private static void initGui() {
       JFrame jf = new JFrame("ComboTest");
       JPanel jp = new JPanel();
       ComboHolder[] model = {
          new ComboHolder( "String 1", 1),
          new ComboHolder( "String 4", 4),
          new ComboHolder( "String 3", 3),
       };
       JComboBox combo = new JComboBox( model );
       jp.add( combo );
       jf.add( jp );
       combo.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent e ) {
             System.out.println( ((ComboHolder)((JComboBox)e.getSource())
                     .getSelectedItem()).getNum() );
          }
       } );

       jf.pack();
       jf.setLocationRelativeTo( null );
       jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
       jf.setSize( 300, 300 );
       jf.setVisible( true );
    }

}

Thanks for the feedback. I'll work through it and map it my
application.

As for what I'm trying to do, this is from my initial posting:

I want to load a combobox with two pieces of information, namely
the
data from a SELECT of a primary key and a datafield. How can I
do
this?

The client selects a "datafield" from the dropdown. I then use the
"Primary Key" to extract the complete records from the database...

Thanks again...

Bruce
 
M

markspace

As for what I'm trying to do, this is from my initial posting:

I want to load a combobox with two pieces of information, namely
the
data from a SELECT of a primary key and a datafield. How can I
do
this?


Well, that's what I did for you. I made a JComboBox hold two pieces of
information instead of one. I had it display a string, and when the
user selected one of those strings, I printed out the number that
corresponded to that string on the console (called "num" in my example).
 
B

bruce

Well, that's what I did for you.  I made a JComboBox hold two pieces of
information instead of one.  I had it display a string, and when the
user selected one of those strings, I printed out the number that
corresponded to that string on the console (called "num" in my example).

Yes... I got your example to work. Thanks

Now I need to map to my application...

Appreciate the help....

Bruce
 
B

bruce

Object[][] items = new Object[][]{
             {1, "BridgeMill Family Medical Associates, PC"},
             {4, "Diagnostic and Imaging Services",},
             {3, "Northside Hospital - Cherokee"}};
         JComboBox cbox = cboTestLoad;
         cbox.setModel(new DefaultComboBoxModel(items));

The DefaultComboBoxModel takes a single dimensioned array as it's
parameter, not a two dimensional array.  That's why you are seeing
arrays as the items in your box model.

Remove the 2nd array for this to work.  What do 1,4,3, represent?  If
it's some sort of internal coding you'll have to make a new type to
cache it.

E.g.:

class ComboHolder {
    final private String display;
    final private int num;

    public ComboHolder( String display, int num )
    {
       this.display = display;
       this.num = num;
    }

    @Override
    public String toString()
    {
       return display;
    }

    public int getNum()
    {
       return num;
    }

}

Here's an example:

package test;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class JCoboboxTest {

    public static void main( String[] args )
    {
       SwingUtilities.invokeLater( new Runnable()
       {

          public void run()
          {
             initGui();
          }
       } );
    }

    private static void initGui() {
       JFrame jf = new JFrame("ComboTest");
       JPanel jp = new JPanel();
       ComboHolder[] model = {
          new ComboHolder( "String 1", 1),
          new ComboHolder( "String 4", 4),
          new ComboHolder( "String 3", 3),
       };
       JComboBox combo = new JComboBox( model );
       jp.add( combo );
       jf.add( jp );
       combo.addActionListener( new ActionListener() {
          public void actionPerformed( ActionEvent e ) {
             System.out.println( ((ComboHolder)((JComboBox)e.getSource())
                     .getSelectedItem()).getNum() );
          }
       } );

       jf.pack();
       jf.setLocationRelativeTo( null );
       jf.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
       jf.setSize( 300, 300 );
       jf.setVisible( true );
    }

}

Okay.. I get your example to run fine. When I tried to map it to my
application, my "Inexperience" became apparent. I need to load the
ComboHolder object from a resultSet. Here is what I tried.

while (resultSet.next()) {

int facilityid = resultSet.getInt("facilityid");
String facility = resultSet.getString("name");
ComboHolder[] model = {new ComboHolder(facility, facilityid)};
System.out.println(facilityid + ":" + facility);

}

1. I don't know that the ComboHolder is being loaded correctly with
the code above.

2. When I added "JComboBox cboFacility = new JComboBox( model );"
after the closing left bracket, I go that model was "out of scope." I
was unable to define anything (above the while statement) that would
work.

Sorry that was unable to map your sample code to my application..

Your "additional" help will be greatly appreciated...

Thank you again...

Bruce

My application compiled and executed with no problems.
 
M

markspace

2. When I added "JComboBox cboFacility = new JComboBox( model );"
after the closing left bracket, I go that model was "out of scope."


Yeah well this is a basic syntax question. I'm pretty much unwilling to
write your entire program for you. You'll have to learn what scope is
and how it works.

All I did was write a little example. I expected you to modify it a lot
more.

Try "java variable scope" on Google.
 
B

bruce

Yeah well this is a basic syntax question.  I'm pretty much unwilling to
write your entire program for you.  You'll have to learn what scope is
and how it works.

All I did was write a little example.  I expected you to modify it a lot
more.

Try "java variable scope" on Google.


Thanks.. I do appreciate your help..

I do know what scope is... That's not the problem.. I have not been
able to define "model" so that it would have the scope I need.

I tried several different instances of defining ComboHolder which
would have made "model" in the "JComboBox cboFacility = new
JComboBox( model );" in scope.
Each attempt gave me an error.

I also added a method to the ComboHolder class to accept the
assignment of individual (String, int) pairs. When I did this, I had
to remove the "final" from the class final variables.

So, I have been trying to do it myself.

I do appreciate the help you have given me....
 
B

bruce

Thanks.. I do appreciate your help..

I do know what scope is... That's not the problem.. I have not been
able to define "model" so that it would have the scope I need.

I tried several different instances of defining ComboHolder which
would have made "model" in the "JComboBox cboFacility = new
JComboBox( model );" in scope.
Each attempt gave me an error.

I also added a method to the ComboHolder class to accept the
assignment of individual (String, int) pairs. When I did this, I had
to remove the "final" from the class final variables.

So, I have been trying to do it myself.

I do appreciate the help you have given me....

I finally got it working... Learned a lot.. thanks..

Now a question if there is a better way of loading an existing
combobox then the following??

this.cboFacility.removeAllItems();
for (ComboHolder cbo : model) {
this.cboFacility.addItem(cbo);
}


Again, Thanks for your help...

Bruce
 
M

Martin Gregorie

Now a question if there is a better way of loading an existing combobox
then the following??
If possible I wouldn't use numbers as keys to rows in the database: I'd
use the values displayed in the JComboBox instead because its almost
always better to use natural keys in a database.

Where that wasn't possible, I'd put the JCombobox values and
corresponding numbers in a table:

create table key_translation
(
name char(10),
value int,
primary key(name)
);

This way you can populate the JComboBox with

select name from key_translation order by name;

and extend the relevant queries by joining key_translation to the table
(s) using the numeric key.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,228
Members
46,818
Latest member
SapanaCarpetStudio

Latest Threads

Top