How to make jcombobox display all by itlself?

Hello all -
Is there a way to make a jcombobox object display its column of items implicitly?
For example, suppose a program has a combobox filled up with names. And, suppose the first item says "toggle sort", which affects how the items are sorted in the combobox (eg, pressing it should cause the list to sort the displayed names based on first name, another press bases the sort on the last name...). The behavior I am aiming for is that when the user presses the "toggle sort" item, the combobox displays its items again awaiting further selection from the user (but not the first item). Know how to fire such an event?
private void namesComboBoxActionPerformed(ActionEvent evt) {
   int selected = namesComboBox.getSelectedIndex();
   if (selected == 0) {
      // some code should result in the namesComboBox displaying its items again. What is it please?
}

Here is a simple code, I don't know if its the correct way to do this sort of thing but it works:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.*;
* Sorting Combobox....
* @author talha
public class ComboSort extends JFrame{
    ArrayList<ComboData> data;
    JComboBox combo;
    public ComboSort() {
        super("Combo Sorting");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        populateData();
        Collections.sort(data);
        // I don't know how much of the combobox model should be overridden!
        combo=new JComboBox(new DefaultComboBoxModel() {
            @Override
            public Object getElementAt(int index) {
                return (index==0)?"Toggle Sort":data.get(index-1);
            @Override
            public int getSize() {
                return data.size()+1;
            @Override
            public int getIndexOf(Object anObject) {
                return (anObject instanceof String)?0:data.indexOf(anObject)+1;
        combo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if(combo.getSelectedIndex()==0){
                    ComboData.toggleSort();
                    Collections.sort(data);
                    //edited to make the pop up visible....
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            combo.setPopupVisible(true);
        combo.setRenderer(new DefaultListCellRenderer() {
            @Override
            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                Component renderer=super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if(value instanceof String){
                    renderer.setForeground(Color.BLUE);
                    renderer.setBackground(Color.YELLOW);
                return renderer;
        // you can remove following....
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                combo.setSelectedIndex(0);
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(new JLabel("Heads of State:"));
        getContentPane().add(combo);
        setSize(300, 300);
        setLocationRelativeTo(null);
    private void populateData() {
        data=new ArrayList<ComboData>();
        data.add(new ComboData("Barak", "Obama"));
        data.add(new ComboData("Gordon", "Brown"));
        data.add(new ComboData("Nicolas", "Sarkozy"));
        data.add(new ComboData("Angela", "Merkel"));
        data.add(new ComboData("Wen", "Jiabao"));
        data.add(new ComboData("Taro", "Aso"));
        data.add(new ComboData("Manmohan", "Singh"));
        data.add(new ComboData("Asif", "Zardari"));
        data.add(new ComboData("Mahmoud", "Ahmedinejad"));
        data.add(new ComboData("Hugo", "Chavez"));
        data.add(new ComboData("Raul", "Castro"));
    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ComboSort().setVisible(true);
class ComboData implements Comparable{
    String firstname;
    String lastname;
    static boolean sortFirstName;
    public ComboData(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    @Override
    public String toString() {
        return firstname+" "+lastname;
    public static void toggleSort(){
        sortFirstName=!sortFirstName;
    public int compareTo(Object o) {
        ComboData other=(ComboData)o;
        if(sortFirstName)return firstname.compareTo(other.firstname);
        else return lastname.compareTo(other.lastname);
}Thanks!
Edit: Reread your original post and made few editions... but I still don't think that this is what you need (but now its much better) :-)
Edited by: T.B.M on Apr 19, 2009 1:16 PM

Similar Messages

  • How can make JTextField display all ASCII character?

    I am writing a java app. There is a Jtextfield . I need display some special character in this jtextfield such as ASCII code is 135(&#135), 164(&#164), 167(&#167) and so on. Thees characters whose ASCII code is 164, 167 can correctly display in spite of you set any font to this jtextfield. But the character whose ASCII code is 135 can`t correctly display. It display as a [];. Who knows and has some ideas?
    Thx. Bob

    Thx any way.
    Now I found a another way to display the (char)135(display as "�").
    First, i defined a static attribute :
    public final static String ASCII_CODE_IS_135 = "�";
    Then, When I need display the char, I display the static attribute value. I found the textfield almost can display all special character by this way in spite of using what font.
    Thx again.

  • How to make JComboBox display an item not in list?

    hi,
    i'd like a gui component which is basically a jcombobox that presents a list A,B,C,D.
    The combobox is paired with another gui component which allows choosing sets of items. A etc.. represent preselected sets of items, so the user can click on A and a particular set would be selected.
    My problem is what to have the JComboBox do when the user selects a set of items that is not in the preselected defaults list. It would be nice to have the JComboBox just say "Other" at the top or something, but I can't figure out a way of doing this without putting the String "Other" in the list of items..
    does anyone have any idea of how to approach this? (I looked at making the JComboBox editable but this seems a little complicated?)
    thanks,
    asjf

    Your best option and cleanest design is to have a
    dummy data item in your list for "none of the above". thanks for the reply - this is what I'm doing at the moment. The problem is that I'm expecting testers to legitimately complain that selecting "None of the above" doesn't do anything, and doesn't really make sense ( it could make a random selection :o) )
    i think i agree that adding functionality to do this "properly" is likely to be more work/pain than its worth..
    Only an editable combobox can display something not in the list.this might help - if I could block mouse clicks to the editable area, and write to it programmatically but think this is probably quite difficult (?)
    asjf

  • How to make the display of custom column names in UWL(not bother abt values

    Hi all
    i want to make the display of custom column names in UWL ( for example GP)
    i dont want or not looking about values for those custom columns . i know that thru custom connector we can achieve to retrieve the values for those custom columns. but currently i am looking only just to display the custom column names( for example GP custom column names, just i want to display the name of the columns ) in UWL .
    Thanks
    Sunil

    Hello Prashant,
    You can add the control to your custom pagelayout, the following article has an example:
    http://spandps.com/2012/02/22/showing-the-audience-target-field-in-an-editmodepanel-sharepoint-sp2010-in-projectserver-ps2010/
    Btw, the SPFieldTargetToControl has a required property:
    http://msdn.microsoft.com/en-us/library/microsoft.office.server.webcontrols.fieldtypes.spfieldtargettocontrol.required(v=office.14).aspx
    - Dennis | Netherlands | Blog |
    Twitter

  • The window displaying bookmarks is too large (suddenly happened with the new version). I can't figure out how to make the display smaller. Zooming out does not work on the bookmark menu display.

    I have version 4, just downloaded, and a Mac w. OS 10.6. 7.
    The bookmarks display (when I pull down "bookmarks") is much too wide. I can't figure out how to reduce the display size. The window is not persistent so I can't even get you a screen shot.
    Thanks, Sara

    It seems there was a change in Firefox 4 where the width of the drop-down is now determined by the length the longest bookmark name in the folder being displayed. Previous versions of Firefox would shorten a long name like that and add an ellipsis to signify the name was truncated.
    Sorry, I don't know how to change that other than to advise you to edit the name of that long bookmark name and make it less verbose. Just scroll down the list of bookmarks in that wide folder until you see the culprit, then right-click that bookmark and open Properties & edit the Name line at the top of that dialog.

  • How to make my display be the main view with my mac Book Pro

    How to set up my external display automatically work as the main display when plugged into my MacBook Pro. I had it set up to work this way on my old MBP but I got a new MBP with Mountian Lion and the Display set up seen different and I can figure out how to make my Apple HD display (about 3 years old) be the main display when I turn on my MBP. Mirror is off when I look at
    System pref’s – Display – Arrangement I just get to pick which display is left and right. I cant remember how it was set up on my old MBP. Mirroring does me no good. Any help will do!!!
    Thanks Brad

    Drag the menu bar in the picture to the picture of the other display.

  • My podcast is only displaying 25 episodes. How do I make it display all of them?

    You can see here:
    http://itunes.apple.com/us/podcast/let-me-ascertain-you-the-civilians/id47797169 0
    But we have about eight more episodes that aren't getting displayed. I see other podcasts that seem to be able to display more of them. What can I do?
    Thanks!

    I'm afraid there's no easy answer to this. The feed, which appears to be OK with only minor errors, has over 30 episodes going back to 20 November; the Store is showing only the last 25. So this isn't a question of the Store failing to update, since it's showing the most recent episode, or the feed being limited, because all the episodes appear when subscribing. In the past the Store hasn't limited the number of episodes as far as I'm aware, but possibly Apple have started doing this.
    In any event, I'm afraid there is nothing you can do about it: your feed is OK and all the episodes appear whe subscribing.

  • How to set up displaying all jsp-errors in the problems-list?

    how can i set up that all jsp-problems and warnings like "some tag does not have an end tag..." are displayed in the problem list?
    when i open up a jsp-page in the editor, the warnings are displayed i can´t see them in the problem list. in the older version (m7) these warnings have been displayed by default and i can not find any setting to display this.
    any idea?
    tnx
    Rel

    When exactly it stopped displaying in Problems View? Have you installed any other plug-ins to Eclipse?
    Try the following steps:
    - Quit & relaunch Workshop
    - In Problems View, Launch Filters... window
    - Click "Restore Defaults" button (make sure JSP problem is checked)
    - Click OK
    - Does the warnings displayed in Workshop JSP/XML Editor appear in the Problems View?
    In case you still face the same problem, please send the following information to [email protected]
    * Help > About Workshop > Click on Eclipse icon - Version & build id
    * Help > About Workshop > Click on Workshop icon - Version & build id
    * Window > Preferences > Java > Installed JREs - the JRE/JDK version
    * .log file from <Eclipse Workspsace>.metadata directory
    * m7.log.0 from <Workshop_Home_Dir>Workshop\eclipse\plugins\com.m7.nitrox_3.0.0 directory
    * <Workshop_Home_Dir>Workshop_InstallLog.log
    * If you can remember, the steps exercised (or plug-ins installed) before encountering this behavior

  • How to make JComboBoxes transparent

    For some reason "setOpaque(false)" doesn't seem to work for JComboBoxes. I'm using java 1.4
    Below is some code. If you compile and run it you should get a window with a button and a combo box, the button is transparent, the combo box is not.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.geom.Area;
    * test transparent swing components
    class TransTest
    public static void main(String args[])
         JFrame theFrame = new JFrame("transparency test");
         JComponent contentPane = new JComponent()
              public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              Area s = new Area((Shape)new Rectangle(0, 0, getWidth(), getHeight()));
              g2.setPaint(new GradientPaint(0f, 0f, Color.GRAY, 150f, 100f, Color.WHITE, true));
              g2.fill(s);
              super.paintChildren(g);
         theFrame.setContentPane(contentPane);
         theFrame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
         JButton button = new JButton("button");
         button.setOpaque(false);          // this works
         JComboBox combo = new JComboBox();
         combo.addItem("combo");
         combo.setOpaque(false);               // this doesn't seem to work
         JPanel pnl = new JPanel();
         pnl.setOpaque(false);
         pnl.add(button);
         pnl.add(combo);
         contentPane.setLayout(new BorderLayout());
         contentPane.add(pnl, BorderLayout.CENTER);
         theFrame.pack();
         theFrame.setVisible(true);

    Try setOpaque(true) and setBackground(new Color(r,g,b,a)) where r, g and b are respectively the values of red, green and blue and a the alpha value (0 means totaly transparent, 255 totaly opaque). Sometimes a component should be opaque with a transparent background to make the transcparency works.
    But I have to ask you a question : have you bugs with the display ? Indeed, I made an app that doesn't use a gradient paint like you, but the JFrame have a ContentPane that display a picture. I made every JComponent transparent in order to see the background picture. The display is very dirty with JButton, JTextArea, JTextField and JList. Indeed, when moving cursor over JButton, the JButton displays the top lecft corner of the JFrame instead of the underlaying part of the picture as expected with transparency. With JTextField and JTextArea, when typing text the same problem occured. With JList, the problem appear when scrolling. only a full update(Graphics g) can clean the display, that is I must call it with every mouseMoved, mouseClicked, etc. events. The problem appears only with JDK > 1.2.2 (JDK1.3 and later)

  • How to make a play all menu and a play single movies menu

    Hi, I'm a noob with Encore and trying to make a dvd menu, but can't seem to get it right.
    I have in total 6 movieclips which I would like to make en menu for. I have made a menu, where there are a play all button and a kind of chapter button.
    I have linked alle movies as end action to each other, expect the last of cause - paly all menu done - check
    Then in the "chaptersmenu" I took the first clip and changed the override setting to the "chaptersmenu", but when I do that the link between clip 2 and 3 becomes dashed instead of solid, and when I preview it stops after the second clip on play all.
    What am I doing wrong and how should I do it, to accomplis what I like?

    Just to recap, so I understand it correct.
    I link each movie specific button to the specific movie, with action of "last menu" and no override. Then for the play all, I create en playlist containing all movies, and the play all button is then linked to that playlist.
    I'll try that when I get home. After I made the question yesterday, I came to think, if I could use Premiere to help me out. So I made a sequence, with all movies in, and created some chapter marks, and that I could get to Work in Encore. So now the computer is just sweating to create the dvd structure, so I can test it.
    I don't know which is the correct way to do it, or if it just a matter of taste, but it seems that Premiere sequence requires a lot more space on the disk then with separate movies. But I have dual layer disks, so guess that doesn't make any difference.

  • How to make jump menus all the same length?

    I have a series of jump menus. Some listings in the jump menu
    are longer than others but I would like the pull down boxes for all
    the jump menus to be the same length. How can I do this?

    By length, do you mean width?
    <select style="width:300px;"></select>
    --Nancy O.
    Alt-Web Design & Publishing
    www.alt-web.com
    "Johnny the boy" <[email protected]> wrote
    in message
    news:fulkis$bdj$[email protected]..
    > I have a series of jump menus. Some listings in the jump
    menu are longer
    than others but I would like the pull down boxes for all the
    jump menus to
    be the same length. How can I do this?

  • How to make modifications in all clients

    Hi All,
    I modified Bill to address in script form in 200 client.
    So those changes are not reflecting in other clients because forms are client dependent.
    Now i want to those modifications in all other clients. How to do that.
    Thanks,
    Subbu.

    If you want to reflet the changes in all development clients, RUN  program RSTXR3TR, in SE38
    1)Transport request : TP #
    2) MODE : <b>EXPORT</b>
    Execute
    Login to the desired client
    RUN  program RSTXR3TR, in SE38
    1)Transport request : TP #
    2) MODE : <b>IMPORT</b>
    Execute
    Now all your changes will be reflected in other clients.
    Reward points to all useful answers.
    Regards,
    Sairam

  • How to Make TLN display Vertically

    Dear All,
    I have a requirement for displaying the TLN vertically instead of Horizontal display can any one help me on the same.
    Thanks

    Hi,
    I have createded a custom TLN and that will also solve your problem.
    I have doucmented in the below link Development of Custom Top Level Navigation -- Horizontal Drop-Down Menu  (http://scn.sap.com/docs/DOC-56038)  .
    Regards,
    Srinivas

  • How to make accounts display only via authorizations?

    Has anyone setup CRM 2007 to get the account page to be display only? We don't want to allow certain users to manage accounts directly in CRM and would like to lock this down via authorization objects. We can't seem to figure out what authorization objects are needed to lock it down appropriately. Thanks in advance.

    Hi James,
    We've had a similar requirement. We used sap note 1260695.
    Using this BAdI you can customize that depending on the BP role, some areas (e.g. marketing attributes) are
    editable, and others (e.g. address data) are only displayed.
    As an alternative, you can use note:
    Note 1259940 - Authority check for accounts depending on roles
    Hope this helps.
    Regards,
    Wim Olieman

  • How to make buttons display in correct location

    Hi, I am trying to adapt a dreamweaver template. I have to
    place a set of buttons to the left of the design. If I place my
    buttons in a new layer over an existing cell, I can get it all to
    look fine in the WYSIWYG editor, but on f12 preview in browser the
    buttons are completely in the wrong place. Would really welcome any
    pointers to solving this ... Thank you. As you have probably
    guessed I am new to dreamweaver...

    > As you have probably
    > guessed I am new to dreamweaver...
    Being new to Dreamweaver is of no consequence, but being new
    to HTML and CSS
    is critical. DW will punish you badly if you have no
    familiarity with HTML
    and CSS. Please take the time to study these techniques
    before getting
    yourself too frustrated.
    We cannot answer any layout question without seeing your
    code, really. But
    from this -
    > If I place my buttons in a new layer
    we can deduce that you are using absolute positioning to try
    to align your
    buttons. The thing about absolute positioning is that it
    places the
    elements ABSOLUTELY on the screen - they stay in exactly that
    location no
    matter what else happens on the page. It sounds like you have
    some other
    centering elements on the page that are moving away from the
    placement of
    the buttons when you actually render the page in the browser.
    It's
    situations like this that cause us to try to tell people that
    a) there is no
    such thing as WYSIWYG, and b) using DW without understanding
    the underlying
    code will likely be a failure.
    The solution to your problem will be one of the following -
    a) don't use absolutely positioned elements to hold your
    buttons - place
    them in a container that follows the normal flow of the page
    instead
    b) wrap the page in a relatively positioned, centering
    container so that
    when the container centers, it carries the absolutely
    positioned elements
    along with it
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "c_a_n_v_a_s" <[email protected]> wrote in
    message
    news:[email protected]...
    > Hi, I am trying to adapt a dreamweaver template. I have
    to place a set of
    > buttons to the left of the design. If I place my buttons
    in a new layer
    > over an
    > existing cell, I can get it all to look fine in the
    WYSIWYG editor, but on
    > f12
    > preview in browser the buttons are completely in the
    wrong place. Would
    > really
    > welcome any pointers to solving this ... Thank you. As
    you have probably
    > guessed I am new to dreamweaver...
    >

Maybe you are looking for

  • HT4191 upgraded to new itunes and no longer able to sync my notes in outlook with my iphone 4s

    I use outlook notes and in itunes 10 you could sync notes when you plugged in your iphone and opened itunes. after itunes 11, you cannot sync notes via usb so how can i sync notes from my desk top to iphone and vis versa? The only thing i have not tr

  • Back ground Jobs report

    HI I am running Process chain as a Back ground job in my user name, now i have a requirement that we need to extract a report out of my system which contains data about " At what time my process chains are running and how many data are loaded" Is tha

  • EMac Display issue

    This is a brand new eMac that has been working for 1 week, now the screen shakes and then goes back to normal, it is not one of the models in the eMac extended coverage program or what ever the name is I have already checked this. I am just wondering

  • Inserting clip into sequence: aspect ratio adjustments

    I just made this page Aspect Ratio Adjustments available to whoever is curious to know what is the rational behind the values of +Aspect Ratio+ and Scale evaluated by FCE whenever it inserts a clip into a sequence. This was inspired by Michael in his

  • IPhoto Gallery user friendliness!

    I wish the iPhoto Gallery had the page numbers at the top and bottom of the gallery. After flipping through all the photos people get to the end and think there are no more photos!!!! I have to add a comment on all my emails to say that they have to