I want to show only the arrow in JComboBox

71 Views Asked by At

I have a JComboBox, but I want it to show only dropdown arrow, that is, without any space on left for the JComboBox element. But when I click the arrow, I want the list to go naturally, without it being empty or something.

This is what I'm dealing with:

enter image description here

I want it to look something like this (also list elements in the center, if that's possible):

enter image description here

Thanks :).

1

There are 1 best solutions below

0
DevilsHnd - 退した On

You could do something like this (read comments in code):

private void showOnlyComboBoxButton(javax.swing.JComboBox combo) {
    // Make sure ComboBox is Editable
    combo.setEditable(true);  
    
    // Get a list of ComboBox Components:
    java.awt.Component[] comp = combo.getComponents();
    
    /* Declare a javax.swing.JComponent object. The ComboBox
       TextField will be held there.        */
    javax.swing.JComponent jc;
    
    // Iterate through the ComboBox components and find the TextField
    for (java.awt.Component c : comp) {
        if (c instanceof javax.swing.JComponent) {
            jc = ((javax.swing.JComponent) c);
            // Is this the TextField?
            if (jc.getName().equals("ComboBox.textField")) {
                // Yes...set it's visible property to boolean false:
                jc.setVisible(false);
                // Break out of loop;
                break;  
            }
        }
    }
    /* Optional - Set the ComboBox drop-down list to 
       the right side of the Arrow Button:        */
    combo.setComponentOrientation(java.awt.ComponentOrientation.RIGHT_TO_LEFT);
    
    // Repaint:
    combo.repaint();
}