2012-04-01 145 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

相关问题