2017-03-22 39 views
2

我知道如何用「yes」或「no」按鈕創建簡單的對話框。如何用兩個問題創建對話框

Object[] options = {"yes", "no"}; 

int selection = JOptionPane.showOptionDialog(
    gameView, 
    "choose one", 
    "Message", 
    JOptionPane.YES_NO_OPTION, 
    JOptionPane.QUESTION_MESSAGE, 
    null, 
    options, 
    options[0] 
); 

但是現在我想創建一個包含兩個問題的對話框。我怎麼做?

我想對話框看起來像這樣:

Dialog

回答

0

你真的可以插入任何你想要的內容轉換成一個對話框。您正在將一個字符串(「選擇其中一項」),但你實際上可以通過在控制整個面板:

import javax.swing.*; 

public class Main { 
    public static void main(String[] args) { 
     // Create a button group containing blue and red, with blue selected 
     final ButtonGroup color = new ButtonGroup(); 
     final JRadioButton blue = new JRadioButton("Blue"); 
     final JRadioButton red = new JRadioButton("Red"); 
     color.add(blue); 
     blue.setSelected(true); 
     color.add(red); 

     // Create a button group containing triangle and square, with triangle selected 
     final ButtonGroup shape = new ButtonGroup(); 
     final JRadioButton triangle = new JRadioButton("Triangle"); 
     final JRadioButton square = new JRadioButton("Square"); 
     shape.add(triangle); 
     triangle.setSelected(true); 
     shape.add(square); 

     // Create a panel and add labels and the radio buttons 
     final JPanel panel = new JPanel(); 
     panel.add(new JLabel("Choose a color:")); 
     panel.add(blue); 
     panel.add(red); 
     panel.add(new JLabel("Choose a shape:")); 
     panel.add(triangle); 
     panel.add(square); 

     // Show the dialog 
     JOptionPane.showMessageDialog(
      null /*gameView*/, panel, "Message", 
      JOptionPane.QUESTION_MESSAGE 
     ); 

     // Print the selection 
     if (blue.isSelected()) { 
      System.out.println("Blue was selected"); 
     } 
     else { 
      System.out.println("Red was selected"); 
     } 

     if (triangle.isSelected()) { 
      System.out.println("Triangle was selected"); 
     } 
     else { 
      System.out.println("Square was selected"); 
     } 
    } 
} 

這就產生了一個彈出式看起來像這樣:

Dialog

它看起來不像你的形象,但這不屬於你的問題範圍。如果你想改變它,你需要玩弄不同類型的佈局。 See this question初學者。

相關問題