How to open JCombobox in a addPropertyChangeListener

111 views Asked by At

In a JDateChooser, we have added a addPropertyChangeListener that detects if a date is chosen. If it is chosen, we want to open a JCombobox. The (date) string is detected when we select, but we can't open the JComboBox.

Here is the code:

dateChooserCal.getDateEditor().addPropertyChangeListener(new PropertyChangeListener() {
    public void propertyChange(PropertyChangeEvent evt) 
    {
        date = dateChooserCal.getDate();

        if ("date".equals(evt.getPropertyName())) 
        {   
            dates = evt.getNewValue();
            dateString = String.format("%1$td-%1$tm-%1$tY", date);  
            if (dateString != null) 
            {
                System.out.print(dateString);
                chooseTimeBox = new JComboBox(controllerApp.getTime());
                chooseTimeBox.setBounds(215, 261, 282, 22);
                add(chooseTimeBox);
                chooseTimeBox.setVisible(true);
            }

        }

    }       

});
1

There are 1 answers

3
MadProgrammer On BEST ANSWER

Well the fact that combo box isn't contained within any displayable element is probably the primary cause of your issue...

// You create a new instance
chooseTimeBox = new JComboBox(controllerApp.getTime());
// You  position and size, more on this later...
chooseTimeBox.setBounds(215, 261, 282, 22);
// You make it visible...but it's visible by default...
chooseTimeBox.setVisible(true);
// But you never add it to anything...

Because you seem to be using a instance field, I might guess that you have already created a previous instance and have already added it, in that case, you should be updating that instances model...

Avoid using null layouts, pixel perfect layouts are an illusion within modern ui design. There are too many factors which affect the individual size of components, none of which you can control. Swing was designed to work with layout managers at the core, discarding these will lead to no end of issues and problems that you will spend more and more time trying to rectify

Have a look at Why is it frowned upon to use a null layout in SWING? and Laying Out Components Within a Container for more details...