2012-04-01 51 views
1

我試圖把JSpinner的一個的JOptionPane如下,的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的填充對話框的寬度不管我設定的尺寸。我也嘗試過使用setPreferredSize()。我該如何解決?

回答

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()); 
    } 
+2

是啊,其實我之前切換到showConfirmDialog的方法你甚至發佈了你的答案。但是你的JPanel方法工作的很好,所以我會盡快接受你的答案:) – gsingh2011 2012-04-01 05:20:16

+0

'JPanel panel = new JPanel();'Huh。非常高雅 - 左對齊的「FlowLayout」。簡短而甜蜜。我總是在接受組件的默認佈局時感到緊張,回想起Sun決定將框架的默認值從「FlowLayout」更改爲「BorderLayout」大約1.5(?)。 – 2012-04-01 06:24:55

+0

+1有關此問題中的JSpinner佈局的更多信息(http://stackoverflow.com/q/7374659/230513)。 – trashgod 2012-04-01 14:17:38

相關問題