user3152465
user3152465

Reputation: 1

JOptionPane inputDialog method doesn`t show horizontal scroll bar instead stretch the width of dialog with the largest data in the list

import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 * @author hxd1
 *
 */
public class demoDialog
{
  public static final String[] pizzas = { "Cheeseassssssssssss123333331231231232111111111111111111111111111111111111111111111111ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss232222222222222222222222222222222222222222222222222222222222222222222222222222222222224", "Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie","Pepperoni", "Sausage", "Veggie" };

  public static void main(String[] args)
  {
    JFrame frame = new JFrame();
    JOptionPane.showInputDialog(frame, "What's your name?","Title",     JOptionPane.PLAIN_MESSAGE, null, pizzas, null);
    System.exit(0);
  }
}

Above code upon execution shows dialog with no horizontal scroll instead frame stretching w.r.t largest data.

Is there anything we could do to solve this?

Upvotes: 0

Views: 513

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347244

Is there anything we could do to solve this

  • Use a JComboBox as the message parameter. The problem with this is, JComboBox will size to it's widest element...
  • Use a JList configured to a single selection. The problem with this is, it's a little confusing from a selection point of view
  • Use a JTable with a JRadioButton in one column. Not much better then the JList, but it provides a slightly better visual cue

List of pizzas

JList list = new JList(pizzas) {
    @Override
    public Dimension getPreferredScrollableViewportSize() {
        Dimension dim = super.getPreferredScrollableViewportSize();
        dim.width = 25;
        return dim;
    }
};
list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

switch (JOptionPane.showOptionDialog(null, new JScrollPane(list), "Pizza", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, null, 0)) {
    case JOptionPane.OK_OPTION:
        // Get the selected index/item
        break;
}

Don't forget, you could wrap the JList in a JPanel and other components, like a JLabel as prompt

Upvotes: 5

Related Questions