JSF selectOneChoice  VS.  Swing JComboBox

I have been so impressed with how clean it is using a JSF selectOneChoice with a selectItem and selectItems.
Using selectItem.itemValue and selectItem.itemLabel is intuitive, and fills a very common need.
I'm wondering if there is a similar type of component I can use with a JComboBox. It seems that a LOV binding needs a target data collection (and iterator); but I simply want a JComboBox to display labels and manage values, independent from an iterator.
Any suggestions are very much appreciated!!!
Jeffrey

Well I would just like to update this thread as more than a year has passed since I began working on ADF BC & Faces. Coming from a SWING background, I've learned quite a lot about web development. For starters, it’s not as easy as "Drag and Drop" and RAD like some demo videos or evangelical pitches makes it out to be. There is a steep learning curve (about half year with daily interaction with JDeveloper) to get comfortable with this technology. Personally speaking, a firm understanding of page definition bindings was the hardest to grasp, but then again maybe I’m just a bit slow. Compared to SWING or desktop UI development, the richness of ADF Faces UI is limited to boundaries of the web browser.
<br>
However, within the last month, our team has made great strides in taking the first step in launching a ported module our internal system (legacy Oracle Forms used by hundreds of hospital employees). Our Dynamic JDBC authentication piece was the keystone for our first module (a modified version from Steve’s infamous “not yet documented samples”). Trying to take full advantage of this technology, we also have created reusable pages and BC components for CRUD operations.
<br>
There is still plenty of work to be done as we are now struggling with team development (difficult due to multiple file modifications within JDev’s). We are also eagerly awaiting several rich UI in the next release of ADF Faces. Overall, the light at the end of the tunnel is starting to appear and I hope the Oracle ADF team and everyone on this forum continues to actively contribute to the growth of this community.
<br>
Here are a couple of screen shots of our app if you are interested.
http://i108.photobucket.com/albums/n23/zeoneozero/login.jpg
http://i108.photobucket.com/albums/n23/zeoneozero/menu.jpg
http://i108.photobucket.com/albums/n23/zeoneozero/spcreg.jpg
Cheers,
-Z

Similar Messages

  • Swing JComboBox causes scrolling problems in applet

    I have an applet with a JPanel that contains a JComboBox that lists font selections for a JTextPane in a JPanel below it. It contains about 12 items, of which only five are visible at a time. If I choose any of the first five and scroll the page on which the applet is running, there are no issues. However, if I scroll the page after scrolling down the list to the sixth item, regardless of whether or not I actually select it, it causes the graphics in the applet to corrupt. The JComboBox code is:
    private JComboBox getFontFaceCB() {
                   String[] fontNames = new String[fontlist.length];
                   for (int i = 0; i < fontlist.length; i++){
                        fontNames[i] = fontlist.getFamily();
                   if (fontFaceCB == null) {
                        fontFaceCB = new JComboBox(fontNames);
                        fontFaceCB.setBackground(Color.white);
                        fontFaceCB.setPreferredSize(new Dimension(150, 30));
                        fontFaceCB.setMaximumRowCount(5);
                        fontFaceCB.setSelectedIndex(0);
                        fontFaceCB.addItemListener(new java.awt.event.ItemListener() {
                             public void itemStateChanged(java.awt.event.ItemEvent e) {
                                            currentFont = fontlist[fontFaceCB.getSelectedIndex()];
                                            StyleConstants.setFontFamily(textStyles, currentFont.getFamily());
                                            jTextPane.setCharacterAttributes(textStyles, true);
                                            viewWidget.repaint();
                   return fontFaceCB;
              }This also happens if I set the default index to something that one must scroll down to reach (e.g. the sixth index) I was wondering if anyone else has come across this issue and has any idea as to how this may be resolved.
    Also, if the window is minimized, resized, etc. the graphics also corrupt, but only after the aforementioned condition.
    Edited by: BANZ111 on Dec 12, 2007 3:59 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I have found the solution:
    I had lightweight components intertwined with heavyweight ones, which, until now, I never regarded as being a possible source of problems. Apparently, when you scroll down a JComboBox, it changes from light to heavy weight? At any rate, I found this with a lot of other useful tips here:
    http://72.5.124.55/javase/6/webnotes/trouble/TSG-Desktop/html/gchzf.html#gdldq
    Perhaps this can be of use to anyone else who gets a similar problem.

  • JSF - selectOneChoice page variable problem

    Hi,
    I have bound my selectOneChoice component to my data control (view object), the "base data source" in the binding is a variable on the page definition (as described in the adf developers guide).
    Everything works fine until I navigate away from and then back to this page, the variable value is lost and therefore so is my original selection in the selectOneChoice.
    Is there a way to either persist the variable value or choose a "base data source" that has session scope? I don't want to choose a table as a base data source as the list is only for searching, not updating anything.
    Thanks
    Mark

    Hi,
    Your navigation cases are defined in adfc-config.xml (or any other task flow definition) as
        <control-flow-rule>
          <from-activity-id>main</from-activity-id>
          <control-flow-case>
            <from-outcome>login</from-outcome>
            <to-activity-id>searchPage</to-activity-id>
          </control-flow-case>
        </control-flow-rule>while "main" is not the name of the page, but view id, it is also defined in adfc-config.xml
        <view id="main">
          <page>main.jspx</page>
        </view>So, when you redirect to main.jspx your navigation just doesn't work because your navigation case is defined for "main", but authentication works (which you can test by typing some secured url directly in the browser).
    Pedja

  • JDev 11gTP4: ADF BC LOVs - JSF selectOneChoice sometimes empty

    Hi JDev team
    With apologies the following is a bit of a ramble rather than a good description of what the problem is within JDev 11gTP4. I'm a bit lost to know what the problem is or where to look next?!
    I've created an ADF BC VO with attributes that derive 3 values from LOVs. All 3 correctly render in the Business Components Browser with a pop list.
    I've also created 2 inputs forms, one standalone, the other called from an ADF Read-Only table page. Both inputs are based on exactly the same VO, created in exactly the same way from the data control pallete. This include selectOneChoice controls created for the LOVs.
    The first page always shows the VO information correctly, and the corresponding selectOneChoice fields always have entries.
    I'm getting very inconsistent results with the 2nd page called from the read-only table. Sometimes the selectOneChoice controls based on the ADF BC VO LOV fields are populated if called from a Create action, other times they're not.
    I can't understand why I'm getting the inconsistent results to the point I don't know what to give you to find the problem. If I replace the selectOneChoice with an ADF LOV control, they always correctly show the data, so it would indicate the selectOneChoice controls are having issues.
    I've also carefully compared the selectOneChoice attributes between the 2 inputForms, as well as the associated bindings, and they are the same.
    The only other difference is the original inputForm is within the unbounded task flow, while the 2nd inputForm lies in a bounded (train) task flow. I can't think of a reason why this would make a difference though.
    So at this point any help would be appeciated as I'm scratching my head to work out what's wrong here.
    Thanks for your help in advance,
    Cheers,
    Chris Muir.

    Did you know this
    Steve Muench quotes "Notice that in TP4 there is no longer an "ADF Create Form" and that we're encouraging you to create a create form using a method activity that declaratively invokes the create operation, then forwards to a page with a regular ADF Form on it. This is due to the numerous confusions that have always surrounded the ADF "invokeAction" now that we have a visual, declarative mechanism to model this type of initialization activity, we will prefer users adopting that. Also, notice that the page definition for the method activity has the new "SkipValidation" property set to true."
    Andrejus made a create sample how to use a lov when the form is in create mode. If you don't do this you get validation errors and the lov is empty.
    There is a thread in this forum and look at Andrejus blog for some create forms example
    Edwin

  • Java Swing: JComboBox  setEditable(true)

    How to limit the length of the text in Jcombobox with seteditable true to 255 characters.So that user can't enter text more then 255 characters.

    You can get editor from the JComboBox. In the editor get a text filed used for edit. You can cast it to JTextField in the simplest case. Then add a DocumentFilter to the JTextFiled's document. Override the methods to check existing Document's length and ignore edits when limit is achieved.
        public void insertString(FilterBypass fb, int offset, String string,
                                 AttributeSet attr) throws BadLocationException {
            fb.insertString(offset, string, attr);
        public void replace(FilterBypass fb, int offset, int length, String text,
                            AttributeSet attrs) throws BadLocationException {
            fb.replace(offset, length, text, attrs);
        }

  • JavaFX equivalent of Swing JComboBox.KeySelectionManager for ChoiceBox?

    Does ChoiceBox have any built-in key selection functionality as was provided by KeySelectionManager to JComboBox?
    If so, could someone provide an example?
    Else, anyone else think this would be worth a feature request? As a user, I really like being able to tab through choice boxes and just hit a key or two to make my selections as opposed to mousing and scrolling through all the items.

    I am also wondering a typical structure of application framework on java fx. Where will the screens be defined and created? How is an operational flow implemented? A simple login form with onSuccess, onError with sufficient redirections will be very helpful. I mean a crud skeleton based on common api of javafx will be a perfect guide.

  • Problem in Swing Component (JComboBox)

    Hello i've got one amazing problem in my Swing Component (JComboBox) while testing for Glasspane..
    Please check this photo http://www.flickr.com/photos/39683118@N07/4483608081/
    Well i used Netbeans Drag n Drop Swing so the code might be messing..any way my code looks like this:
    My code looks like this:
    public class NewJPanel extends javax.swing.JPanel {
        /** Creates new form NewJPanel */
        public NewJPanel() {
            initComponents();
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
            jComboBox1 = new javax.swing.JComboBox();
            jCheckBox1 = new javax.swing.JCheckBox();
            setOpaque(false);
            jTextField1.setText("jTextField1");
            jLabel1.setText("jLabel1");
            jLabel2.setText("jLabel2");
            jLabel3.setText("jLabel3");
            jButton1.setText("jButton1");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            jComboBox1.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
            jComboBox1.setNextFocusableComponent(jCheckBox1);
            jComboBox1.setOpaque(false);
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jComboBox1ActionPerformed(evt);
            jCheckBox1.setText("jCheckBox1");
            jCheckBox1.setOpaque(false);
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(119, Short.MAX_VALUE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabel1)
                        .addComponent(jLabel2)
                        .addComponent(jLabel3))
                    .addGap(51, 51, 51)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton1)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jCheckBox1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(115, 115, 115))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(70, 70, 70)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addGap(15, 15, 15)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jCheckBox1))
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addContainerGap(93, Short.MAX_VALUE))
            jComboBox1.getAccessibleContext().setAccessibleParent(null);
        }// </editor-fold>
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
        // Variables declaration - do not modify
        private javax.swing.JButton jButton1;
        private javax.swing.JCheckBox jCheckBox1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration
    }

    For more help create a [SSCCE (Short, Self Contained, Compilable and Executable, Example Program)|http://sscce.org], that demonstrates the incorrect behaviour.

  • JComboBox takes ages to load/refresh when tried to add more items.

    Swing gurus ...
    Here is the test app generated from VA3.5 concept is the
    same - JComboBox takes long time to add data items to itself when added more items.
    In this senario, I tried to load about 500 items into the combo box, takes about 2+ minutes to load. I have an app which needs to show about 1K items in the pick list ( ComboBox ) - which takes any where from 4 - 10 min - this is not acceptable - are there any ways we can load more items into combo box ? Help is really appreciated.
    Example:
    * Insert the type's description here.
    * Creation date: (6/28/2001 11:23:26 AM)
    * @author: Administrator
    public class ComboTest extends javax.swing.JFrame {
         private javax.swing.JPanel ivjJFrameContentPane = null;
         private javax.swing.JButton ivjLoadBtn = null;
         private javax.swing.JComboBox ivjTestCombo = null;
    * ComboTest constructor comment.
    public ComboTest() {
         super();
         initialize();
    * ComboTest constructor comment.
    * @param title java.lang.String
    public ComboTest(String title) {
         super(title);
    * connEtoC1: (LoadBtn.action.actionPerformed(java.awt.event.ActionEvent) --> ComboTest.loadBtn_ActionPerformed(Ljava.awt.event.ActionEvent;)V)
    * @param arg1 java.awt.event.ActionEvent
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void connEtoC1(java.awt.event.ActionEvent arg1) {
         try {
              // user code begin {1}
              // user code end
              this.loadBtn_ActionPerformed(arg1);
              // user code begin {2}
              // user code end
         } catch (java.lang.Throwable ivjExc) {
              // user code begin {3}
              // user code end
              handleException(ivjExc);
    * Return the JFrameContentPane property value.
    * @return javax.swing.JPanel
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JPanel getJFrameContentPane() {
         if (ivjJFrameContentPane == null) {
              try {
                   ivjJFrameContentPane = new javax.swing.JPanel();
                   ivjJFrameContentPane.setName("JFrameContentPane");
                   ivjJFrameContentPane.setLayout(null);
                   getJFrameContentPane().add(getTestCombo(), getTestCombo().getName());
                   getJFrameContentPane().add(getLoadBtn(), getLoadBtn().getName());
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjJFrameContentPane;
    * Return the LoadBtn property value.
    * @return javax.swing.JButton
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JButton getLoadBtn() {
         if (ivjLoadBtn == null) {
              try {
                   ivjLoadBtn = new javax.swing.JButton();
                   ivjLoadBtn.setName("LoadBtn");
                   ivjLoadBtn.setText("Load");
                   ivjLoadBtn.setBounds(248, 41, 85, 25);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjLoadBtn;
    * Return the TestCombo property value.
    * @return javax.swing.JComboBox
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private javax.swing.JComboBox getTestCombo() {
         if (ivjTestCombo == null) {
              try {
                   ivjTestCombo = new javax.swing.JComboBox();
                   ivjTestCombo.setName("TestCombo");
                   ivjTestCombo.setDoubleBuffered(true);
                   ivjTestCombo.setBounds(78, 41, 164, 23);
                   // user code begin {1}
                   // user code end
              } catch (java.lang.Throwable ivjExc) {
                   // user code begin {2}
                   // user code end
                   handleException(ivjExc);
         return ivjTestCombo;
    * Called whenever the part throws an exception.
    * @param exception java.lang.Throwable
    private void handleException(java.lang.Throwable exception) {
         /* Uncomment the following lines to print uncaught exceptions to stdout */
         // System.out.println("--------- UNCAUGHT EXCEPTION ---------");
         // exception.printStackTrace(System.out);
    * Initializes connections
    * @exception java.lang.Exception The exception description.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initConnections() throws java.lang.Exception {
         // user code begin {1}
         // user code end
         getLoadBtn().addActionListener(new java.awt.event.ActionListener() {
              public void actionPerformed(java.awt.event.ActionEvent e) {
                   connEtoC1(e);
    * Initialize the class.
    /* WARNING: THIS METHOD WILL BE REGENERATED. */
    private void initialize() {
         try {
              // user code begin {1}
              // user code end
              setName("ComboTest");
              setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
              setSize(426, 131);
              setTitle("Test App");
              setContentPane(getJFrameContentPane());
              initConnections();
         } catch (java.lang.Throwable ivjExc) {
              handleException(ivjExc);
         // user code begin {2}
         // user code end
    * Comment
    public void loadBtn_ActionPerformed(java.awt.event.ActionEvent actionEvent)
         String val = "String Item: ";
         for ( int i=0; i<500; i++ )
              getTestCombo().addItem( val + i);
         return;
    * main entrypoint - starts the part when it is run as an application
    * @param args java.lang.String[]
    public static void main(java.lang.String[] args) {
         try {
              ComboTest aComboTest;
              aComboTest = new ComboTest();
              aComboTest.addWindowListener(new java.awt.event.WindowAdapter() {
                   public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
              aComboTest.show();
              java.awt.Insets insets = aComboTest.getInsets();
              aComboTest.setSize(aComboTest.getWidth() + insets.left + insets.right, aComboTest.getHeight() + insets.top + insets.bottom);
              aComboTest.setVisible(true);
         } catch (Throwable exception) {
              System.err.println("Exception occurred in main() of javax.swing.JFrame");
              exception.printStackTrace(System.out);

    The "Really fast combo boxes" thread referred to by lk555 can be summarized as follows:
    1. RegFish wrote a custom JComboBox that handles large numbers of elements better than a standard JComboBox does.
    2. You can download his code at http://www.reddfish.co.nz/freesoftware/PoliteComboBox.jar
    3. You may want to reconsider your design, since a JComboBox with more than a few dozen elements is usually too hard for the user to use (see various postings in the long thread).

  • Changing the size of a JComboBox

    Greetings,
    I am trying to build a mechanism to perform zooming on a JPanel with an arbitrary collection of components (including nested JPanels). I've tried a number of things with little success. The following is my most promising contraption. It can zoom labels, textfields, checkboxes, and buttons. However, for some reason, the combo box refuses to accept a changes to its size. I'm not sure why this is the case. Its font changes size appropriately.
    Anyway, I'm running in JDK 1.4, and the following program lays out a palette of components. To change the size of the components, hit F1 to zoom in, and F2 to zoom out.
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.KeyEventPostProcessor;
    import java.awt.KeyboardFocusManager;
    import java.awt.event.KeyEvent;
    import java.awt.geom.AffineTransform;
    import javax.swing.JButton;
    import javax.swing.JCheckBox;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class Demo extends JPanel
        public class Zoomer
            private double m_zoom = 1;
            private JPanel m_panel;
            public Zoomer(JPanel panel)
                m_panel = panel;
            private AffineTransform getTransform()
                return AffineTransform.getScaleInstance(m_zoom, m_zoom);
            private Font transform(Font font)
                return font.deriveFont(getTransform());
            private Dimension transform(Dimension dimension)
                Dimension retval = new Dimension();
                retval.setSize(dimension.getWidth() * m_zoom, dimension.getHeight() * m_zoom);
                return retval;
            private void performZoom(Container container)
                Component[] components = container.getComponents();
                for(int i = 0; i < components.length; i++)
                    Component component = (Component)components;
    component.setFont(transform(component.getFont()));
    component.setSize(transform(component.getSize()));
    for(int i = 0; i < components.length; i++)
    Component component = components[i];
    if(component instanceof Container)
    performZoom((Container)component);
    public double getZoom()
    return m_zoom;
    public void setZoom(double zoom)
    if(zoom > 8.0 || zoom < 0.125) return;
    m_zoom = zoom;
    performZoom(m_panel);
    public void zoom(double factor)
    setZoom(getZoom() * factor);
    public Demo()
    JPanel panel = new JPanel();
    panel.add(buildPanel());
    panel.add(buildPanel());
    final Zoomer zoomer = new Zoomer(panel);
    add(panel);
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventPostProcessor(new KeyEventPostProcessor()
    public boolean postProcessKeyEvent(KeyEvent e)
    if(e.getID() != KeyEvent.KEY_PRESSED) return false;
    if(e.getKeyCode() == KeyEvent.VK_F1)
    zoomer.zoom(1.2);
    if(e.getKeyCode() == KeyEvent.VK_F2)
    zoomer.zoom(1/1.2);
    return false;
    private JPanel buildPanel()
    JPanel panel = new JPanel();
    panel.add(new JLabel("label: "));
    panel.add(new JTextField("Hello World"));
    panel.add(new JCheckBox("checkbox"));
    panel.add(new JComboBox(new String[] { "Bread", "Milk", "Butter" }));
    panel.add(new JButton("Hit Me!"));
    return panel;
    * Create the GUI and show it. For thread safety, this method should be
    * invoked from the event-dispatching thread.
    private static void createAndShowGUI()
    // Create and set up the window.
    JFrame frame = new JFrame("Demo");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // Create and set up the content pane.
    Demo newContentPane = new Demo();
    newContentPane.setOpaque(true); // content panes must be opaque
    frame.setContentPane(newContentPane);
    // Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args)
    // Schedule a job for the event-dispatching thread:
    // creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    public void run()
    createAndShowGUI();

    component.setSize(transform(component.getSize()));First of all the above line is not needed. The LayoutManager will determine the bounds (size and location) of each component in the container based on the rules of the LayoutManager. The Flow Layout is the default layout manager for a panel and it simply uses the preferred size of the component as the size of the component.
    So what happens is that when you change the font of the component you are changing the preferred size of the component.
    So why doesn't the combo box work? Well I took a look at the preferred size calculation of the combo box (from the BasicComboBoxUI) and it actually caches the preferred size. The combo box uses a renderer, so the value is cached for performance one would assume. The method does recalculate the size when certain properties change. Note the isDisplaySizeDirty flag used in the code below:
             else if (propertyName.equals("prototypeDisplayValue")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
             else if (propertyName.equals("renderer")) {
                    isMinimumSizeDirty = true;
                    isDisplaySizeDirty = true;
                    comboBox.revalidate();
                }It also handles a Font property change as well:
                else if ( propertyName.equals( "font" ) ) {
                    listBox.setFont( comboBox.getFont() );
                    if ( editor != null ) {
                        editor.setFont( comboBox.getFont() );
                    isMinimumSizeDirty = true;
                    comboBox.validate();
                }but notice that the isDisplaySizeDirty flag is missing. This would seem to be a bug (but I don't know why two flags are required).
    Anyway, the following change to your code seems to work:
    // component.setSize(transform(component.getSize()));
    if (component instanceof JComponent)
         ((JComponent)component).updateUI();
    }

  • Update Jcombobox 's label in render

    hi ,everybody, i have a problem about combobox, any body can help me!
    thank you!
    I want to have a combobox with checkbox as item, I rewrite a render writen by ice, because the combobox has three state, when I click diferent checkbox in this combobox , the label of combobox will update rightly, but if I click one checkbox to change the checkbox state ,the label will no update , it seem that when I click one checkbox many times .the menthod
    getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus)
    will no update label
    my code :
    mainclass:
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Iterator;
    import java.util.Vector;
    import javax.swing.DefaultListCellRenderer;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.plaf.basic.BasicComboBoxEditor;
    public class mainclass {
          public static void main(String[] args) {
                 final testbox myComboBox = new testbox();
                 myComboBox.addItem("SelectAll");
                 myComboBox.addItem("ClearAll");
                 myComboBox.addItem("GrayedAll");
                 for(int i = 0; i < 5; i++) {
                     myComboBox.addItem("Item " + i);
                 JFrame frame = new JFrame("My ComboBox");
                 frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                 frame.setSize(150, 60);
                 frame.setLocation(300, 300);
                 //frame.setJMenuBar( menubar );
                 JPanel panel=new JPanel();
                 panel.setLayout(new BorderLayout());
                 panel.add(myComboBox,BorderLayout.NORTH);        
                 frame.getContentPane().add(panel);
                 frame.setVisible(true);
                 final IconedCellRendererField renderer = IconedCellRendererField.getCheckBoxRendererInstance();
                 myComboBox.setRenderer(renderer);
                 myComboBox.addActionListener(new ActionListener()
                     public void actionPerformed(ActionEvent e)
                          if(myComboBox.getSelectedItem().toString().equals("SelectAll")){
                               renderer.selectAll(true);                         
                          if(myComboBox.getSelectedItem().toString().equals("ClearAll")){
                               renderer.clearAll(true);
                          if(myComboBox.getSelectedItem().toString().equals("GrayedAll")){
                               renderer.grayedAll(true);
    }renderer:
    import java.awt.*;
    import java.awt.event.*;
    //import java.io.*;
    //import java.net.*;
    import java.util.*;
    import javax.swing.*;
    //import javax.swing.event.*;
    import javax.swing.border.*;
    //import javax.swing.table.*;
    public class IconedCellRendererField extends DefaultListCellRenderer implements MouseListener {
         public Icon icon, selIcon;
         Icon[] icons = null;
         public boolean useIconBackground = true, useIndexSensitiveIcons = false,
                   useCheckBoxAsIcon = false, useLinkState = false;
         Dimension labelDim = null;
         public JLabel iconLabel;
         public JCheckBox box = null;
         public JPanel noback;
         public SelectionStateHandler selStateHandler = null;     
         private JList theList = null;
         public boolean[] selState = null, enableState = null;
         int offset = 5;
         Rectangle rect = null;
         int currentLinkRow = -1;
         boolean isOnRow = false, paintDivider = false;
         private Icon dividerImage = null;     
         private Color linkColor = Color.blue, hoverColor = Color.red, selectedLinkColor = Color.green;
         /* Initialises the renderer with one icon that is displayed without the
          * cell background.
         public IconedCellRendererField(Icon icon) {
              this(icon,false);
         /* Initialises the renderer with two icons that provide a switch capability
          * when a row is selected/deselected
         public IconedCellRendererField(Icon icon, Icon selIcon) {
              this.icon = icon;
              this.selIcon = selIcon;
              //addMouseListener(this);
         /* Initialises the renderer with two icons that provide a switch capability
          * when a row is selected/deselected. The boolean argument enables the icon
          * to either use the renderer background or appear transparent.
         public IconedCellRendererField(Icon icon, Icon selIcon, boolean useIconBackground) {
              this(icon, selIcon);
              setIconHasBackground(useIconBackground);
              createNoBackgroundPanel();
         /* Initialises the renderer with a single no siwthing icon. The boolean
          * argument enables the icon to either use the renderer background
          * or appear transparent.
         public IconedCellRendererField(Icon icon, boolean useIconBackground) {
              this(icon, icon, useIconBackground);
         /* Initialises the renderer to load two icons from the provided image locations.
          * This enables icon switching on selection.
         public IconedCellRendererField(String iconLoc, String selIconLoc) {
              icon = new ImageIcon(iconLoc);
              selIcon = new ImageIcon(selIconLoc);
              //addMouseListener(this);
         /* Initialises the renderer to load a single icon from the provided image location.
          * The icon can either have the renderer background or not based on the
          * boolean property.
         public IconedCellRendererField(String iconLoc, boolean iconBackground) {
              this(iconLoc, iconLoc, iconBackground);
         /* Initialises the renderer to load two icons from the provided image locations.
          * This enables icon switching on selection. The icon can either have the renderer
          * background or not based on the boolean property.
         public IconedCellRendererField(String iconLoc, String selIconLoc, boolean iconBackground) {
              this(iconLoc, selIconLoc);
              setIconHasBackground(iconBackground);
              createNoBackgroundPanel();
         /* Initialises the renderer to load a single icon from the provided image location.
         public IconedCellRendererField(String iconLoc) {
              this(iconLoc, true);
         /* Initialises the renderer with an array of image icons that are repeated for
          * each row in the list.
         public IconedCellRendererField(Icon[] icons, boolean useIconBackground) {
              this(icons[0], icons[0], useIconBackground);
         public void createNoBackgroundPanel() {
              iconLabel = new JLabel((Icon)null, JLabel.CENTER);
              if(labelDim != null) {      iconLabel.setPreferredSize(labelDim); }
              iconLabel.setBorder( new EmptyBorder(1,5,1,5) );
              noback = new JPanel( new BorderLayout() ) {
                  * Overridden for performance reasons.
                  * See the <a href="#override">Implementation Note</a>
                  * for more information.
                  //public void validate() {}
                 // public void invalidate() {}          
                  public void repaint() {}
                  //public void revalidate() {}
                  public void repaint(long tm, int x, int y, int width, int height) {}
                  public void repaint(Rectangle r) {}
                  protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
                        // Strings get interned...
                        if (propertyName == "text"
                                   || ((propertyName == "font" || propertyName == "foreground")
                                       && oldValue != newValue)) {
                            super.firePropertyChange(propertyName, oldValue, newValue);
                  public void firePropertyChange(String propertyName, byte oldValue, byte newValue) {}
                  public void firePropertyChange(String propertyName, char oldValue, char newValue) {}
                  public void firePropertyChange(String propertyName, short oldValue, short newValue) {}
                  public void firePropertyChange(String propertyName, int oldValue, int newValue) {}
                  public void firePropertyChange(String propertyName, long oldValue, long newValue) {}
                  public void firePropertyChange(String propertyName, float oldValue, float newValue) {}
                  public void firePropertyChange(String propertyName, double oldValue, double newValue) {}
                  public void firePropertyChange(String propertyName, boolean oldValue, boolean newValue) {}
              if(useCheckBoxAsIcon()) {
                   box = new JCheckBox();
                   //box.addMouseListener(this);
                   box.setOpaque(false);
                   noback.add( box, BorderLayout.WEST );
                   //noback.addMouseListener(this);
                   rect = box.getBounds();
                   //list.addMouseListener(this);
              } else {
                   noback.add( iconLabel, BorderLayout.WEST );
              noback.add( this, BorderLayout.CENTER );
              noback.setBorder( new EmptyBorder(1,1,1,1) );
              noback.setOpaque(false);
         public Component getListCellRendererComponent(JList list, Object value, int index,
                        boolean isSelected, boolean cellHasFocus) {
              System.out.println(value+"+"+index+"+"+isSelected+"+"+cellHasFocus);
              if(theList == null || theList != list) {
                   theList = list;
                   if(useLinkState) {
                        attachLinkSimulationListener();
              setOpaque(true);
              setText( value == null ? "" : value.toString());
              if(useIndexSensitiveIcons) {
                   icon = getIcon(index);
              if(useIconBackground)
                   setIcon(icon);          
              setFont( list.getFont() );
              setToolTipText(value.toString() );
              if(list.isEnabled())
                   setEnabled( isEnabled(index) );
              else
                   setEnabled( list.isEnabled() );
              if(isSelected && isEnabled(index) ) {
                   setForeground( Color.black );
                   setBackground( new Color(223, 235, 245) );
                   if(useIndexSensitiveIcons) {
                        selIcon = getIcon(index);
                   if(useIconBackground)
                        setIcon(selIcon);
              } else {
                   setForeground(Color.black);
                   setBackground(Color.white);
                   setBorder(null);
              if(cellHasFocus) {
                   setBorder( new CompoundBorder( new LineBorder( new Color(150, 150, 220) ),
                                                      new EmptyBorder(2,2,2,2)  ) );
              } else {
                   setBorder( new EmptyBorder(2,2,2,2));
              if(useLinkState) {
                   if(currentLinkRow == index) {
                        setText("<html><u>" + value.toString()+"</u></html>" );     
                        setForeground( getHoverLinkColor() );               
                   } else {
                        setForeground( getLinkColor() );
                   if(isSelected) {
                        setForeground( getSelectedLinkColor() );
                   setBackground(Color.white);
                   setBorder( new EmptyBorder(1,1,1,1) );
              if( shdPaintDivider() ) {
                   Border border = null;
                   if(dividerImage != null) {
                        border = new MatteBorder(0,0,1,0, dividerImage);
                   } else {
                        border = new MatteBorder(0,0,1,0, getLinkColor() );
                   if(index < theList.getModel().getSize() - 1 ) {
                        setBorder( new CompoundBorder(getBorder(),border) );
                   } else {
                        setBorder( new EmptyBorder(1,1,1,1) );
              if(useIconBackground == false) {
                  if(isSelected)
                      iconLabel.setIcon(selIcon);
                  else
                      iconLabel.setIcon(icon);
                  if(useCheckBoxAsIcon()) {
                      if(selState == null) {
                          updateSelectionStateTrackers(list);
                      if(selStateHandler == null) {
                          list.addMouseListener( selStateHandler = new SelectionStateHandler(list) );
                      try {
                          box.setSelected( selState[index] );
                      } catch(Exception e) {}
                  if( shdPaintDivider() ) {              
                      //if(index < theList.getModel().getSize() - 1 ) {
                          noback.setBorder( getBorder() );
                          setBorder( new EmptyBorder(1,1,1,1) );
                      //} else {
                      //  noback.get
                  // this should cause a JComboBox to paint the Label instead of the
                  // check box + label combination
                  if(index == -1) {
                       Vector<Object> v=new Vector<Object>();
                       v=getSelectedObjects();
                        String val=generateString();
                       JLabel label=new JLabel(val);                    
                      if(iconLabel.getIcon() != null) {
                           label.setIcon( iconLabel.getIcon() );
                      System.out.println("label");
                      return label;
                  return noback;
              return this;
         public String generateString()
              String val = "";
              if(selState[0]==true&&selState[1]==false&&selState[2]==false){
                    for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(val.length()==0){
                                  val=val+curString+"-1";
                           } else {                              
                                  val=val+"&"+curString+"-1";
               //clear all     
               if(selState[1]==true&&selState[0]==false&&selState[2]==false ){                                   
                      for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(val.length()==0){
                                  val=val+curString+"-0";
                           } else {                              
                                  val=val+"&"+curString+"-0";
              //grayedall
               if(selState[2]==true&&selState[0]==false&&selState[1]==false ){                                   
                      val="";                      
               if(selState[0]==false&&selState[1]==false&&selState[2]==false ){
                    for(int i = 3; i < theList.getModel().getSize(); i++) {
                           String curString=theList.getModel().getElementAt(i).toString();
                           if(selState==true&&enableState[i]==false){
                             continue;
                        if(selState[i]==true&&enableState[i]==true){
                             if(val.length()==0){
                                       val=val+curString+"-1";
                             } else {                              
                                       val=val+"&"+curString+"-1";
                        if(selState[i]==false&&enableState[i]==true){
                             if(val.length()==0){
                                       val=val+curString+"-0";
                             } else {                              
                                       val=val+"&"+curString+"-0";
              return val;
         public void updateSelectionStateTrackers(JList list) {
              selState = new boolean[ list.getModel().getSize() ];
              enableState = new boolean[ list.getModel().getSize() ];
              for(int i = 0; i < selState.length; i++) {
                   selState[i] = false;
                   enableState[i] = true;
         public int[] getSelectedIndices() {
              if(!useCheckBoxAsIcon()) {
                   return new int[0];
              int length = 0;
              if(selState==null){
                   return null;
              for(int i = 0; i < selState.length; i++) {
                   if(selState[i]) {
                        length++;
              int[] indices = new int[length];
              for(int i = 0, n = 0; i < selState.length; i++) {
                   if(selState[i]) {
                        indices[n++] = i;
              //System.out.println("Selected Indices.length = " + indices.length);
              return indices;
         public Vector<Object> getSelectedObjects() {
              int[] indices = getSelectedIndices();
              Vector<Object> objects = new Vector<Object>();
              if(indices==null){
                   return null;
              for(int i = 0; i < indices.length; i++) {
                   objects.addElement( theList.getModel().getElementAt(indices[i]) );
              return objects;
         public void setIconHasBackground(boolean b) {
              useIconBackground = b;
         public Icon[] getIcons() {
              return icons;
         public Icon getIcon(int index) {
              if(icons != null && icons.length == 0) {
                   return icon;
              if(icons != null && index > icons.length) {
                   index = index - (icons.length - 1);
              return icons[index];
         public void setIcons(Icon[] icons) {
              if(icons != null) {
                   useIndexSensitiveIcons = true;
              this.icons = icons;
         public void setIcon(Icon icon, int index) {
              if(icons != null && icons.length > 0) {
                   icons[index] = icon;
         public void setIconLabelDimension(Dimension dim) {
              labelDim = dim;
         public static IconedCellRendererField getCheckBoxRendererInstance() {
              IconedCellRendererField cr = new IconedCellRendererField(new EmptyIcon());
                   cr.setUseCheckBoxAsIcon(true);
              return cr;
         public void setUseCheckBoxAsIcon(boolean use) {
              useCheckBoxAsIcon = use;
              createNoBackgroundPanel();
         public boolean useCheckBoxAsIcon() {
              return useCheckBoxAsIcon;
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
         public void setDisplayItemsAsLinks(boolean use) {
              useLinkState = use;
         public void setLinkColor(Color color) {
              linkColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getLinkColor() {
              return linkColor;
         public void setHoverLinkColor(Color color) {
              hoverColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getHoverLinkColor() {
              return hoverColor;
         public void setSelectedLinkColor(Color color) {
              selectedLinkColor = color;
              if(theList != null) {
                   theList.repaint();
         public Color getSelectedLinkColor() {
              return selectedLinkColor;
         public void attachLinkSimulationListener() {
              theList.setCursor( Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) );
              theList.addMouseListener( new MouseAdapter() {
                   public void mouseEntered(MouseEvent e) {
                        isOnRow = true;                    
                   public void mouseExited(MouseEvent e) {
                        isOnRow = false;
    currentLinkRow = -1;
    theList.repaint();
              theList.addMouseMotionListener( new MouseMotionAdapter() {
                   public void mouseMoved(MouseEvent e) {
    isOnRow = true;
    currentLinkRow = theList.locationToIndex( e.getPoint() );
    theList.repaint();
              /*table.addMouseListener(new MouseAdapter() {
    public void mouseEntered(MouseEvent e) {
    public void mouseExited(MouseEvent e) {
    isOnRow = false;
    currentHighlightRow = -1;
    table.repaint();
    table.addMouseMotionListener( new MouseMotionAdapter() {
    public void mouseMoved(MouseEvent e) {
    isOnRow = true;
    currentHighlightRow = table.rowAtPoint( e.getPoint() );
    table.repaint();
         public boolean shdPaintDivider() {
              return paintDivider;
         public void setPaintDivider(boolean paintDivider) {
              this.paintDivider = paintDivider;
         public void setDividerImage(Icon icon) {
              this.dividerImage = icon;
              setPaintDivider(true);
         private void dispatchEvent(MouseEvent me) {
    if(rect != null && box != null && rect.contains(me.getX(), me.getY())){
    Point pt = me.getPoint();
    pt.translate(0,0);
    box.setBounds(rect);
    box.dispatchEvent(new MouseEvent(box, me.getID()
    , me.getWhen(), me.getModifiers()
    , pt.x, pt.y, me.getClickCount()
    , me.isPopupTrigger(), me.getButton()));
    if(!box.isValid()) {
         repaint();
         System.out.println("Dispatch Event: Box.invalid called");
    System.out.println("Dispatch Event called");
    } else {
         System.out.println("Dispatch Event Called, rect null");
    public void mouseClicked(MouseEvent me){
    dispatchEvent(me);
    public void mouseEntered(MouseEvent me){
    dispatchEvent(me);
    public void mouseExited(MouseEvent me){
    dispatchEvent(me);
    public void mousePressed(MouseEvent me){
    dispatchEvent(me);
    public void mouseReleased(MouseEvent me){
    dispatchEvent(me);
    public class SelectionStateHandler extends MouseAdapter {
         JList list = null;
         public SelectionStateHandler(JList list) {
              this.list = list;
         public void mouseClicked(MouseEvent e)
              * Handles the checkbox selection process. Uses the bounds property of the
              * check box within the selected cell to determine whether the checkbox should
              * be selected or not
              public void mouseReleased(MouseEvent e) {
                   /*if(list == null || list.getSelectedIndex() == -1
         || !isEnabled( list.locationToIndex(e.getPoint()) ) ) {
         return;
              if(list == null || list.getSelectedIndex() == -1){
                   return;
         int[] indices = list.getSelectedIndices();
         // get the current relative position of the check box
         //rect = box.getBounds(rect);
         for(int i = 0; i < indices.length; i++) {
         // get the current relative position of the check box
         int loc = list.locationToIndex( e.getPoint() );
         rect = list.getCellBounds(loc,loc);
         // ensure the point clicked in within the checkBox
         if(e.getX() < (rect.getX() + 20) ) {
              Object obj=list.getModel().getElementAt(i);
              //if(!obj.equals("SelectAll")&&!obj.equals("ClearAll")&&!obj.equals("GrayedAll")){
                   if(indices[i]>2){
                        selState[0]=false;
                        selState[1]=false;
                        selState[2]=false;
                        //����
                        if(!this.isEnabled(indices[i])&&selState[indices[i]]==true){
                             this.setEnabled(indices[i],true);
                             selState[indices[i]]=false;
                        } else if(this.isEnabled(indices[i])&&selState[indices[i]]==true){
                             //����
                             selState[indices[i]]=true;
                             this.setEnabled(indices[i],false);                              
                        }else if(this.isEnabled(indices[i])&&selState[indices[i]]==false){
                             //����
                             selState[indices[i]]=true;
                             this.setEnabled(indices[i],true);
                   } else {
                        selState[indices[i]] = !selState[indices[i]];
         list.revalidate();
         list.repaint();
         public void selectAll(boolean b) {
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        this.enableAll(true);
                        Object obj=list.getModel().getElementAt(i);
                        if(!obj.equals("ClearAll")&&!obj.equals("GrayedAll")){
                             selState[i] = b;
                        } else{
                             selState[i]=!b;
                        selState[0]=false;
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void clearAll(boolean b){
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        Object obj=list.getModel().getElementAt(i);
                        this.enableAll(true);
                        if(!obj.equals("ClearAll")){
                             selState[i] = !b;
                        } else{
                             selState[i]=b;
                        selState[1]=false;
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void grayedAll(boolean b){
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   try {
                        Object obj=list.getModel().getElementAt(i);
                        if(!obj.equals("SelectAll")&&!obj.equals("ClearAll")){
                             if(i==2){
                                  selState[i] = !b;
                             }else{                             
                                  selState[i] = b;
                             this.setEnabled(i,false);
                        } else{
                             selState[i]=!b;                          
                   } catch(ArrayIndexOutOfBoundsException aie) {
                        updateSelectionStateTrackers(list);
                        selectAll(b);
                        return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void setSelectedIndex(int index) {
              for(int i = 0; i < list.getModel().getSize(); i++) {
                   selState[i] = false;
              selectIndex(index);
         public void selectIndex(int index) {
              try {
                   selState[index] = true;
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   selectIndex(index);
                   return;
              if(list != null) {
                   list.revalidate();
                   list.repaint();
         public void setEnabled(int index, boolean b) {
              try {
                   enableState[index] = b;
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   setEnabled(index, b);
         public boolean isEnabled(int index) {
              if(index == -1) {
                   return true;
              boolean isEnabled = true;
              try {
                   isEnabled = enableState[index];
              } catch(ArrayIndexOutOfBoundsException aie) {
                   updateSelectionStateTrackers(list);
                   return isEnabled(index);
              return isEnabled;
         public void enableAll(boolean b) {
              for(int i = 0; i < enableState.length; i++) {
                   enableState[i] = b;
    public void selectAll(boolean b) {
         if(selStateHandler == null) {
              return;
         selStateHandler.selectAll(b);
    public void clearAll(boolean b){
         if(selStateHandler == null) {
              return;
         selStateHandler.clearAll(b);
    public void grayedAll(boolean b){
         if(selStateHandler == null) {
              return;
         selStateHandler.grayedAll(b);
    public void setSelectedIndex(int index) {
         if(selStateHandler == null) {
              return;
         selStateHandler.setSelectedIndex(index);
    public void selectIndex(int index) {
         if(selStateHandler == null) {
              return;
         selStateHandler.selectIndex(index);
    public void enableAll(boolean b) {
         if(selStateHandler == null) {
              return;
         selStateHandler.enableAll(b);
    public void setEnabled(int index, boolean enable) {
         if(selStateHandler == null) {
              return;
         selStateHandler.setEnabled(index, enable);
    public boolean isEnabled(int index) {
         if(selStateHandler == null) {
              return true;
         return selStateHandler.isEnabled(index);
    public boolean isEnabledAll() {
         if(enableState == null) return true;
         for(int i = 0; i < enableState.length; i++) {
              if(!isEnabled(i)) {
                   return false;
         return true;
    // EmptyIcon implementation
    public static class EmptyIcon implements Icon {
         int width = 16, height = 16;
         public EmptyIcon() {
         setSize(16,16);
         public EmptyIcon(int width, int height) {
         setSize(width, height);
         public void setSize(int width, int height) {
         this.width = width;
         this.height = height;
         public int getIconWidth() {  return width; }
         public int getIconHeight() { return height; }
         public void paintIcon(Component c, Graphics g, int x, int y) {}
    public int getItemCount(){
         if(theList!=null){
              return theList.getModel().getSize();
         } else {
              return 0;
         public boolean[] getEnableState() {
              return enableState;
         public boolean[] getSelState() {
              return selState;
         public JList getTheList() {
              return theList;
    testbox :import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JComboBox;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    public class testbox extends JComboBox
    * @param args
    JComboBox myComboBox;
    public testbox()
    myComboBox = new JComboBox();
    public void setPopupVisible(boolean b)
         if(b)
              myComboBox.showPopup();
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

    You are updating the label value when (index == -1), let change into (index<=0).
    like below
    // this should cause a JComboBox to paint the Label instead of the
                // check box + label combination
                if (index <= 0) {
                    Vector v = new Vector();
                    v = getSelectedObjects();
                    String val = generateString();
                    JLabel label = new JLabel(val);
                    if (iconLabel.getIcon() != null) {
                        label.setIcon(iconLabel.getIcon());
                    System.out.println("label");
                    return label;
                }

  • How to Scatter JComboBox ?

    Hi, i am working on a simple example to learn the Swing API. I have a small program that uses 6 different combo boxes. there should be 2 sets of 3 Combo boxes (day, month, year). My problem is that I cannot seem to get them to seperate. They always line up right next to each other. I posted some code below. sorry the tabbing is a bit screwy. if you paste it to an editor it will make more sense. anyways, i use 2 different jpanels, with a GridLayout of only one column (inserting Jpanels into a gridlayout of only 1 column), but still it aligns them together on the same line! i can't figure it out. any help will be appreciated. thanks
    ps-you should be able to just cut and paste this code and compile if you want to see what i mean.
    import javax.swing.*;
    import java.awt.*;
    import java.lang.*;
    public class DateFinder {
         public static void main(String[] args) {
              JFrame           myFrame           = new JFrame("How many days since your birthday?");
              Container      myContentPane      = myFrame.getContentPane();
              JPanel           buttonPanel      = new JPanel(new GridLayout(1,2));
              JPanel          comboPanel          = new JPanel(new GridLayout(1,4));
              JPanel          comboPanel1          = new JPanel(new GridLayout(1,4));
              JPanel          rootPanel          = new JPanel(new GridLayout(8,1));
              JButton      Calculate           = new JButton("Calculate");
              JButton          Reset               = new JButton("Reset");
              JLabel          yourBday          = new JLabel("Your Birthday");
              JLabel          Today               = new JLabel("Today");
              int           yearCounter          = 0;
              int           i;
              String[]     DaysList          = {"1","2","3","4","5","6","7","8","9","10",
                                                 "11","12","13","14","15","16","17","18",
                                                 "19","20","21","22","23","24","25","26",
                                                 "27","28","29","30","31"};
              String[]     MonthsList          = {"January","February","March","April","May",
                                                 "June","July","August","September","October",
                                                 "November","December"};
              String[] YearsList = new String[120];
              for(i=0;i<120;i++) {
                   YearsList[i] = String.valueOf(2005 - i);
              }//end for
    JComboBox DaysCombo     = new JComboBox(DaysList);
    JComboBox MonthsCombo     = new JComboBox(MonthsList);
    JComboBox YearsCombo     = new JComboBox(YearsList);
    JComboBox DaysCombo1     = new JComboBox(DaysList);
    JComboBox MonthsCombo1= new JComboBox(MonthsList);
    JComboBox YearsCombo1     = new JComboBox(YearsList);
              buttonPanel.add(Calculate);
              buttonPanel.add(Reset);
              comboPanel.add(yourBday);
              comboPanel.add(DaysCombo);
              comboPanel.add(MonthsCombo);
              comboPanel.add(YearsCombo);
              comboPanel1.add(Today);
              comboPanel1.add(DaysCombo1);
              comboPanel1.add(MonthsCombo1);
              comboPanel1.add(YearsCombo1);
              rootPanel.add(comboPanel);
              rootPanel.add(comboPanel1);
              rootPanel.add(buttonPanel);
              comboPanel.add(DaysCombo1);
              comboPanel.add(MonthsCombo1);
              comboPanel.add(YearsCombo1);
              myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              myContentPane.add(rootPanel);
              //myContentPane.add(buttonPanel, BorderLayout.SOUTH);
              //myContentPane.add(comboPanel, BorderLayout.EAST);
              //myContentPane.add(comboPanel1,BorderLayout.NORTH);
              myFrame.setSize(500,200);
              myFrame.setVisible(true);
         }//end main
    }//end class definition

    OK.. I guess I now understood your problem and debugged ur code...
    You have three lines of unnecessary code. (Repeated twice).
    import java.awt.BorderLayout;
    import java.awt.Container;
    import java.awt.GridLayout;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class Temp {
         public static void main(String[] args) {
              JFrame myFrame = new JFrame("How many days since your birthday?");
              Container myContentPane = myFrame.getContentPane();
              JPanel buttonPanel = new JPanel(new GridLayout(1, 2));
              JPanel comboPanel = new JPanel(new GridLayout(1, 4));
              JPanel comboPanel1 = new JPanel(new GridLayout(1, 4));
              JPanel rootPanel = new JPanel(new GridLayout(3, 1));
              JButton Calculate = new JButton("Calculate");
              JButton Reset = new JButton("Reset");
              JLabel yourBday = new JLabel("Your Birthday");
              JLabel Today = new JLabel("Today");
              int yearCounter = 0;
              int i;
              String[] DaysList =
                        "1",
                        "2",
                        "3",
                        "4",
                        "5",
                        "6",
                        "7",
                        "8",
                        "9",
                        "10",
                        "11",
                        "12",
                        "13",
                        "14",
                        "15",
                        "16",
                        "17",
                        "18",
                        "19",
                        "20",
                        "21",
                        "22",
                        "23",
                        "24",
                        "25",
                        "26",
                        "27",
                        "28",
                        "29",
                        "30",
                        "31" };
              String[] MonthsList =
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December" };
              String[] YearsList = new String[120];
              for (i = 0; i < 120; i++) {
                   YearsList = String.valueOf(2005 - i);
              } //end for
              JComboBox DaysCombo = new JComboBox(DaysList);
              JComboBox MonthsCombo = new JComboBox(MonthsList);
              JComboBox YearsCombo = new JComboBox(YearsList);
              JComboBox DaysCombo1 = new JComboBox(DaysList);
              JComboBox MonthsCombo1 = new JComboBox(MonthsList);
              JComboBox YearsCombo1 = new JComboBox(YearsList);
              buttonPanel.add(Calculate);
              buttonPanel.add(Reset);
              comboPanel.add(yourBday);
              comboPanel.add(DaysCombo);
              comboPanel.add(MonthsCombo);
              comboPanel.add(YearsCombo);
              comboPanel1.add(Today);
              comboPanel1.add(DaysCombo1);
              comboPanel1.add(MonthsCombo1);
              comboPanel1.add(YearsCombo1);
              rootPanel.add(comboPanel);
              rootPanel.add(comboPanel1);
              rootPanel.add(buttonPanel);
              //YOU DO NOT NEED THE FOLLOWING THREE LINES.
    //          comboPanel.add(DaysCombo1);
    //          comboPanel.add(MonthsCombo1);
    //          comboPanel.add(YearsCombo1);
              myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              myContentPane.add(rootPanel, BorderLayout.CENTER);
              //myContentPane.add(buttonPanel, BorderLayout.SOUTH);
              //myContentPane.add(comboPanel, BorderLayout.EAST);
              //myContentPane.add(comboPanel1,BorderLayout.NORTH);
              myFrame.setSize(500, 200);
              myFrame.setVisible(true);
         } //end main
    } //end class definition
    Run this progam and I guess you will see what you have been wanting to.
    Sai Pullabhotla.

  • What is the best way to use Swing GUIs in an MVC design?

    I have a question on how to build an application using swing frames for the UI, but using an MVC architecture. I've checked the rest of the forum, but not found an answer to my question that meets my needs.
    My application at this stage presents a login screen to get the userid and password, or to allow the user to choose a new locale. If an Enter action is performed, the userid and password are checked against the DB. If not accepted, the screen is repainted with a "try-again" message. If the Cancel action is performed, the process stops. If a locale action is performed, the screen is repainted with different langauge labels. Once the login process is passed, a front screen (another swing frame) is presented.
    Implementation: I am using a session object (Session, represents the user logging in) that calls the Login screen (LoginGUI, a Swing JFrame object with various components). Session uses setters in LoginGUI to set the labels, initial field entries etc, before enabling the screen. From this point, the user will do something with the LoginGUI screen - could be closing the window, entering a mix of userid and password, or maybe specifying a locale. Once the user has taken the action, if required, the session object can use getters to retrieve the userid and password values entered in the fields.
    The crux of the problem is 1) how will Session know that an action has been taken on the LoginGUI, and 2) how to tell what action has been taken.
    This could be solved by getting LoginGUI to call back to Session, however, I am trying to buid the application with a good separation of business, logic and presentation (i.e MVC, but not using any specific model). Therefore, I do not want LoginGUI to contain any program flow logic - that should all be contained in Session.
    I am aware of two possible ways to do this:
    1. Make LoginGUI synchronised, so that Session waits for LoginGUI to send a NotifyAll(). LoginGUI could hold a variable indicating what has happened which Session could interrogate.
    2. Implement Window Listener on Session so that it gets informed of the Window Close action. For the other two actions I could use a PropertyChangeListener in Session, that is notified when some variable in LoginGUI is changed. This variable could contain the action performed.
    Has anyone got any comments on the merits of these methods, or perhaps a better method? This technique seems fundamental to any application that interfaces with end-users, so I would like to find the best way.
    Thanks in advance.

    Hi,
    I tried to avoid putting in specific code as my question was more on design, and I wanted to save people having to trawl through specific code. And if I had any school assignments outstanding they would be about 20 years too late :-). I'm not sure computers more sophisticated than an abacus were around then...
    Rather than putting the actual code (which is long and refers to other objects not relevant to the discussion), I have put together two demo classes to illustrate my query. Comments in the code indicate where I have left out non-relevant code.
    Sessiondemo has the main class. When run, it creates an instance of LoginGUIdemo, containing a userid field, password field, a ComboBox (which would normally have a list of available locales), an Enter and a Cancel box.
    When the Locale combo box is clicked, the LoginGUIdemo.userAction button is changed (using an ActionListener) and a property change is fired to Session (which could then perform some work). The same technique is used to detect Enter events (pressing return in password and userid, or clicking on Enter), and to detect Cancel events (clicking on the cancel button). Instead of putting in business code I have just put in System.out.printlns to print the userAction value.
    With this structure, LoginGUIdemo has no business logic, but just alerts Sessiondemo (the class with the business logic).
    Do you know any more elegant way to achieve this function? In my original post, I mentioned that I have also achieved this using thread synchronisation (Sessiondemo waits on LoginGUI to issue a NotifyAll() before it can retrieve the LoginGUI values). I can put together demo code if you would like. Can you post any other demo code to demonstrate a better technique?
    Cheers,
    Alan
    Here's Sessiondemo.class
    import java.io.*;
    import java.awt.event.*;
    import java.util.*;
    import java.beans.*;
    public class Sessiondemo implements PropertyChangeListener {
        private LoginGUIdemo lgui;   // Login screen
        private int localeIndex; // index referring to an array of available Locales
        public Sessiondemo () {
            lgui = new LoginGUIdemo();
            lgui.addPropertyChangeListener(this);
            lgui.show();
        public static void main(String[] args) {
            Sessiondemo sess = new Sessiondemo();
        public void propertyChange(java.beans.PropertyChangeEvent pce) {
            // Get the userAction value from LoginGUI
            String userAction = pce.getNewValue().toString();
            if (userAction == "Cancelled") {
                System.out.println(userAction);
                // close the screen down
                lgui.dispose();
                System.exit(0);
            } else if (userAction == "LocaleChange") {
                System.out.println(userAction);
                // Get the new locale setting from the LoginGUI
                // ...modify LoginGUI labels with new labels from ResourceBundle
    lgui.show();
    } else if (userAction == "Submitted") {
    System.out.println(userAction);
    // ...Get the userid and password values from LoginGUIdemo
                // run some business logic to decide whether to show the login screen again
                // or accept the login and present the application frontscreen
    }And here's LoginGUIdemo.class
    * LoginGUIdemox.java
    * Created on 29 November 2002, 18:59
    * @author  administrator
    import java.beans.*;
    public class LoginGUIdemo extends javax.swing.JFrame {
        private String userAction;
        private PropertyChangeSupport pcs;
        /** Creates new form LoginGUIdemox */
        // Note that in the full code there are setters and getters to allow access to the
        // components in the screen. For clarity they are not included here
        public LoginGUIdemo() {
            pcs = new PropertyChangeSupport(this);
            userAction = "";
            initComponents();
        public void setUserAction(String s) {
            userAction = s;
            pcs.firePropertyChange("userAction",null,userAction);
        public void addPropertyChangeListener(PropertyChangeListener l) {
            pcs.addPropertyChangeListener(l);
        public void removePropertyChangeListener(PropertyChangeListener l) {
            pcs.removePropertyChangeListener(l);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        private void initComponents() {
            jTextField1 = new javax.swing.JTextField();
            jTextField2 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            getContentPane().setLayout(new java.awt.FlowLayout());
            addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent evt) {
                    exitForm(evt);
            jTextField1.setText("userid");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField1);
            jTextField2.setText("password");
            jTextField2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jTextField2);
            jComboBox1.setToolTipText("Select Locale");
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    LocaleActionPerformed(evt);
            getContentPane().add(jComboBox1);
            jButton1.setText("Enter");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    EnterActionPerformed(evt);
            getContentPane().add(jButton1);
            jButton2.setText("Cancel");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    CancelActionPerformed(evt);
            getContentPane().add(jButton2);
            pack();
        private void LocaleActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("LocaleChange");
        private void CancelActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Cancelled");
        private void EnterActionPerformed(java.awt.event.ActionEvent evt) {
            setUserAction("Submitted");
        /** Exit the Application */
        private void exitForm(java.awt.event.WindowEvent evt) {
            System.exit(0);
         * @param args the command line arguments
        public static void main(String args[]) {
            new LoginGUIdemo().show();
        // Variables declaration - do not modify
        private javax.swing.JTextField jTextField2;
        private javax.swing.JTextField jTextField1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton1;
        // End of variables declaration

  • SQL Query not working in action performed event of combobox in swing

    hi all..
    i have to retreive from the database based on the item selected in the comboBox.......
    when the program runs for the first time the data of defaultselected item is being displayed...
    but when another item is selected the data is not retrieved from the database....
    i am able to print the selected item but unable to query the database for the selected item
       private void resultsItemStateChanged(java.awt.event.ItemEvent evt) {                                        
    // TODO add your handling code here:
            try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                conn = DriverManager.getConnection("jdbc:odbc:aa");
                System.out.println("you have selected me : --- >" + results.getSelectedItem().toString());
                sql="SELECT * FROM " + name + " WHERE term = ? ";
                srch2 = conn.prepareStatement(sql);
                srch2.setString(1,results.getSelectedItem().toString());
                rs2 = srch2.executeQuery();
                rs2.next();
                tarea2.setText("\n Definition:"+rs1.getString(3));
                tarea3.setText("\n Description:"+rs1.getString(4));
                tarea4.setText("\n Related Terms:"+rs1.getString(5));
                tarea5.setText("\n Hyperlinks : "+rs1.getString(6));
                tarea6.setText("\n References:"+rs1.getString(7));
                conn.close();
                rs2.close();
            } catch(Exception e){}
    }    please help me to query the database for the selected item
    Thanks in advance...

    hi all..
    i have to retreive from the database based on the item selected in the comboBox.......
    when the program runs for the first time the data of defaultselected item is being displayed...
    but when another item is selected the data is not retrieved from the database....
    i am able to print the selected item but unable to query the database for the selected item
    private void resultsItemStateChanged(java.awt.event.ItemEvent evt) {                                        
    // TODO add your handling code here:
          ResultSet rs2=null;
           PreparedStatement srch2 = null;
            Connection conn1= null;
            Statement us = null;
            try{
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                conn1 = DriverManager.getConnection("jdbc:odbc:aa");
               System.out.println("you have selected me : --- >" + results.getSelectedItem().toString());
                 sql="SELECT * FROM " + name + " WHERE term = ?";
                srch2 = conn.prepareStatement(sql);
                srch2.setString(1,results.getSelectedItem().toString());
                rs2 = srch2.executeQuery();
               rs2.next();
                tarea2.setText("\n"+rs1.getString(3));
                tarea3.setText("\n "+rs1.getString(4));
                tarea4.setText("\n"+rs1.getString(5));
                tarea6.setText("\n"+rs1.getString(6));
                tarea5.setText("\n"+rs1.getString(7));
              rs2.close();
              conn1.close();
            } catch(Exception e){
                System.out.println(e);
        After printing for the first time it is showing like this ...
    java.sql.SQLException: ResultSet is closed
    at sun.jdbc.odbc.JdbcOdbcResultSet.checkOpen(JdbcOdbcResultSet.java:6646)
    at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:257)
    at more_info.resultsActionPerformed(more_info.java:301)
    at more_info.access$100(more_info.java:25)
    at more_info$2.actionPerformed(more_info.java:121)
    at javax.swing.JComboBox.fireActionEvent(JComboBox.java:1242)
    at javax.swing.JComboBox.setSelectedItem(JComboBox.java:569)
    at javax.swing.JComboBox.setSelectedIndex(JComboBox.java:605)
    at javax.swing.plaf.basic.BasicComboPopup$Handler.mouseReleased(BasicComboPopup.java:814)
    at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:273)
    at java.awt.Component.processMouseEvent(Component.java:6038)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
    at javax.swing.plaf.basic.BasicComboPopup$1.processMouseEvent(BasicComboPopup.java:480)
    at java.awt.Component.processEvent(Component.java:5803)
    at java.awt.Container.processEvent(Container.java:2058)
    at java.awt.Component.dispatchEventImpl(Component.java:4410)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
    at java.awt.Container.dispatchEventImpl(Container.java:2102)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

  • JComboBox    How to get input from JComboBox

    Hi all.
    I have a JComboBox called combobox.
    User can choose one string out of 5 using this JComboBox.
    Whenever the user press a button, I'd like to get an input through this combobox using actionListener.
    How can I get input through JComboBox?
    combobox.getValue() ???
    I appreciate your help !

    http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComboBox.html
    Object getSelectedItem()

  • JComboBox is not visible on JPanel

    I have a class that extends JPanel. Within this class I have added several different components; JLabels, JTextFields, JButtons and a JComboBox.
    All of the added components are visible and working except for the JComboBox. I can see the white background of the box and the popup and its list when I click on the area where the JComboBox is located, but I cannot see the selected text in the box. This seems strange since all the other components surrounding the JComboBox display correctly.
    The background is set to white and the foreground is set to black. It has three options in the popup which are displayed using the foreground color, as it should. When I select an option from the popup, it seems to be working because the next time I display the popup, that selection is highlighted. But the selected text never shows in the box.
    If I create a JComboBox in a JPanel, not an extended class, everything seems to work correctly. I can select from the popup and the selection appears in the box.
    Could you please give me some suggestions as to how to make the selected text in the JComboBox visible?
    Thanks
    Bob

    My layout manager is set to null. I don't think that there is anything obscuring it because the backgroud is visible. The only thing that I can't see it the selected text and the combo box down arrow. I am using VisualCafe to generate this code.
    The extended class is loaded from the following class:
    public class TheSchedule extends javax.swing.JFrame
    using the following code:
         void JButtonGenTimeUnits_actionPerformed(java.awt.event.ActionEvent event)
              JPanelMainPanel.add(new TimeUnitDefinition((Frame)this));
              JPanelMainPanel.repaint();
    The actual code of the TimeUnitDefinition is as follows:
    package com.klawuhn.schedule;
    import javax.swing.*;
    import java.beans.*;
    import java.awt.*;
    import com.symantec.itools.javax.swing.models.StringComboBoxModel;
    import symantec.itools.awt.util.Calendar;
    import com.symantec.itools.javax.swing.borders.LineBorder;
    public class TimeUnitDefinition extends javax.swing.JPanel {
    private Frame parentFrame = null;
         public TimeUnitDefinition(Frame parentFrame)
         this.parentFrame = parentFrame; // Needed when displaying the calendars
              //{{INIT_CONTROLS
              setAlignmentY(1.0F);
              setAlignmentX(1.0F);
              setOpaque(false);
              setLayout(null);
              setSize(457,283);
              JLabelStartDate.setText("Start Date:");
              add(JLabelStartDate);
              JLabelStartDate.setBounds(12,12,156,24);
              JTextFieldStartDate.setDisabledTextColor(java.awt.Color.white);
              JTextFieldStartDate.setToolTipText("This is the date to start generating time units.");
              JTextFieldStartDate.setEditable(false);
              add(JTextFieldStartDate);
              JTextFieldStartDate.setBackground(java.awt.Color.white);
              JTextFieldStartDate.setBounds(168,12,216,24);
              JButtonCalendar1.setText("-");
              JButtonCalendar1.setActionCommand("-");
              add(JButtonCalendar1);
              JButtonCalendar1.setBounds(384,12,24,24);
              JLabelEndDate.setText("End Date:");
              add(JLabelEndDate);
              JLabelEndDate.setBackground(java.awt.Color.cyan);
              JLabelEndDate.setBounds(12,48,156,24);
              JTextFieldEndDate.setDisabledTextColor(java.awt.Color.white);
              JTextFieldEndDate.setToolTipText("This is the date to start generating time units.");
              JTextFieldEndDate.setEditable(false);
              add(JTextFieldEndDate);
              JTextFieldEndDate.setBackground(java.awt.Color.white);
              JTextFieldEndDate.setBounds(168,48,216,24);
              JButtonCalendar2.setText("-");
              JButtonCalendar2.setActionCommand("-");
              add(JButtonCalendar2);
              JButtonCalendar2.setBounds(384,48,24,24);
              JLabelStartTime.setText("Start Time:");
              add(JLabelStartTime);
              JLabelStartTime.setBounds(12,84,156,24);
              JTextFieldStartTime.setToolTipText("This is the time of day to start generating time units.");
              add(JTextFieldStartTime);
              JTextFieldStartTime.setBounds(168,84,240,24);
              JLabelEndTime.setText("End Time:");
              add(JLabelEndTime);
              JLabelEndTime.setBounds(12,120,156,24);
              JTextFieldEndTime.setToolTipText("This is the time of day to end generating time units.");
              add(JTextFieldEndTime);
              JTextFieldEndTime.setBounds(168,120,240,24);
              JLabelUnitOfMeasure.setText("Unit of Measure:");
              add(JLabelUnitOfMeasure);
              JLabelUnitOfMeasure.setBounds(12,156,156,24);
              JComboBoxUnitOfMeasure.setModel(stringComboBoxModel1);
              JComboBoxUnitOfMeasure.setToolTipText("This is the unit of measure used when generating the time units.");
              add(JComboBoxUnitOfMeasure);
              JComboBoxUnitOfMeasure.setBackground(java.awt.Color.white);
              JComboBoxUnitOfMeasure.setForeground(java.awt.Color.black);
              JComboBoxUnitOfMeasure.setBounds(168,156,240,24);
              JLabelBlockSize.setText("Block Size:");
              add(JLabelBlockSize);
              JLabelBlockSize.setBounds(12,192,156,24);
              JTextFieldBlockSize.setText("45");
              JTextFieldBlockSize.setToolTipText("This is the size of the time unit in Unit of Measures.");
              add(JTextFieldBlockSize);
              JTextFieldBlockSize.setBounds(168,192,240,24);
              JButtonSubmit.setText("Submit");
              JButtonSubmit.setActionCommand("Submit");
              JButtonSubmit.setToolTipText("This button will generate the time units.");
              add(JButtonSubmit);
              JButtonSubmit.setBounds(36,228,108,40);
              JButtonCancel.setText("Cancel");
              JButtonCancel.setActionCommand("Cancel");
              JButtonCancel.setToolTipText("This button will discard any changes.");
              add(JButtonCancel);
              JButtonCancel.setBounds(288,228,108,40);
                   String[] tempString = new String[3];
                   tempString[0] = "Days";
                   tempString[1] = "Hours";
                   tempString[2] = "Minutes";
                   stringComboBoxModel1.setItems(tempString);
              //$$ stringComboBoxModel1.move(0,288);
              JComboBoxUnitOfMeasure.setSelectedIndex(2);
              //{{REGISTER_LISTENERS
              SymAction lSymAction = new SymAction();
              JButtonSubmit.addActionListener(lSymAction);
              JButtonCalendar1.addActionListener(lSymAction);
              JButtonCalendar2.addActionListener(lSymAction);
         //{{DECLARE_CONTROLS
         javax.swing.JLabel JLabelStartDate = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldStartDate = new javax.swing.JTextField();
         javax.swing.JButton JButtonCalendar1 = new javax.swing.JButton();
         javax.swing.JLabel JLabelEndDate = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldEndDate = new javax.swing.JTextField();
         javax.swing.JButton JButtonCalendar2 = new javax.swing.JButton();
         javax.swing.JLabel JLabelStartTime = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldStartTime = new javax.swing.JTextField();
         javax.swing.JLabel JLabelEndTime = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldEndTime = new javax.swing.JTextField();
         javax.swing.JLabel JLabelUnitOfMeasure = new javax.swing.JLabel();
         javax.swing.JComboBox JComboBoxUnitOfMeasure = new javax.swing.JComboBox();
         javax.swing.JLabel JLabelBlockSize = new javax.swing.JLabel();
         javax.swing.JTextField JTextFieldBlockSize = new javax.swing.JTextField();
         javax.swing.JButton JButtonSubmit = new javax.swing.JButton();
         javax.swing.JButton JButtonCancel = new javax.swing.JButton();
         com.symantec.itools.javax.swing.models.StringComboBoxModel stringComboBoxModel1 = new com.symantec.itools.javax.swing.models.StringComboBoxModel();
         class SymAction implements java.awt.event.ActionListener
              public void actionPerformed(java.awt.event.ActionEvent event)
                   Object object = event.getSource();
                   if (object == JButtonSubmit)
                        JButtonSubmit_actionPerformed(event);
                   else if (object == JButtonCalendar1)
                        JButtonCalendar1_actionPerformed(event);
                   else if (object == JButtonCalendar2)
                        JButtonCalendar2_actionPerformed(event);
         void JButtonSubmit_actionPerformed(java.awt.event.ActionEvent event)
              System.out.println("See Submit button");
              TimeUnitCreate timeUnitCreate = new TimeUnitCreate(
              JTextFieldStartDate.getText(),
              JTextFieldEndDate.getText(),
              JTextFieldStartTime.getText(),
              JTextFieldEndTime.getText(),
              (String)JComboBoxUnitOfMeasure.getSelectedItem(),
              JTextFieldBlockSize.getText()
              timeUnitCreate.createTimeUnits();
              this.setVisible(false);
    System.out.println("Done creating Time Units.");
    // (new TimeUnitDefinition()).setVisible(true);
         void JButtonCalendar1_actionPerformed(java.awt.event.ActionEvent event)
         CalendarDialog calendarDialog = new CalendarDialog(parentFrame,"Date",true);
         calendarDialog.show();
         JTextFieldStartDate.setText(calendarDialog.getSelectedDate());
         void JButtonCalendar2_actionPerformed(java.awt.event.ActionEvent event)
         CalendarDialog calendarDialog = new CalendarDialog(parentFrame,"Date",true);
         calendarDialog.show();
         JTextFieldEndDate.setText(calendarDialog.getSelectedDate());
    }

Maybe you are looking for

  • How can I delete all photographs in stream of my iPhone 4 without loosing them on my mac?

    How can I delete all photographs in stream of my iPhone 4 without loosing them on my mac? Because I have too much photographs in my phone's memory and I need to know a simple methode to get them off.

  • Connecting 6248up to a dcx

    what are the steps to connect 2 FI 6248UP to a brocade dcx switch? I have a total of 6 FC Ports shown but they are configured as uplink ports. Should they be FC storage ports instead? I am not sure I need all 6 links to the dcx switch, so maybe 4 on

  • Hotsynch Abnormally Terminates when changing default settings - Treo 700p

    I recently purchased a Sprint Treo 700p. I installed Hotsync from the CD and successfully synchronized with my Outlook 2003 (front end to Exchange 2003) Contact and Calendar folders. After several days, I noticed that it no longer synchronized those

  • IPhoto shuts down my iMac

    When I try to work in iPhoto it shuts down my iMac. I had a lot of problems with iPhoto in December and worked with an Apple Advisor then to rebuild my library and every thing was fine for a while... then the shut downs started happening. Randomly at

  • Shortening quicktime file play length

    i have a graphic file that was done in after effects by someone and delivered to me in a .mov file. The file is 14 seconds and i need to reduce it to 5 seconds. The file has motion (credit requirements for a finance company appearing across the scree