我正在使用Netbeans平台向现有代码库中添加内容(14)及其GUI生成器显示用户选择的数据,以创建输出文件。用户选择输入,然后选择使用默认文件名生成文件。我想用一个对话框中断该过程,向用户呈现他们输入的内容的摘要,一个包含默认文件名和“确定”-“取消”按钮的TextField
。我创建了一个由DialogDescriptor
配置的DialogDisplayer
,其中包含一个JPanel
,其中包含摘要信息和文件名JTextField
。这一切都正常,我看到了摘要数据,我可以修改文件名,但选择OK
或Cancel
不会关闭窗口。只有右上角的X才能关闭它。
我的actionPerformed()
方法被调用,并执行与所选按钮相对应的代码,但就是不知道如何从那里关闭窗口。我试着将关闭选项设置为null(dd.setClosingOptions(null);
),API说这会导致所有操作关闭窗口。失败。
我在API中没有看到要调用以关闭DialogDisplayer
窗口的方法。
我最初想使用JDialog
,但它需要一个Frame,我不知道如何从org.netbeans.spi.project.ActionProvider
(启动请求的封闭类)中获取它。我使用Swing的时间比我愿意承认的要长(从java 1.1开始),但Netbeans平台框架对我来说是新的。
下面是我的代码:
private class FileNameDialog extends JPanel implements ActionListener
{
private final JTextField fileNameField = new JTextField(50);
private final JLabel fileNameLabel = new JLabel("File Name");
private final JLabel infoLabel = new JLabel();
private final JPanel entryPanel = new JPanel(new FlowLayout());
public FileNameDialog(String fileName, String info)
{
infoLabel.setText(info);
fileNameField.setText(fileName);
setLayout(new BorderLayout());
entryPanel.add(fileNameLabel);
entryPanel.add(fileNameField);
add(BorderLayout.CENTER, infoLabel);
add(BorderLayout.PAGE_END, entryPanel);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals(OK_BUTTON))
{
//Replace the file name with what was entered and move on
abort = false; //Global field in enclosing class
logger.log(Level.INFO, "Setting abort to FALSE for {0}",
fileNameField.getText());
}
else if (e.getActionCommand().equals(CANCEL_BUTTON))
{
abort = true; //Global field in enclosing class
logger.log(Level.INFO, "Setting abort to TRUE");
}
//Close the Dialog Window Here (somehow)
}
}
/**
* Request text entry from the user. Currently used for displaying the
* file name and allowing the user to update it. This is the entry point
* for all this code.
* @param info summary text
* @param title window title
* @return the user entered String
*/
private String userRequestDialog(String info, String title, String fileName)
{
FileNameDialog fileNameDialog = new FileNameDialog(fileName, info);
Object [] options = { new JButton ("OK"),
new JButton ("Cancel")};
DialogDescriptor dd = new DialogDescriptor (fileNameDialog,
title,
true,
options,
null,
DialogDescriptor.DEFAULT_ALIGN,
null,
fileNameDialog);
DialogDisplayer.getDefault().notify(dd); //Display the window
dd.setClosingOptions(null); //Doesn't seem to have any effect
return fileNameDialog.fileNameField.getText(); //FileName to use as process continues
}
为了好玩,我尝试了Object frame = lookup.lookup(JFrame.class);
,但返回的结果为空。
1条答案
按热度按时间yws3nbqq1#
@jjazzboss --你的答案解决了我的问题,你应该得到表扬。
虽然从技术上讲它没有回答这个问题,但它允许我用JOptionPane替换Netbeans DialogDisplayer,如下所示。我还尝试了一个模仿https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html中的CustomDialog的CustomDialog,但OK和Cancel按钮仍然没有关闭它。我怀疑Netbeans中的某些东西正在窃取这些事件,因为侦听器中的断点从未被命中(或者我把代码搞砸了)。