我正在尝试提供一个删除对象的确认窗口,该窗口要求用户在文本字段中输入“删除”一词以确认他们的操作,然后单击标有“删除”的按钮。此外,它还将具有标准的“取消”按钮。
以下是我想要的基本思想,但我不确定如何正确返回布尔值:
public static boolean confirmDelete(String msg) {
JPanel panel = new JPanel();
JPanel sPanel1 = new JPanel();
JPanel ssPanel1 = new JPanel();
ssPanel1.setLayout(new BoxLayout(ssPanel1, BoxLayout.Y_AXIS));
JLabel lbl = new JLabel(msg);
confirm = new JTextField(10);
ssPanel1.add(lbl);
ssPanel1.add(confirm);
JPanel ssPanel2 = new JPanel();
ssPanel2.setLayout(new BoxLayout(ssPanel2, BoxLayout.Y_AXIS));
JButton ok = new JButton("Delete");
ok.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(confirm.getText().toLowerCase().equals("delete")) {
//Set the returned value to true;
} else {
alertMsg("Invalid input. Please try again.");
}
}
});
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//Set the returned value to false;
}
});
ssPanel2.add(ok);
ssPanel2.add(cancel);
sPanel1.add(ssPanel1);
sPanel1.add(ssPanel2);
panel.add(sPanel1);
JFrame deleteFrm = new JFrame("Confirm Delete");
deleteFrm.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
//Add content to the window.
deleteFrm.setContentPane(panel);
//Display the window.
deleteFrm.pack();
deleteFrm.setVisible(true);
}
基本上,我想使用该行调用此窗口boolean deleteItem = ClassName.confirmDelete(msg);
并让它返回布尔值以说明他们是否正确确认了删除状态。如何设置它以返回代码示例中描述的布尔值(这是一种伪代码,因为它显然不正确)。像上面提到的那样,这甚至可以通过单行调用来实现吗?