JSpinner在JOptionPane中占用整个宽度

时间:2012-04-01 05:07:44

标签: java swing width joptionpane jspinner

我正在尝试将JSpinner放在JOptionPane中,如下所示,

        SpinnerModel saModel = new SpinnerNumberModel(11, 1, 36, 1);
        JSpinner saSpinner = new JSpinner(saModel);
        Dimension d = saSpinner.getSize();
        d.width = 20;
        saSpinner.setSize(d);

        Object[] message = { "Choose the key number for sa.", saSpinner };

        JOptionPane optionPane = new JOptionPane(message,
                JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
        JDialog dialog = optionPane.createDialog(frame, "Change Sa Key");
        dialog.setVisible(true);

这样可行,但唯一的问题是JSpinner会填充Dialog的宽度,而不管我设置的大小。我也尝试过使用setPreferredSize()。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:5)

为什么不把它放在JPanel中?

  SpinnerModel saModel = new SpinnerNumberModel(11, 1, 36, 1);
  JSpinner saSpinner = new JSpinner(saModel);
  Dimension d = saSpinner.getSize();
  d.width = 20;
  saSpinner.setSize(d);

  // Object[] message = { "Choose the key number for sa.", saSpinner };

  JPanel panel = new JPanel();
  panel.add(new JLabel("Choose the key number for sa:"));
  panel.add(saSpinner);

  JOptionPane optionPane = new JOptionPane(panel,
          JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION);
  JDialog dialog = optionPane.createDialog(frame, "Change Sa Key");
  dialog.setVisible(true);

虽然我自己,但我不知道我会为此创建一个JDialog,而只是显示JOptionPane.showConfirmDialog(...)方法:

  SpinnerModel saModel = new SpinnerNumberModel(11, 1, 36, 1);
  JSpinner saSpinner = new JSpinner(saModel);
  Dimension d = saSpinner.getSize();
  d.width = 20;
  saSpinner.setSize(d);

  JPanel panel = new JPanel();
  panel.add(new JLabel("Choose the key number for sa:"));
  panel.add(saSpinner);

  int selection = JOptionPane.showConfirmDialog(frame, panel, "Change Sa Key", 
          JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);
  if (selection == JOptionPane.OK_OPTION) {
     System.out.println("Sa Key is: " + saModel.getValue().toString());
  }