【问题标题】:JSpinner takes up entire width in JOptionPaneJSpinner 在 JOptionPane 中占据整个宽度
【发布时间】:2012-04-15 06:20:48
【问题描述】:

我正在尝试将 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() 。我该如何解决这个问题?

【问题讨论】:

    标签: java swing width joptionpane jspinner


    【解决方案1】:

    为什么不直接把它放在 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());
      }
    

    【讨论】:

    • 是的,我实际上在您发布答案之前就切换到了 showConfirmDialog 方法。但是您的 JPanel 方法效果很好,所以只要允许我接受您的回答,我就会接受您的回答:)
    • JPanel panel = new JPanel(); 呵呵。非常优雅 - 左对齐 FlowLayout。短而甜。不过,我总是对接受组件的默认布局感到紧张,回想起 Sun 决定将框架的默认布局从 FlowLayout 更改为 BorderLayout 大约 1.5(?)。
    • +1 有关JSpinner 布局的更多信息,请参见Q&A
    猜你喜欢
    • 2021-01-30
    • 1970-01-01
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-07
    相关资源
    最近更新 更多