Java - Allow using backspace in an editable JCombo

2019-09-17 20:32发布

I am using Substance L&F and I have set a JComboBox to editable so that i can select the value that i want from its popup, or type a new value in its Editor.

Typing a new value works fine, but if i want to delete a miss-typed letter from the Combo editor, and i click Backspace to do that it selects the letters in the editor instead of erasing them. Here is a screenshot :

enter image description here

I want the Combo editor to work like a JTextField when typing keyboard letters or Backspace or Delete in it, so is there a way to do that ? Or what is causing this?

2条回答
Root(大扎)
2楼-- · 2019-09-17 21:22

See below for the importance of an SSCCE not everything that goes wrong is a bug, most of the times it something wrong in your actual code, which without an SSCCE we are non the wiser.

Seems to work fine for me:

On start up:

enter image description here

After selecting JComboBox and pressing Backspace:

enter image description here

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Test {

    public Test() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);


                JComboBox jc = new JComboBox(new String[]{"Hello", "Bye", "World", "Cruel"});
                jc.setEditable(true);
                frame.add(jc);

                frame.pack();
                frame.setVisible(true);

            }
        });
    }

    public static void main(String[] args) {
        new Test();
    }
}

UPDATE

As per your comment:

I did not think it would work fine ! ... It is a problem in Substance; the L&F i am using.

See below for details on the Bug:

Substance: Editable JComboBox does not support backspace key

As stated:

This behavior is by design. This is a "feel" part of Substance that adds auto-completion on editable comboboxes.

Alternatively see my answer here for more L&Fs and/or a way to make your own

UPDATE 2:

Thanks to @Brad (for deciphering the bug log I linked from Substance :P) to fix this simply do:

UIManager.put( LafWidget.COMBO_BOX_NO_AUTOCOMPLETION, Boolean.TRUE ); 
查看更多
男人必须洒脱
3楼-- · 2019-09-17 21:23
UIManager.put(LafWidget.COMBO_BOX_NO_AUTOCOMPLETION, Boolean.TRUE);

This work for me!

查看更多
登录 后发表回答