我有興趣創建一個 JOptionPane 或任何包含多個串列選擇的可互動彈出窗格。我還希望提取用戶所做的選擇。
下面的代碼顯示了一個 MRE,我在其中生成兩個不同的 JOptionPanes,其中包含串列選擇并從每個中提取選擇。本質上,我試圖將兩者結合起來。
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);
}
}
其中之一的樣子:

uj5u.com熱心網友回復:
JOptionPane其實是很靈活的。您可以構建一個包含任意數量組件的容器,然后用于JOptionPane顯示它,例如...

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());
}
});
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/379357.html
上一篇:QueryParam解碼我用cp1252編碼的url
下一篇:JavaGUI實時字計數器
