2016-06-10 29 views
-2

我在弄清楚如何爲選項窗格中使用的選項指定名稱/標題,以便我可以在if語句中使用它們。這裏是我到目前爲止的代碼:如何在if語句中使用選項窗格中的信息

int i = 0; 
while(i<1){ 
     JFrame frame = new JFrame(); 
      String[] options = new String[2]; 
      options[0] = new String("Peat"); 
      options[1] = new String("Repeat"); 
      JOptionPane.showOptionDialog(frame.getContentPane(),"Peat and Repeat were walking on a bridge\nPeat fell off, " 
        + "who was left?","", 0,JOptionPane.INFORMATION_MESSAGE,null,options,null); 
    } 

你會推薦我下一步做完這個「笑話」?

回答

1

我想你的問題是什麼意思是你如何確定用戶選擇了什麼選項? JOptionPane.showOptionDialog返回所選選項的索引。所以你可以這樣做:

import javax.swing.*; 

public class Example { 

    public static void main(String[] args) { 

     String[] options = {"Peat", "Repeat"}; 

     int selectedOption = JOptionPane.showOptionDialog(null,"Peat and Repeat were walking on a bridge\nPeat fell off, who was left?","", JOptionPane.DEFAULT_OPTION,JOptionPane.INFORMATION_MESSAGE,null,options,null); 

     if(selectedOption == 0) System.out.println("Peat selected"); 
     else System.out.println("Repeat selected"); 
    } 
} 

當用戶選擇「泥炭」時,它會打印「泥炭選定」。

當他們選擇「重複」時,它將打印「重複選擇」