I am interested in creating a JOptionPane or any interactable pop-up Pane that contains multiple list selections. I also wish to extract the selections the user made.
The code below shows an MRE where I generate two different JOptionPanes with list selections and extract the choice from each. Essentially, I am trying to combine the two.
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class JOptionPaneTest {
public static void main(String[] a) {
JFrame frame = new JFrame();
String bigList[] = new String[30];
String smallList[] = new String[5];
for (int i = 0; i < bigList.length; i ) {
bigList[i] = Integer.toString(i);
}
for (int i = 0; i < smallList.length; i ) {
smallList[i] = Integer.toString(i);
}
String choice = (String) JOptionPane.showInputDialog(frame, "Pick the first number", "Number 1", JOptionPane.QUESTION_MESSAGE,
null, bigList, "Titan");
String choice2 = (String) JOptionPane.showInputDialog(frame, "Pick the second number", "Number 2", JOptionPane.QUESTION_MESSAGE,
null, smallList, "Titan");
System.out.println(choice);
System.out.println(choice2);
}
}
CodePudding user response:
JOptionPane
is actually very flexible. You could build a container containing any number of components and then use JOptionPane
to display it, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
String bigList[] = new String[30];
String smallList[] = new String[5];
for (int i = 0; i < bigList.length; i ) {
bigList[i] = Integer.toString(i);
}
for (int i = 0; i < smallList.length; i ) {
smallList[i] = Integer.toString(i);
}
JComboBox<String> bigListComboBox = new JComboBox<>(new DefaultComboBoxModel<String>(bigList));
JComboBox<String> smallListComboBox = new JComboBox<>(new DefaultComboBoxModel<String>(smallList));
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_END;
gbc.insets = new Insets(4, 4, 4, 4);
panel.add(new JLabel("Pick the first number"), gbc);
gbc.gridy ;
panel.add(new JLabel("Pick the second number"), gbc);
gbc.gridx ;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(bigListComboBox, gbc);
gbc.gridy ;
panel.add(smallListComboBox, gbc);
JOptionPane.showMessageDialog(null, panel, "Pick two numbers", JOptionPane.QUESTION_MESSAGE);
System.out.println("First number = " bigListComboBox.getSelectedItem());
System.out.println("Second number = " smallListComboBox.getSelectedItem());
}
});
}
}