Sort elements in JComboBox

Hi,
I need to sort elements in JComboBox. How can I do this.
thanks in advance

couple of ways in this thread
http://forum.java.sun.com/thread.jspa?forumID=31&threadID=616993

Similar Messages

  • Sort element inside JComboBox

    Hi,
    i have a JComboBox containing list of Strings
    so lets say:
    String[] test = {"omega", "alpha", "beta", "Arc"}
    JComboBox testing = new JComboBox(test);
    now is there a way to sort the elements inside the JComboBox once they have been inserted ? or anyone know how to sort the elements before putting them in inside JComboBox ?
    the sample code was just for testing and I am dealing with MANY elements (at least 10) inside the JComboBox
    thanks in advance
    if you have any links that helps with this topic, I will also appreciate it

    <hmm>
    1) Check out the [url http://java.sun.com/docs/books/tutorial/collections/index.html]Collections API
    2) Note that using a java.util.Vector, (which combo box accepts in its constructor), allows you to do
    one of two things:
    ............If you are using a custom object, have it implement Comparable
    ............If you are using flat Strings, never mind...
    Then calling java.util.Collections.sort(myVector) would do this for you. NOTE: by not implementing
    Comparable, this may have undesirable results....
    A number of collection objects sort by default when you add an element.....

  • How to get index of currently focussed element in JComboBox

    Hello
    I have an editable JComboBox and i have the following property set on it
    "JComboBox.lightweightKeyboardNavigation","Lightweight". THis enables the user to traverse using arrow keys without actually selecting each time.
    In this case how do i find out which element or value is in focus because the value in focus may be different from the selected value in the combo box.
    Please help!!!!!!!!
    Gunjan

    Try this:
    import java.awt.event.KeyEvent;
    import java.util.Vector;
    import javax.swing.ComboBoxModel;
    import javax.swing.JComboBox;
    public class LightWeightComboBox extends JComboBox {
    private int m_intSelectedIndex;
    public LightWeightComboBox() {
    super();
    init();
    public LightWeightComboBox(ComboBoxModel aModel) {
    super(aModel);
    init();
    public LightWeightComboBox(Object[] items) {
    super(items);
    init();
    public LightWeightComboBox(Vector items) {
    super(items);
    init();
    private void init() {
    // Enable lightweight keyboard navigation.
    putClientProperty("JComboBox.lightweightKeyboardNavigation", "Lightweight"); // JDK 1.3
    putClientProperty("JComboBox.isTableCellEditor", Boolean.TRUE); // JDK 1.4
    public void showPopup() {
    m_intSelectedIndex = getSelectedIndex();
    super.showPopup();
    private void updateSelectedIndex(int intKeyCode) {
    if (intKeyCode == KeyEvent.VK_UP) {
    m_intSelectedIndex--;
    if (m_intSelectedIndex < 0) {
    m_intSelectedIndex = 0;
    else if (intKeyCode == KeyEvent.VK_DOWN) {
    m_intSelectedIndex++;
    if (m_intSelectedIndex > (getItemCount()-1)) {
    m_intSelectedIndex = getItemCount()-1;
    public void processKeyEvent(KeyEvent e) {
    if (isPopupVisible()) {
    if ( (e.getID() == KeyEvent.KEY_RELEASED) && ( (e.getKeyCode() == KeyEvent.VK_UP) || (e.getKeyCode() == KeyEvent.VK_DOWN) ) ) {
    updateSelectedIndex(e.getKeyCode());
    else if ( (e.getID() == KeyEvent.KEY_RELEASED) && ( (e.getKeyCode() == KeyEvent.VK_SPACE) || (e.getKeyCode() == KeyEvent.VK_ENTER) ) ) {
    hidePopup();
    setSelectedIndex(m_intSelectedIndex);
    else if ( (e.getID() == KeyEvent.KEY_RELEASED) && ( (e.getKeyCode() == KeyEvent.VK_DOWN) || (e.getKeyCode() == KeyEvent.VK_SPACE) || (e.getKeyCode() == KeyEvent.VK_ENTER) ) ) {
    showPopup();
    if ( (e.getKeyCode() != KeyEvent.VK_ENTER) && (e.getKeyCode() != KeyEvent.VK_SPACE) ) {
    super.processKeyEvent(e);
    }

  • Sorting elements in the X axis in BAM

    Hi all,
    Is there a way to sort how elements are shown in the X axis? For example, I have an Order graphic showing quantity of orders grouped by state of the order but I'd like the states to be in the order they appear in the business process.
    Thanks,
    Daniel

    Have another column in the Data Object stating order populate this column with 0,1,2,3,4......for the order you want for the states. And select both ur state and order column in group by option

  • How to sort elements in Hashtable.

    I am adding elements in sorted order in Hashtable. But when I iterate through the Hashtable using 'Enumeration' on the keys the the elements are not fetched in sorted order. I want to retrieve the keys in sorted order. How can we fetch the keys on sorted order?
    import java.util.* ;
    public class temp
         public static void main(String [] abc)
              Hashtable hashList = new Hashtable();
              hashList.put("1","One");
              hashList.put("2","Two");
              hashList.put("33","Three");
              hashList.put("44","Four");
         Enumeration keys = hashList.keys();
         while(keys.hasMoreElements() )
                        System.out.println("Key: " + keys.nextElement());
    Output for this is -
    Key: 2
    Key: 1
    Key: 33
    Key: 44

    obtain a set view of the keys contained in this Hashtable and sort it.

  • Sorting elements by category - is this possible in Muse?

    I have a page that may eventually have 100+ groups of 3 separate elements, which all are connected with a musical artist. I would like the user to be able to sort through the list based on categories I create.
    Here is the current site - http://www.vfepedals.com/support-an-artist.html
    Here's an example of how another website does something very similar: http://www.jhspedals.com/
    Ideally, it would sort through multiple elements, and each set would be contained in a fixed rectangular box (so I'm basically sort empty boxes that multiple elements could go in, much like LIghtbox).
    There are many places on my website that this could be employed to make the site look better and be easy-to-navigate.
    Is this possible in Muse? If so, how? What widgets do I need? I'm willing to invest some money if that's what it takes, but any solution will have to be something I can edit in Muse myself.

    Hi
    You can try to use toolitp where insert the categories in trigger and the items in container , so when user will click or hover over trigger it would show up the category clicked.
    The exact behavior that you have mentioned cannot be achieved without using custom code implementation, but with Muse widget you can achieve a similar effect.
    Additionally you can checkout few interesting widgets in library to use :
    http://muse.adobe.com/exchange
    Thanks,
    Sanjit

  • Jtable sorting column having Jcombobox renderer

    Hi
    I am trying to sort Jtable column having Jcombobox renderer , please can you give me some idea to do it.
    already tried with JDK1.6 table.setAutoCreateRowSorter(true);

    To get better help sooner, post a [_SSCCE_|http://mindprod.com/jgloss/sscce.html] that clearly demonstrates your problem.
    Use code tags to post codes -- [code]CODE[/code] will display asCODEOr click the CODE button and paste your code between the {code} tags that appear.
    db

  • Sorting elements within an array

    Hi, I'm working on a small piece of software and I've got to a little problem. The software has a Train class, which has two integers (departureTime and arrivalTime). In my main controlling class, there are methods to add Trains to a Trains array (called "trains"), to delete these trains, to display the trains present in the form of a timetable, etc.
    I am trying to get it so that the trains, when the user decides to display the timetable, are display in ascending order based on their departureTime. I can't use a simply Array.sort() as the array is an array of Train objects, and not of the integers themselves.
    I've played round with FOR loops, etc. I have a Time class, which has in it a method that goes as follows...
    public int compare(Time t) {
    // compare this Time with Time t
    if (this.minutes == t.minutes) return 0;
    if (this.minutes > t.minutes) return 1;
    return -1;
    So I can easily find out whether the individual train is sooner or later than the other, but it is a case of doing this in such a way that the trains end up in an order in the array of ascending numerical order by the departureTime.
    A seperate array could be created, "displayTrains" which holds them in, that would be fine. I only need the trains to be sorted by departuretime for the display method, they can be in any order in the rest of the program.
    Any ideas? The following is what I have so far for the display method, though where the sorting code will go there is a comment....
    //method to display the trains currently in the system, in departure time order
    public static void displayTrains() {
    String trainsDisplay="", sdeptTime, sarrTime, sjourTime;
    Time deptTime = new Time();
    Time arrTime = new Time();
    Time jourTime = new Time();
    Time sortDeptTimeA = new Time();
    Time sortDeptTimeB = new Time();
    Train [] displayTrains = new Train[numberTrains];
    int counter1=0, counter2=0, counter=0, compare, arrayPos=0;
    boolean earlier=false;
    //code to sort here
    trainsDisplay = "Loughborough to Leicester Train Timetable:\n\n";
    for (counter=0; counter<numberTrains; counter++) {
    deptTime = trains[counter].getDepartureTime();
    arrTime = trains[counter].getArrivalTime();
    jourTime = trains[counter].getJourneyTime();
    sdeptTime = deptTime.toString();
    sarrTime = arrTime.toString();
    sjourTime = jourTime.toString();
    trainsDisplay = trainsDisplay + "Departure: " + sdeptTime +
    " Arrival: " + sarrTime + " Duration: " + sjourTime + "\n";
    JOptionPane.showMessageDialog(null, trainsDisplay);
    I would really appreciate any ideas people have, I'm learning Java at the moment, so if its really simple, then the code would also be greatly appreciated!
    Kindest regards,
    David.

    Okay, create another class that implements the Comparator interface, e.g.TrainComparator and then one of its methods should be compareTo(Object,Object)
    public class TrainComparator implements Comparator {
        public int compareTo(Object o1, Object o2) {
    }How compareTo is implemented is up to you. But you should return a negative int if o1 is less than o2, 0 if o1 is equal to o2 and a positive integer if o1 is greater than o2. You can cast o1 and o2 as Train objects and call methods from that class to help you.

  • Sort Second Element in Array of Strict Type Def Clusters

    I need to sort the an array of strict type def clusters by the second or third element in the cluster.  In the past I have used 1-D array sort and sorted by the first element of the cluster.  When I need to sort by the second, third, or fourth element of the cluster I just break down the cluster and rebuild it placing the desired sort element in the first position of the new cluster.  This works for simple tasks and clusters, but as the cluster gets more complicated this becomes a pain to do this.  There must be a cleaner way to sort by other elements within the original array of strict type def clusters.  Has anyone succeeded in doing this a different way?

    Hello,
    Here's the way I would do it...just create a new cluster array, where each cluster contains two elements...the unbundled item you want to sort by, and the cluster itself.  Then sort the new cluster array, then unbundle the sorted cluster array to get the original clusters (now sorted).  Here is a screenshot:
    There may be a better way, but this is the first thing I thought of.
    -D
    Message Edited by Darren on 03-16-200610:00 AM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Sorted_cluster.jpg ‏30 KB

  • Get sorted distinct element from XML message in BPEL

    Hi,
    I have a database adapter which picks all the records with status 'N', it has different batch IDs.
    My requirement is to get all the distinct batch ID from the message collection, is it possible I can get the distinct batchID in ascending order in while process activity?
    Please help me if anyone have idea.
    Thanks in advance.
    Regards,
    Sreejit

    Sreejit,
    You can not sort element in the While activity. You need to use <xsl:sort/> to sort elements.
    See the following articles for <xsl:sort/> :
    http://www.w3schools.com/xsl/el_sort.asp
    http://www.dpawson.co.uk/xsl/sect2/N6461.html#d10242e19
    Regards,
    Dharmendra
    http://soa-howto.blogspot.com

  • Multiple key strokes in editable JComboBox for sorting

    I want to sort values of JComboBox based on key strokes in the combo. By default, JComboBox traps only one character "public int selectionForKey(char aKey,ComboBoxModel aModel)". I want to have this behaviour based on multiple character typed, e.g.
    Combo has following values:
    South - Ana
    Scotland - Ana
    Scotland - DTT
    SuperMacro
    My requirement is if the user types S, then the values should be sorted by S, if the user types C after S, then the values should be sorted by SC, if the user types O after S, then the values should be sorted by SO.
    Ravindra

    try implementing key listener instead.

  • Weird sorting behavior in AS

    Consider the code:
    var a:Array = new Array();
    a.push({str:"a", val:2});
    a.push({str:"b", val:3});
    a.push({str:"c", val:2});
    a.push({str:"d", val:2});
    a.push({str:"e", val:3});
    a.sortOn("val", 16);
    for (var i:int=0; i<=4; i++){
    trace(a
    .str + " -- " + a.val);
    It outputs:
    c -- 2
    d -- 2
    a -- 2
    b -- 3
    e -- 3
    Why does it change the original order - shouldn't the output
    be a,c,d,b,e - whereas the output is c,d,a,b,e? I tried it in both
    AVM1 and AVM2.
    Any clues would be greatly appreciated.
    Thanks,
    Pallav

    i don't think you can guarantee the order of sorted elements
    where the field you're sorting on is equal. for example, if you
    sortOn val again, the order changes again:
    a -- 2
    d -- 2
    c -- 2
    b -- 3
    e -- 3
    if you need it to retain original sort order where sort
    fields are equal you may have to write that sort routine yourself.
    alternatively, if it helps you could sort on two fields:

  • Trying to add a listener to a JComboBox in a JTable

    Hi all.
    I have a little problem which I can't resolve.
    I made a program in which I create a table using a class which extends JTable (but this isn't the point with the problem, I think. It's only for rendering purposes)
    In this table I put various types of items (such as Strings, JButton, JComboBox). I have no problem with the visualization of them, but the problem is with the listener for the combo boxes. I created a listener of my own and registered it in the constructor of the combo box editor, but when I change a value it's never fired. Can someone please help me?
    Here's some code which can help understanding the problem
    Combo box editor:
    public class MyComboBoxEditor extends DefaultCellEditor{
    public MyComboBoxEditor(JTableX _tabellaDiAppartenenza) {
    super(new JComboBox());                  
    (JComboBox)super.editorComponent).addItemListener(new MyItemListener((JComboBox)super.editorComponent));    
    public Component getTableCellEditorComponent(JTable arg0, Object arg1, boolean arg2, int arg3, int arg4) {
    String elementi[]=new String[((JComboBox)arg1).getItemCount()];
    for(int i=0;i<((JComboBox)arg1).getItemCount();i++){
    elementi=(String)((JComboBox)arg1).getItemAt(i);
    super.editorComponent=new JComboBox(elementi);
    return super.getTableCellEditorComponent(arg0, arg1, arg2, arg3, arg4);
    }combo box listener:public class MyItemListener implements ItemListener{
    private JComboBox combo;
    public MyItemListener(JComboBox object){
    combo=object;
    public void itemStateChanged(ItemEvent arg0) {
    int changeEvent = arg0.getStateChange();
    if(changeEvent==ItemEvent.SELECTED){
    Object value=arg0.getItem();
    combo.setSelectedItem(value);
    }table:public class JTableX extends JTable{
    protected MyCellEditorModel myCellEditorModel;
    public JTableX(MyDataModel tm){
    super(tm);
    Object ge = defaultEditorsByColumnClass.get(Boolean.class);
    DefaultCellEditor dce = (DefaultCellEditor)ge;
    dce.setClickCountToStart(0);
    MyButtonEditor mbe = new MyButtonEditor(new JCheckBox("Bottone"), this);
    mbe.setClickCountToStart(0);
    MyComboBoxEditor mcbe = new MyComboBoxEditor(this);
    mcbe.setClickCountToStart(0);
    defaultEditorsByColumnClass.clear();
    Hashtable cellEditors = new Hashtable();
    cellEditors.put(JButton.class, mbe);
    cellEditors.put(JComboBox.class, mcbe);
    cellEditors.put(Boolean.class, dce);
    this.defaultRenderersByColumnClass.put(JButton.class, new MyButtonRenderer());
    this.defaultRenderersByColumnClass.put(JComboBox.class, new MyComboBoxRenderer());
    defaultEditorsByColumnClass.put(Object.class, new MyCellEditorModel1(cellEditors));
    public TableCellEditor getCellEditor(int row, int col){
    if(myCellEditorModel!=null) return myCellEditorModel;
    return super.getCellEditor(row,col);
    public TableCellRenderer getCellRenderer(int row, int column) {
    Object value = getValueAt(row,column);
    if (value !=null) {
    return getDefaultRenderer(value.getClass());
    return super.getCellRenderer(row,column);
    public void setCellEditor(MyCellEditorModel anEditor) {
    myCellEditorModel = anEditor;
    }Hoping the code is enough to understand the problem, I thanks all for watching and reading the post and for the future answeres.
    Bye all.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    super.editorComponent=new JComboBox(elementi);You create a new combo box each call to getTableCellEditComponent() (overriding the one of the constructor), but you aren't adding a ItemListener to it.

  • Custom Sort via the XSL and custom template?

    I am trying to add a sort order to a CQWP. I would like a template style that does the sorting? I have to sort by a field called SortOrder, then I want it to be by file name - here is the code:
    I am thinking to do a foreach but not able to get it working? Is there another easier way?
    <!--Start Custom Policy Sort-->
        <xsl:template name="PolicySortedBullets" match="Row[@Style='PolicySortedBullets']" mode="itemstyle">
            <xsl:variable name="SafeLinkUrl">
                <xsl:call-template name="OuterTemplate.GetSafeLink">
                    <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <xsl:variable name="DisplayTitle">
                <xsl:call-template name="OuterTemplate.GetTitle">
                    <xsl:with-param name="Title" select="@Title"/>
                    <xsl:with-param name="UrlColumnName" select="'LinkUrl'"/>
                </xsl:call-template>
            </xsl:variable>
            <div class="item link-item bullet">
                <xsl:call-template name="OuterTemplate.CallPresenceStatusIconTemplate"/>
       <a href="{$SafeLinkUrl}" title="{@LinkToolTip}" target="_blank">
                  <xsl:if test="$ItemsHaveStreams = 'True'">
                    <xsl:attribute name="onclick">
                      <xsl:value-of select="@OnClickForWebRendering"/>
                    </xsl:attribute>
                  </xsl:if>
                  <xsl:if test="$ItemsHaveStreams != 'True' and @OpenInNewWindow = 'True'">
                    <xsl:attribute name="onclick">
                      <xsl:value-of disable-output-escaping="yes" select="$OnClickTargetAttribute"/>
                    </xsl:attribute>
                  </xsl:if>
                  <xsl:value-of select="$DisplayTitle"/>
                </a>
            </div>
        </xsl:template>
    <!--End Custom Policy Sort-->

    http://stackoverflow.com/questions/5415383/xslt-sortingboth-ascending-and-descending
    http://sharepoint.stackexchange.com/questions/81167/content-query-web-part-group-by-sort
    You can use the XSLT <xsl:sort> element to customize your sort order.
    https://sites.google.com/site/icsharepoint2010/xslt/sorting-in-xslt
    <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
    <xsl:output method="text"/>
    <xsl:template match="employees">
    <xsl:apply-templates>
    <xsl:sort select="salary"/>
    </xsl:apply-templates>
    </xsl:template>
    <xsl:template match="employee">
    Last: <xsl:apply-templates select="last"/>
    First: <xsl:apply-templates select="first"/>
    Salary: <xsl:apply-templates select="salary"/>
    Hire Date: <xsl:apply-templates select="@hireDate"/>
    <xsl:text>
    </xsl:text>
    </xsl:template>
    </xsl:stylesheet>

  • Sorting xml content based on decimal numbers

    hi,
    I would like to proceed a sorting an xml content. So, when the sorting elements are numbers, I must add the dt:dt="number" attribute in the concerned tag.
    But when this number are decimal numbers, it seems that the sorting occurs only when the decimal separator is the '.', but it does not work when the decimal separator is the ','.
    So is there a solution for sorting decimal numbr with the decimal separator ',' ?
    Thanks in advance
    Bye

    Typically the best way is if you know the name of the default table that contains your document. You do the update on the default table as follows
    update yourTable  t
         set object_value = updateXML(...)
    where ref(t) = (
                     select extractValue(res,'/Resource/XMLRef')
                       from resource_view
                      where equals_path(res,'/some/path/mydocument.xml') = 1
                          )

Maybe you are looking for

  • Vendor creation problem

    Hi, I am getting one Error Message, When I create a Vendor(90001) in Xk01. The Error Message is  .. Enter a Number Between A and ZZZZZ. but some other vendor has created with number(80001) only Please Revert Back. Thanks & Regards,   Dhanush.S.T

  • Write to measuremen​t file resets to 1904

    LV 2014 Windows 7 Professional 64 bit OS The first run of this vi creates an excel file that is time stamped correctly. The second and subsequent runs, the time stamp is reset to 1/1/1904 00:00:00.000. When I click the state 1 button, the USB DAQ's m

  • SE54 view column lables short

    Hello, When I create custom data elements and refer them into a custom table. After I create a se54 view for the table, the column heading are always short. I want them to be dynamic.i.e. if the user expands the column width, the lable should get cha

  • Material available date in cross-company business

    Hello guys,   I encountered a question in <b>cross-company business</b>. 1. create PO with ME21N; 2. create outbound delivery against PO with VL10B. I found material available date in outbound delivery is always the same as delivery date in PO. why?

  • JRE in Oracle 81701 - difficulties......

    When starting the Oracle Management Server for Oracle 8.1.7.0.1, sometimes the start command (oemctrl start oms) hangs and sometimes completes, but the OMS is nonresponsive. Also a large number of jre processes are started, mostly inactive. i.e. 66 j