Page 1 of 2 12 LastLast
Results 1 to 20 of 28
  1. #1
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default Populating databasefields in combobox

    I have a table called location with two fields "Code","Country".
    What is the best way to get the data in this fields in a combobox?
    The purpose is to let a user select the country via code and country.

  2. #2
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    I have a table called location with two fields "Code","Country".
    What is the best way to get the data in this fields in a combobox?
    The purpose is to let a user select the country via code and country.
    My guess is that Country and Code are functionally dependent, i.e f(Code) == Country and f^-1(Country) == Code. I'd read the entire ResultSet, glue the two fields together for each row (make it one String) and populate the JComboBox.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    Only problem is, that i get one result. And its a strange result { :: null United States US ::}

    Code in view:
    Java Code:
    this.jComboBoxLocation.addItem(Database.DatabaseConnectie.getLocation().toString());
    Code in dataconnection class
    Java Code:
     public static HashMap<String, Airport> getLocation(){
            HashMap<String, Airport> location = new  HashMap<String, Airport>();
            try {
                PreparedStatement pstmt;
    
                pstmt = con.prepareStatement("Select * from location;");
    
                ResultSet rs = pstmt.executeQuery();
    
                while (rs.next()) {
                    Airport loc = new Airport();
                    loc.setCountryCode(rs.getString("landcode"));
                    loc.setCountry(rs.getString("country"));
                    location.put(loc.getName(),loc);
                }
            }
            catch (SQLException ex) {
                Logger.getLogger(DatabaseConnectie.class.getName()).log(Level.SEVERE, null, ex);
            }
            return location;
        }

  4. #4
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    I'm using an arraylist now, same result.
    The whole resultset comes in one row of the combobox

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    I'm using an arraylist now, same result.
    The whole resultset comes in one row of the combobox
    Put a System.out.println( ... ) call inside that while loop body and see how many results are fetched from your database. The System.out.println( ... ) statement is a fine debugging tool, use it.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  6. #6
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    Well it got i almost to work.

    I'm doing the following in the view:
    Java Code:
    for(int i = 0; i < n ; i++)
                this.jComboBoxLocation.addItem(Database.DatabaseConnectie.getLocation().get( i ));
    Now i get:

    null : : Austria : AT : null
    null : : Belgium : BE : null


    So thats good, only why the nulls, when i only ask the Country and the Code, from a table who has only the country and the code.
    Last edited by aborgeld; 05-07-2011 at 03:34 PM.

  7. #7
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    It gets more info from the Airport class so i made a new Location class because its a table, and now i get

    Austria : AT
    Belgie : BE

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    It gets more info from the Airport class so i made a new Location class because its a table, and now i get

    Austria : AT
    Belgie : BE
    That getLocation() method returns an entire List or Map or whatever full of locations. You call that method over and over again in your loopmwhere you populate your JComboBox; I find that smelly ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    What would you recommand?

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    What would you recommand?
    Something like this:

    Java Code:
    List results= getLocation( ... ); // only hit the db once
    for (int i= 0, n= results.size(); i < n; i++)
       // populate a JCombobox with result.get(i);
    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  11. #11
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,236
    Rep Power
    7

    Default

    If I understand the question then you want something like:

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    
    public class ComboBoxItem extends JFrame implements ActionListener
    {
    	public ComboBoxItem()
    	{
    		Vector model = new Vector();
    		model.addElement( new Item(1, "car" ) );
    		model.addElement( new Item(2, "plane" ) );
    		model.addElement( new Item(4, "boat" ) );
    		model.addElement( new Item(3, "train" ) );
    		model.addElement( new Item(5, "boat aadf asfsdf a asd asd" ) );
    
    		JComboBox comboBox;
    
    		//  Easiest approach is to just override toString() method
    		//  of the Item class
    
    		comboBox = new JComboBox( model );
    		comboBox.addActionListener( this );
    		getContentPane().add(comboBox, BorderLayout.NORTH );
    
    		//  Most flexible approach is to create a custom render
    		//  to diplay the Item data
    		//  Note this approach will break keyboard navigation if you don't
    		//  implement a default toString() method.
    
    		comboBox = new JComboBox( model );
    		comboBox.setRenderer( new ItemRenderer() );
    		comboBox.addActionListener( this );
    		getContentPane().add(comboBox, BorderLayout.SOUTH );
    	}
    
    	public void actionPerformed(ActionEvent e)
    	{
    		JComboBox comboBox = (JComboBox)e.getSource();
    		Item item = (Item)comboBox.getSelectedItem();
    		System.out.println( item.getId() + " : " + item.getDescription() );
    	}
    
    	class ItemRenderer extends BasicComboBoxRenderer
    	{
    		public Component getListCellRendererComponent(
    			JList list, Object value, int index,
    			boolean isSelected, boolean cellHasFocus)
    		{
    			super.getListCellRendererComponent(list, value, index,
    				isSelected, cellHasFocus);
    
    			if (value != null)
    			{
    				Item item = (Item)value;
    				setText( item.getDescription().toUpperCase() );
    			}
    
    			return this;
    		}
    	}
    
    	class Item
    	{
    		private int id;
    		private String description;
    
    		public Item(int id, String description)
    		{
    			this.id = id;
    			this.description = description;
    		}
    
    		public int getId()
    		{
    			return id;
    		}
    
    		public String getDescription()
    		{
    			return description;
    		}
    
    		public String toString()
    		{
    			return description;
    		}
    	}
    
    	public static void main(String[] args)
    	{
    		JFrame frame = new ComboBoxItem();
    		frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    		frame.pack();
    		frame.setVisible( true );
    	 }
    
    }
    Last edited by camickr; 05-07-2011 at 04:22 PM.

  12. #12
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    Josh,

    It works and you where right in your comment. And Darryl to.

    The output in the combobox is now:
    AT : Austria
    BE : Belgium

    But can i query on AT and BE only instaed of query on AT: Austria or BE: Belgium.

    The users can choose BE : Belgium and then i want the system to fill two textboxes.
    One with the code BE, the other one with the Country.

    In code i will set the countryCode and set the countryName.

  13. #13
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    Josh,

    It works and you where right in your comment. And Darryl to.

    The output in the combobox is now:
    AT : Austria
    BE : Belgium

    But can i query on AT and BE only instaed of query on AT: Austria or BE: Belgium.

    The users can choose BE : Belgium and then i want the system to fill two textboxes.
    One with the code BE, the other one with the Country.

    In code i will set the countryCode and set the countryName.
    Nothing a bit of String fiddling can't solve: get the selected item from the JComboBox; you know it has the form <code> : <country> so the split(":") method call can help you out.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  14. #14
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,242
    Rep Power
    19

    Default

    Um, the selected item isn't a String.

    The displayed <code> : <country> is the toString() representation of the item.

    db

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by DarrylBurke View Post
    Um, the selected item isn't a String.

    The displayed <code> : <country> is the toString() representation of the item.

    db
    You are right and I goofed but it's Saturday evenening so I'm forgiven so it doesn't count ;-)

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  16. #16
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    No worries, i'm glad you helped me this far.

    I have <code> : <country> for user display, but i want to check the code for filling in the textbox. I still need to get a string from my list am i right? Maybe with a cast.

  17. #17
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    No worries, i'm glad you helped me this far.

    I have <code> : <country> for user display, but i want to check the code for filling in the textbox. I still need to get a string from my list am i right? Maybe with a cast.
    You populate your JComboBox with Airport objects; those objects have a toString() method (you must've written it yourself) that show <code> : <country> as their String representation. When you fetch a selected element from your JComboBox you still get an Airport object (as Darryl correctly pointed out). It's up to you how you want to handle that.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  18. #18
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    well i just need it for compare so it does not need to be an aiport, i changed it to string.
    But has anybody have a good method to get the first 2 or 3 characters out of my arraylist.

    So i now got:
    AT : Australia
    BE : Belgium
    and so on

    and i want

    AT
    BE

    So i can check it with the data in the database or in this case the textbox.

  19. #19
    aborgeld is offline Senior Member
    Join Date
    Dec 2010
    Location
    The Hague
    Posts
    114
    Rep Power
    0

    Default

    So i have made the Arraylist to string and my combobox works.
    But when i try something like this i get a out of bounds error.
    Java Code:
      StringBuilder sb = new StringBuilder();
    
     for (String s: results){
                  s=sb.substring(0, 4);
                 System.out.println(s);
            }
    Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.AbstractStringBuilder.substring(Abstract StringBuilder.java:879)
    at java.lang.StringBuilder.substring(StringBuilder.ja va:55)

  20. #20
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,529
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by aborgeld View Post
    So i have made the Arraylist to string and my combobox works.
    But when i try something like this i get a out of bounds error.
    Java Code:
      StringBuilder sb = new StringBuilder();
    
     for (String s: results){
                  s=sb.substring(0, 4);
                 System.out.println(s);
            }
    Exception in thread "AWT-EventQueue-0" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
    at java.lang.AbstractStringBuilder.substring(Abstract StringBuilder.java:879)
    at java.lang.StringBuilder.substring(StringBuilder.ja va:55)
    From the stack trace I can see that sb is s StringBuilder. When do you fill it?

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Page 1 of 2 12 LastLast

Similar Threads

  1. populating combo box
    By newto in forum New To Java
    Replies: 11
    Last Post: 11-25-2010, 08:53 AM
  2. Need help: Populating data
    By rahul202 in forum Java Servlet
    Replies: 0
    Last Post: 10-25-2010, 07:16 PM
  3. populating a JList
    By hariza in forum AWT / Swing
    Replies: 2
    Last Post: 09-30-2010, 03:53 AM
  4. Populating a JTable
    By toymachiner62 in forum New To Java
    Replies: 2
    Last Post: 10-13-2009, 05:56 AM
  5. Error when populating the data
    By srinivas_k543 in forum Java Servlet
    Replies: 2
    Last Post: 07-10-2009, 08:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •