如果您使用的阵列是,让我们说长度为15,并且您希望一次显示它们,它会在一个非常长的显示框中并排显示:
String[] options = {"Option 1","Option 2","Option 3","Option 4",
"Option 5","Option 6","Option 7","Option 8","Option 9",
"Option 10","Option 11","Option 12","Option 13","Option 14",
"Option 15"};
int displayoptions = JOptionPane.showOptionDialog (null, "select one", "Title",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options [0]);
有没有办法显示它以便它有一个Flow Layout?
答案 0 :(得分:3)
对于15种选择,我更喜欢这样做:
import java.awt.*;
import javax.swing.*;
public class ManyOptions {
ManyOptions() {
initUI();
}
public void initUI() {
String[] options = {"Option 1", "Option 2", "Option 3", "Option 4",
"Option 5", "Option 6", "Option 7", "Option 8", "Option 9",
"Option 10", "Option 11", "Option 12", "Option 13", "Option 14",
"Option 15"};
JComboBox combo = new JComboBox(options);
int result = JOptionPane.showConfirmDialog(
null,
combo,
"Select One",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
System.out.println("Selected Index: " + combo.getSelectedIndex());
} else {
System.out.println("choice cancelled..");
}
// old way, for comparison..
int displayoptions = JOptionPane.showOptionDialog(
null,
"select one",
"Title",
JOptionPane.DEFAULT_OPTION,
JOptionPane.WARNING_MESSAGE,
null,
options,
options[0]);
System.out.println("displayoptions: " + displayoptions);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
ManyOptions o = new ManyOptions();
}
};
SwingUtilities.invokeLater(r);
}
}
答案 1 :(得分:1)
最好使用带有GridLayout的JPanel,并将其显示在模态JDialog中(实际上是JOptionPane)。例如,
import java.awt.Component;
import java.awt.Dialog.ModalityType;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class Foo1 {
private static final int BUTTON_COUNT = 15;
private static String selection = "";
public static void main(String[] args) {
JPanel panel = new JPanel(new GridLayout(3, 0, 5, 5));
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
for (int i = 0; i < BUTTON_COUNT; i++) {
panel.add(new JButton(new ButtonAction("Option " + (i + 1))));
}
JDialog dialog = new JDialog(null, "Select One", ModalityType.APPLICATION_MODAL);
dialog.add(panel);
dialog.pack();
dialog.setLocationRelativeTo(null);
dialog.setVisible(true);
System.out.println("selection: " + selection);
}
private static class ButtonAction extends AbstractAction {
public ButtonAction(String name) {
super(name);
}
@Override
public void actionPerformed(ActionEvent e) {
selection = e.getActionCommand();
Component c = (Component) e.getSource();
Window win = SwingUtilities.getWindowAncestor(c);
win.dispose();
}
}
}