我想要一个包含用于用户选择的JList的对话框。虽然以下会这样做,但我还想要一条消息和一个“取消”按钮。
list = new JList(LstArray1.toArray());
JOptionPane.showMessageDialog(
null, list, "Title", JOptionPane.INFORMATION_MESSAGE);
更像这样,但将组合框更改为JList。
String input = (String) JOptionPane.showInputDialog (null, "Choose from list", "title", JOptionPane.INFORMATION_MESSAGE, null, LstArray2.toArray(), LstArray2.get(0));
我看了以下但似乎找不到我需要的东西。 http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
答案 0 :(得分:2)
这可能不是您正在寻找的,但希望它能为您提供所需的基础或激发您自己的替代方法:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ListDialog {
private JList list;
private JLabel label;
private JOptionPane optionPane;
private JButton okButton, cancelButton;
private ActionListener okEvent, cancelEvent;
private JDialog dialog;
public ListDialog(String message, JList listToDisplay){
list = listToDisplay;
label = new JLabel(message);
createAndDisplayOptionPane();
}
public ListDialog(String title, String message, JList listToDisplay){
this(message, listToDisplay);
dialog.setTitle(title);
}
private void createAndDisplayOptionPane(){
setupButtons();
JPanel pane = layoutComponents();
optionPane = new JOptionPane(pane);
optionPane.setOptions(new Object[]{okButton, cancelButton});
dialog = optionPane.createDialog("Select option");
}
private void setupButtons(){
okButton = new JButton("Ok");
okButton.addActionListener(e -> handleOkButtonClick(e));
cancelButton = new JButton("Cancel");
cancelButton.addActionListener(e -> handleCancelButtonClick(e));
}
private JPanel layoutComponents(){
centerListElements();
JPanel panel = new JPanel(new BorderLayout(5,5));
panel.add(label, BorderLayout.NORTH);
panel.add(list, BorderLayout.CENTER);
return panel;
}
private void centerListElements(){
DefaultListCellRenderer renderer = (DefaultListCellRenderer) list.getCellRenderer();
renderer.setHorizontalAlignment(SwingConstants.CENTER);
}
public void setOnOk(ActionListener event){ okEvent = event; }
public void setOnClose(ActionListener event){
cancelEvent = event;
}
private void handleOkButtonClick(ActionEvent e){
if(okEvent != null){ okEvent.actionPerformed(e); }
hide();
}
private void handleCancelButtonClick(ActionEvent e){
if(cancelEvent != null){ cancelEvent.actionPerformed(e);}
hide();
}
public void show(){ dialog.setVisible(true); }
private void hide(){ dialog.setVisible(false); }
public Object getSelectedItem(){ return list.getSelectedValue(); }
}
示例用法:
JList list = new JList(new String[] {"foo", "bar", "foobar"});
ListDialog dialog = new ListDialog("Please select an item in the list: ", list);
dialog.setOnOk(e -> System.out.println("Chosen item: " + dialog.getSelectedItem()));
dialog.show();
随意使用/修改上述内容,如果您有任何疑问,请在下面提出