2013-10-16 112 views
0

所以我有一個程序,當我點擊一個按鈕時啓動一個輸入對話框。我需要幫助的是,一旦我從輸入對話框收集信息並且它們消失後,我按下Enter鍵並重新出現輸入對話框。爲什麼?輸入對話框[需要的信息]

另外,我怎樣才能讓它如此,如果輸入對話框留空,它會出現一個錯誤,然後重複,直到它不是空的?


public static String fn; 
public static String sn; 

public void actionPerformed (ActionEvent e){ 
    fn = JOptionPane.showInputDialog("What is your first name?"); 
    sn = JOptionPane.showInputDialog("What is your second name"); 

    //JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE); 
    text.setText("Welcome " + fn + " " + sn + "."); 
    b.setVisible(false); 
    text.setVisible(true); 
    text.setBounds(140,0,220,20); 
    text.setHorizontalAlignment(JLabel.CENTER); 
    text.setEditable(false); 
    text.setBackground(Color.YELLOW); 
    writeToFile(); 
} 

public BingoHelper(){ 
    super("BINGO"); 
    add(text); 
    text.setVisible(false); 
    add(b); 
    this.add(pnlButton); 
    pnlButton.setBackground(Color.BLUE); 
    //pnlButton.add(b);+ 
    b.setVisible(true); 
    b.setBounds(145,145,145,20); 
    //b.setPreferredSize(new Dimension(150,40)); 
    b.addActionListener(this); 
    b.setBackground(Color.GREEN); 
    rootPane.setDefaultButton(b); 
} 
+1

無關:不做組件的任何手動尺寸/定位,永遠 - 這就是佈局管理的全部責任。 – kleopatra

+0

當你收集輸入,並且輸入對話消失時,按鈕獲得焦點? – Cold

回答

2

當你調用rootPane.setDefaultButton你所指定的是回車鍵啓動按鈕。

要防止在輸入不可接受時關閉JOptionPane,請創建一個實際的JOptionPane實例,然後創建您自己的按鈕並將其指定爲選項。按鈕的動作或ActionListener的必須調用的JOptionPane的setValue方法:

final JOptionPane optionPane = new JOptionPane("What is your first name?", 
    JOptionPane.QUESTION_MESSAGE); 
optionPane.setWantsInput(true); 

Action accept = new AbstractAction("OK") { 
    private static final long serialVersionUID = 1; 
    public void actionPerformed(ActionEvent event) { 
     Object value = optionPane.getInputValue(); 
     if (value != null && !value.toString().isEmpty()) { 
      // This dismisses the JOptionPane dialog. 
      optionPane.setValue(JOptionPane.OK_OPTION); 
     } 
    } 
}; 

Object acceptButton = new JButton(accept); 
optionPane.setOptions(new Object[] { acceptButton, "Cancel" }); 
optionPane.setInitialValue(acceptButton); 

// Waits until dialog is dismissed. 
optionPane.createDialog(null, "First Name").setVisible(true); 

if (!Integer.valueOf(JOptionPane.OK_OPTION).equals(optionPane.getValue())) { 
    // User canceled dialog. 
    return; 
} 

String fn = optionPane.getInputValue().toString();