我知道如何创建一个简单的对话框"是"或"不"的按钮。
Object[] options = {"yes", "no"};
int selection = JOptionPane.showOptionDialog(
gameView,
"choose one",
"Message",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE,
null,
options,
options[0]
);
但现在我想创建一个包含两个问题的对话框。我该怎么做?
我希望对话框看起来像这样:
答案 0 :(得分: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");
}
}
}
这会创建一个如下所示的弹出窗口:
它看起来与您的图像完全不同,但不属于您的问题范围。如果你想改变它,你需要使用不同类型的布局。 See this question为初学者。