views:

39

answers:

3

Is it possible to create a dialog where the user can select values from a list, but also can edit the text? (Something like a dialog with an editable JComboBox.)

A: 

JDialogs are usually used to display notifications to the user. I think that if you want such behaviour you will have to create a simple JFrame that does what you need.

npinti
A: 

Not sure what you mean by "edit the text after selection".

However, you can easily create a simple dialog using a JOptionPane. You can add a JPanel to the option pane. Check out Dialog Focus for more information.

camickr
I mean you can select a value from a drop-down list, but also, you can edit it
János Harsányi
A: 
import java.awt.*;
import javax.swing.*;
import javax.swing.event.*;

class ShowBothInputs {

    public static void main(String[] args) {

        Runnable r = new Runnable() {

            public void run() {
                String[] items = {
                    "Apple",
                    "Banana",
                    "Grape",
                    "Cherry"
                };

                // what was requested
                EditableListPanel elp = new EditableListPanel(items);
                JOptionPane.showMessageDialog(null, elp);
                System.out.println( "EditableListPanel value: " + elp.getValue() );

                // probably what this UI actually needs
                JComboBox jcb = new JComboBox(items);
                jcb.setEditable(true);
                JOptionPane.showMessageDialog(null, jcb);
                System.out.println( "JComboBox value: " + jcb.getSelectedItem() );
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

class EditableListPanel extends JPanel {

    private JTextField value;

    EditableListPanel(String[] items) {
        super( new BorderLayout(5,5) );

        final JList list = new JList( items );
        list.addListSelectionListener( new ListSelectionListener(){
                public void valueChanged(ListSelectionEvent lse) {
                    value.setText( (String)list.getSelectedValue() );
                }
            } );
        add( list, BorderLayout.CENTER );

        value = new JTextField("", 20);
        add( value, BorderLayout.NORTH );
    }

    public String getValue() {
        return value.getText();
    }
}
Andrew Thompson
The 2nd dialog is exactly what I was looking for.
János Harsányi