JComboBox Length question!

When i use JComboBox,it's length is fixed.Perhaps some items is too long to display,so user can't understand it clearly.So i want find JComboBox that can expand automaticly,if item is long,it will be expanded.I tried several function JComboBox provided,but it's remain as usral.I don't know if some master-hand meets same question! Thanks a lot!

If you want the List wider, look [url http://www2.gol.com/users/tame/swing/examples/SwingExamples.html]here
If you want the whole combo wider, use
myCombo.setMinimumSize(new Dimension(200,20));
It's also possible to calculate the width of string in a certain font (to plug in above), but you can search for that.

Similar Messages

  • JComboBox simple question

    I think is a very simple question, I ve got a JComBox with an array of Strings. Something like this:
    JPanel myPanel;
    JComBox box;
    String levels[]={"Level 1","Level 2","Level 3","Level 4","Level 5"};
    box = new JComboBox (levels);
    myPanel.add(box);
    Ok. My question is: How can I let just the level 1 enable at first, or how can I enable or disable just one level of the JCombox, like level 1 and 2 enable but level 3, 4 and 5 disable.
    Thanks a lot!! Hope someone helps me!!

    I don't think this is possible with a JComboBox. I believe it is with a JMenu and JMenuItems.
    You could only display valid options by adding/deleting them. Or you could handle it in the listener code. ie if they select an invalid option do nothing. This would require you keeping track of which options are valid elsewhere in the code.

  • Retrieving values from a JComboBox - Design question.

    I would like some design guidance on a problem that I am hoping has been solved before. Here is my situation:
    I have a JComboBox that I populate with String values from a database table. The exact set of values to be loaded into the JComboBox varies according values specified elsewhere on the GUI.
    When I select an item from the JComboBox, I need to read the database to retrieve more information. The text is not sufficient for me to identify the data I need, so I need to get the table key from somewhere.
    Is there anyway I can associate my table key with the text value inside the JComboBox and retrieve it when the user selects a drop down value from the JComboBox?
    Many thanks in advance.

    when you load the data from the db, try to get ALL the information needed: item label+item value+description. put this data into a map (a hashmap) for example using a unique identifier. For example, use a numeric index. In this case, the item value should be the index that uniquely identifies your items.
    create a simple bean that encapsulates the item contents: index+value+label, description.
    Doing this will avoid the huge db access occurences.
    hth

  • JCombobox Renderer Question

    I am trying to use a custom renderer for a jcombobox in order to show combobox items in different font color. I get a DefaultListCellRenderer and update it according to my needs (setting font color). When I run the application, the combobox is populated properly. When I select one of the items (say "Red") from the combobox, the item gets selected, but the after the selection the font color of the item that is selected defaults to black (instead of red here). What should I do so that after selecting the item, the selected item is shown in the appropriated font color as indicated by custom renderer.
    Here is the code for the custom renderer.
        private class ColorCmbRenderer implements ListCellRenderer {
            protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
            private final Dimension preferredSize = new Dimension(50, 23);
            public Component getListCellRendererComponent(JList list, Object value,
                                                        int index, boolean isSelected,
                                                        boolean cellHasFocus) {
            JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
                                                        isSelected, cellHasFocus);
                switch (index) {
                    case 0: renderer.setText("Black");
                            renderer.setForeground(Color.BLACK);
                            break;
                    case 1: renderer.setText("Red");
                            renderer.setForeground(Color.RED);
                            break;
                    case 2: renderer.setText("Blue");
                            renderer.setForeground(Color.BLUE);
                            break;
                    case 3: renderer.setText("Green");
                            renderer.setForeground(Color.GREEN);
                            break;
                    default: break;
                renderer.setPreferredSize(preferredSize);
                return renderer;
        }Another thing that I wanted to know is whether each of the items in the jcombobox can be associated with individual Action objects by using something like setAction(new HTMLEditorKit.BoldAction()).
    regards,
    Nirvan.

    There are 3 foregrounds to be set.import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.*;
    import javax.swing.plaf.basic.BasicComboBoxRenderer;
    public class ComboColors {
       JComboBox comboBox;
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new ComboColors().makeUI();
       public void makeUI() {
          comboBox = new JComboBox(
                new Object[]{"BLACK", "RED", "BLUE", "GREEN"});
          comboBox.setRenderer(new BasicComboBoxRenderer() {
             private final Color[] colors = {
                Color.BLACK, Color.RED, Color.BLUE, Color.GREEN
             @Override
             public Component getListCellRendererComponent(JList list, Object value,
                   int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value,
                      index, isSelected, cellHasFocus);
                if (index == -1) {
                   index = comboBox.getSelectedIndex();
                setForeground(colors[index]);
                list.setSelectionForeground(colors[index]);
                comboBox.setForeground(colors[index]);
                return this;
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.add(comboBox);
          frame.add(new JButton("Dummy"), BorderLayout.SOUTH);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
    }db

  • File length question...

    I'm a java student, and I'm having problems. I have to take the information from a Vector, and write it to a disk file on the A drive. Then I have to be able to read the file back into the Vector for processing. I can't find any info on how to do that. I've seen 347 different ways to CREATE a file that isn't already there... but how do I set the length to be written, and then how do I read and transfer the data back into the Vector? Any help would be greatly appreciated!! I'm so frustrated that my wife is worried I'm going to break my hand from punching the monitor so hard...

    I will continue my search for information, and maybe I'll find it. Maybe it
    has something to do with using a Vector instead of an ArrayList or
    something...Nope, a Vector will do just as fine as an ArrayList. You shouldn't be
    afraid to write some toy code and play with it. Here's a bit I type in on
    the fly:public abstract class Person implements Serializable {
       public abstract void speak();
    public class Fred extends Person {
       public void speak() { System.out.println("Wilmaaaa!!!!");
    public class Barny extends Person {
       public void speak() { System.out.println("Jeez Fred ...");
    public class Dino extends Person {
       public void speak() { System.out.println("Arf! Arf! Arfarfarf!");
    }The following class attempts to create a List (or Vector if you want),
    sticks three persons in it and tries to write the entire thing to a file:public class Test {
       static public void main(String[] args) {
          ObjectOutputStream oos= null;
          List<Person> list= new ArrayList<Person();
          list.add(new Fred());
          list.add(new Barney());
          list.add(new Dino());
          try {
             FileOutputStream fos= new FileOutputStream("test.data");
             oos= new ObjectOutputStream(fos);
             oos.writeObject(list);
          catch (Exception e) { e.printStackTrace(); }
          finally {
             try { oos.close(); } catch (Exception e) { /* muffle */ }
          ObjectInputStream ois= null;
          try {
             FileInputStream fis= new FileInputStream("test,data")l
             ois= new ObjectInputStream(fis);
             list= (List<Person>)ois.readObject();
             for (Person p : list)
                p.speak();
          catch (Exception e) { e.printStackTrace(); }
          finally {
             try { ois.close(); } catch (Exception e) { /* muffle */ }
    }This was all from the top of my head, so no warranty etc. ;-)
    You should get this up and running in no time; then play with it for a
    while and see if you can understand what's happening.
    kind regards,
    Jos

  • JComboBox listener question

    Hi,
    I was wondering what kind of listener I would use to detect enter being pressed in a JComboBox.
    I tried an actionListener but this sends actionEvents at far too many times, I want to limit what I'm doing to only when the user presses enter in the JComboBox.
    It seems rather odd that a keyListener can't be used with a JComboBox, or at least according to the API specifications...
    All help is very appreciated!!

    The JComboBox itself just has the text field and then the down arrow, correct? Like if I am writing in that text field I am writing in the JComboBox? Basically all i need is a way to do something when the user presses 'enter', but not when all the other various things that trigger ordinary action events are fired. Using a keyListener to find out whether the key pressed was 'enter' seemed like the best way to do this, but if key events aren't even getting sent when the focus is in the text portion of the JComboBox that may not be the case. If there's anyway i can explain the problem better I'd be happy to do so.
    Thanks

  • JComboBox newbie question

    I cant seem to find out how to add items to my jcombobox using Forte.
    I have this :
    String[] dbId = { "579", "459", "789", "098", "297" };
    jComboBox1.addItem(dbId);
    Where do I put this code to fill the combo box with the String array?
    Steve

    Depends on what application you are building.
    If you are building a standalone application, put those codes in the constructor of your application class.
    If you are building an applet, put those codes in the init() method of your applet.

  • JComboBox Usage Question

    Hi guys,
    I have a JClient form which have two JComboBox (State and City). When the State combo box changes it's value, the City combo box's allowable values would change. Both combo boxes are based on database tables. How can I synchronize these two comboboxes, so when the first box changes its' value then the second box will requery the database and display a different set of allowable values?
    Regards
    Tony

    Shailesh,
    These are my code. With the LOV binding, the combox are binded to table but the city combo will not refresh it's lists after state combo change the value.
    stateCombo.setModel(JUComboBoxBinding.createLovBinding(
    panelBinding, stateCombo, "CustomerView", null,
    "CustomerViewIter", new String[] {"StateId"}, "StateLookupView",
    new String[] {"StateId"}, new String[] {"StateName"}, null, null));
    cityCombo.setModel(JUComboBoxBinding.createLovBinding(
    panelBinding, cityCombo, "CustomerView", null,
    "CustomerViewIter", new String[] {"CityId"}, "CityLookupView",
    new String[] {"CityId"}, new String[] {"CityName"}, null, null));
    stateCombo.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    cityCombo.repaint();
    }); From the datamodel you posted at the beginning, the lovVOname for the second combo should have been CityView1, or in other words you should pick the viewobject that is viewlinked to the master StateVO.
    Here's how it works.
    Once you select a state in the states vo, the viewlinked collection on the detail changes to reflect all cities for that state. The Lov combo should then 'redraw' it's list as a reaction to the rangeRefreshed event from BC4J for the detail VO.

  • JComboBox checkmark question

    When using a JComboBox the selected item is indicated in the dropdown list with a checkmark. I created a really simple renderer that changes the color of the text based on an attribute of the Object:
    public class SupportedObjectComboBoxRenderer extends JLabel implements ListCellRenderer {
      public SupportedObjectComboBoxRenderer() {
      public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        SupportedObject so = (SupportedObject)value;
        this.setForeground(so.isActive() ? Color.BLACK : Color.GRAY);
        this.setText(so.getName());
        return this;
    }The checkmark is no longer displayed. I believe I need to render that myself (in the JLabel). Is that default checkmark icon accessible so that I can load it as a resource? Or is there something else I should be doing to show it?

    Is there a way you can change the text color of a JComboBox item without
    otherwise disrupting the look and feel?don't know if this will work for you, but worth a try
    import java.awt.*;
    import javax.swing.*;
    class Testing extends JFrame
      JComboBox cbo = new JComboBox(new String[]{"London","Madrid","New York","Rome","Sydney","Washington"});
      public Testing()
        setSize(150,75);
        setLocation(400,300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        cbo.setRenderer(new MyRenderer());
        JPanel jp = new JPanel();
        jp.add(cbo);
        getContentPane().add(jp);
      public static void main(String args[]){new Testing().setVisible(true);}
    class MyRenderer extends DefaultListCellRenderer
      public Component getListCellRendererComponent(JList list,Object value,
                          int index,boolean isSelected,boolean cellHasFocus)
        JLabel lbl = (JLabel)super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
        lbl.setForeground(index%2==0? Color.RED:Color.BLUE);
        return lbl;
    }

  • Array.length Question

    Hello,
    I am trying to find out what class array's length attribute comes from and how array is able to use it.
    I have been studying the API but cannot find it or work it out.
    Thanks,
    Harold Clements

    Arrays are considered part of the language and are not listed in the API.
    But length appears to behave like a public field, mostly.
    Have you checked the language spec? It's available free online.

  • JComboBox - 2 questions

    First, does implementing ListCellRenderer in a combo govern what is displayed when the combo popup is displayed or when it's not? If it isn't the popup, how do you take control of what is displayed when the combo's button is clicked and the popup displays? I'd like to display a two-column table in the popup area and I'm not quite where to start.
    Second, anyone have any idea how to stop the default drop down popup from displaying when a combo is clicked? Basically, in another case I'd like to install my own listener and display something unique when the combo is clicked and not have the drop down displayed.
    Any thoughts and help would be appreciated.

    ListCellRenderer only presents a user friendly view of what the value is usually is. For example if you add a JLabel to a combo box, the user sees something like this...
    javax.swing.JLabel[preferredwidth=preferredheight=text="Java Website"font=java.awt.Font[...
    ... which is the result of toString(). But if you use a renderer, you present the user with a label so the user only sees:
    Java Website
    Second point: you can do this roughly by rendering your cell as a JPanel with the layout as a GridLayout(2, 1). I haven't done this before but I think it might work. If it doesn't, you'll have to write a custom combobox. Which you will have to do for your third question.
    Stephen                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Cable length question

    My office building has two floors...the bottom floor is where my boss' office is, as well as a meeting table with a 42" TV mounted on the wall. This is where my boss looks over my videos and dailies (sp?). My desk is upstairs. Instead of wasting time compressing video and building Audio/Video TS folders and burning DVDs every time he wants to make a change, I want to just do external video out of FCP and into the TV downstairs. Make sense?
    My question is, I'm going to need about 75-100 feet of cable (component, I think, cuz I'm going through my DSR-11) to connect to that TV. Is there an easier way? I know it's not going to look pretty because it's component video, but do they have S-VHS cables that long? I don't have anything better as an out on the DSR-11.
    Thanks in advance,
    Jonathan

    Thanks everyone for the ideas...
    I guess I'm trying to by-pass the whole "export it to xxx media and bring it somewhere." As I'm sure many of you have experienced in your own jobs, I have a boss with little to no patience. He watches something and says, "Let me see the raw interview" or "What happens when we switch these clips around." He got this big TV in the meeting room and wants to watch everything from there (he's a bit too lazy to walk up the friggin stairs to my computer). So instead of wasting 20 minutes exporting a 55 minute interview through compressor, building the DVD in DVDSP, then burning it onto disc, I'm thinking it would be easier to play it in FCP (since it's already captured) and using the TV downstairs as the external monitor. And the yelling up from another floor isn't a concern...he can just talk on our intercom system through the phones if there's a problem.
    As for putting it out to tape, we only have one DSR-11...and not much of a budget to get another...again, I'm trying to (hopefully) bypass any exporting/putting out to tape of any kind and save some time. I'm sure I'm not the first to try this and fail (I mean, exporting just comes with the job, right?), but a guy can hope...
    Jonathan
    Jonathan

  • Quick array length question...

    for this part of my code i'm trying to determine the components needed to find the average of my array. I can't seem to find a way to determine the length of my array (how many components it consists of). Every time I keep getting the dereferencing error....I know it's something simple but I just can't seem to get it right. Please help!
    int total = 0, mean = 0, length = 0;
    for(int j=0; j<i; j++)
    total = total + array[j];
    System.out.print(array[j]+" ");
    System.out.print(total);

    Hi Cher,
    This length attribute if any array object will give you the number of components I mean number of elements in that array.
    array.length; rather than array.length();
    This may be helpfull.
    int total = 0, mean = 0, length = 0;
    for(int j=0; j<array.length; j++)
    total = total + array[j];
    System.out.print(array[j]+" ");
    System.out.print(total);>
    Aski

  • USB Cable Length Question

    I would like to use a USB cable to connect my computer to my wife's laser printer that is 16 feet away. The USB cable will be connected to a powered hub. Will a USB cable work at this distance? I have not seen one this long in stores but will search for one on the internet if 4 members think it will work. I would be using USB 1.1.

    Sorry for making this more complicated, but I just took out my tape measure to measure the actual distance of usb cable I'll need.
    Just to get to the switchbox I'll need an almost 13 foot usb cable (really like 12 and 1/2 feet). So I'm assuming I'll need a 15 foot usb cable to get to the switchbox. At that point, any short cable attached from the switchbox to the printer will still exceed the 15 foot limit since I'm assuming one must add the length of the longer cable [15 ft] and smaller cable from switchbox [say 2 or 3 ft].
    The solution I'm thinking of that might work is to get a powered switchbox. Wouldn't a powered switchbox then revitalize the usb signal and even allow another cable [up to 15 feet] to be attached even though I'll only need a much shorter cable to get from the switchbox to the printer. I don't think the switchbox you linked me to is powered. If you, or others, think a powered switchbox would then allow more cable then please say so and if you can link me to a powered switchbox.
    In my thinking, a powered switchbox is much like adding a powered usb hub to the end of a 15 foot cable and then would allow one to go another 15 feet. Theoretically thinking, with many powered hubs or powered switchboxes one could really take the cable out an extremely long distance (if not infinity) - ?

  • Editable JComboBox typeahead question

    I have a editable JComboBox which also does the type ahead....So lets
    say I have 4 elements in combo box INDIA , JAPAN, MOROCCO , USA.
    When the user types M then MOROCCO which is 3rd elements gets highlighted and when user tabs out MOROCCO gets selected. But my requirement is when user types in M then MOROCCO should be highlighted ( which is happening ) but also it should be the first element in the list closest to the combobox rather than being the 3rd element in the drop down.
    Please help ..Thanks

    Well since you want the selected element always be the first element, you can simply use setSelectedIndex(0). But before you setSelectedIndex, you have to getSelectedIndex(). In your example the selected index = 2, so you can get the String Object "Morcco". Then you can rearrange the Object[] within the JComboBox by calling removeAllItems or removeItem and addItem. Oh, also you might want to set up an ItemListener and do the rearranging inside the method
    itemStateChanged(ItemEvent e)
    Hope this Helps :}
    Kenny

Maybe you are looking for

  • Creation of Partner profile

    Hi to all, I am new to SAP, that too in payroll, currently iam working in outsourcing payroll for US project, where we have to create interface between SAP to ADP (third party) where they will process the gross payroll to net payroll, I don’t have id

  • Is there a way to check what songs were played on iPod touch on a certain date?

    I want to see what songs (and order they were played in if possible) on a certain date and to see what time they were played. I don't know if there is memory of plays beyond merely last time a song was played.

  • Help required in finding out the tables for FS-Claims Management module

    Hi All, In FS - claims Management module, i need to find out from which tables we can fetch the following fields, INSURED             : insured person DESCINSURED     : Description of insured person CLAIMANT     : person eligible for benefits DESCCLA

  • Question regarding the powershell creation of service applications in SharePoint 2010/2013

    Hi I create all my service applications in SharePoint 2010/2013 using Powershell. Is there a "best practice" when to start the service Instance for a service application? Is it better to start the service instance prior to creating a service applicat

  • How to save selection screen in LISTCUBE?

    I execute LISTCUBE, enter my CUBE name, get message "The Infoprovider contains too many characteristics. Make a preselection.".  I choose 20 characteristics to display then the data target browser selection screen display.  Is there a way to save thi