xoX Zeus Xox
xoX Zeus Xox

Reputation: 195

JComboBox to display multiple lines of text

I'm currently writing a small tool for sending sql queries to a database and recieving the according data.

Now to my problem: I want to allow the user to enter a new search query or select from a "latest" list, where the last few queries are saved. For that, I planned on using an editable JComboBox, but I'm having trouble diplaying multiple lines of text in the box itself.

The reason I want to do that, is because sql queries can get quite long and since I want make the box editable and at the same time keep the frame clean.

I've found ways to display multiple lines in the dropdown menu, but nothing for the box itself.

Thank you in advance and please forgive me if I overlooked something simple ;)

Greetings Zeus

Upvotes: 1

Views: 1533

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347332

Extended editing functionality is supplied by the ComboBoxEditor, this allows you to define the actual component which is used as the combobox's editor

Based on your requirements, you're going to need (at the very least) a JTextArea, to provide (optionally) word wrapping and multiple lines

A rough and ready example might look something like this...

public class TextAreaComboBoxEditor implements ComboBoxEditor {

    private JTextArea ta = new JTextArea(4, 20);
    private JScrollPane sp = new JScrollPane(ta);

    public TextAreaComboBoxEditor() {
        ta.setWrapStyleWord(true);
        ta.setLineWrap(true);
    }

    @Override
    public Component getEditorComponent() {
        return sp;
    }

    @Override
    public void setItem(Object anObject) {
        if (anObject instanceof String) {
            ta.setText((String) anObject);
        } else {
            ta.setText(null);
        }
    }

    @Override
    public Object getItem() {
        return ta.getText();
    }

    @Override
    public void selectAll() {
        ta.selectAll();
    }

    @Override
    public void addActionListener(ActionListener l) {
    }

    @Override
    public void removeActionListener(ActionListener l) {
    }

}

This doesn't support ActionListener, as JTextArea uses the Enter key for it's own purposes. If you wanted to, you could use the key bindings API to add your own Action that can trigger the ActionListeners, for that, you'd need to supply a List or other means for managing them so you can call them back

Upvotes: 3

Related Questions