[英]Filling a HashSet doesn't work the first time — only on second call
我想做什么:
我希望HashSet充满程序不知道的新单词。 用户按下主机上的“转换”按钮。 带有单词的文件的路径在mainFrame上给出。
如果单词是新单词,则将打开一个JDialog并要求插入新单词(因此您可以更改拼写,例如第一个字母big ...)。
如果用户按下JDialog上的“写入”按钮,则该单词将添加到HashSet中。
但是,如果在此之后打印我的HashSet,则仅显示“旧”值。 当我第二次按下主机上的“转换”按钮时,所有值将正确显示在HashSet中。
如果有人可以帮助我,我将不胜感激。 如果需要更多信息,请告诉我。 这是按下“转换”按钮时来自ActionListener的代码:
if (e.getActionCommand().equals(convert.getActionCommand())) {
try {
//a file with words is given
fileHandler = new FileIO(path.getText().trim());
//lines is a ArrayList<String> and returns all the lines
lines = fileHandler.readFile();
for (int i = 0; i < lines.size(); i++) {
//words is a String[]
words = lines.get(i).split(" ");
for (int j = 0; j < words.length; j++) {
//hs is a HashSet<String>
if (hs.contains(words[j])) {
System.out.println("hit: " + words[j]);
}else if (!hs.contains(words[j])) {
dialog = new JDialog(mainFrame);
dialog.setTitle("new Word");
dialog.setLayout(new BorderLayout());
newWord = new JTextField(words[j].toLowerCase());
newWord.selectAll();
write = new JButton("write");
write.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//can not use the counters "i" or "j" here otherwise it would be so easy...
s = newWord.getText().trim();
dialog.setVisible(false);
if(dialog != null)
dialog.dispose();
if (dialog.isActive()) {
System.out.println("active");
}else {
//dead code ??? -- never executed so far
System.out.println("finally....done");
}
}
});
dialog.add(newWord, BorderLayout.NORTH);
dialog.add(write, BorderLayout.SOUTH);
dialog.pack();
dialog.setVisible(true);
//todo is filled correctly IF pressed "convert Button" the second time
if (!s.contentEquals("")) {
words[j] = s;
hs.add(s);
s = "";
}
}
} // words
//Displays the input line but why not the manipulated from the JDialog input?
StringBuffer sb = new StringBuffer();
for (String string : words) {
sb.append(string);
sb.append(" ");
}
System.out.println(sb.toString());
lines.set(i, sb.toString());
sb.delete(0, sb.length());
} // lines
当我按下mainFrame上的“退出”按钮时,写入(在文件中)并显示我的HashSet的代码:
hashSetHandler = new HashSetIO(WORDS_FILE);
hashSetHandler.write(hs);
for (String string : hs) {
System.out.println(string);
您应该考虑使dialog
成为模态。
当前,当您按下convert
,会看到许多弹出窗口(每个从文件中读取的新单词都会弹出一个窗口),不是吗?
模态dialog
和“普通” dialog
之间的区别将在此处影响您的代码:
dialog.setVisible(true);
//todo is filled correctly IF pressed "convert Button" the second time
if (!s.contentEquals("")) {
words[j] = s;
hs.add(s);
s = "";
}
模式dialog
将在dialog.setVisible(true)
行处阻塞,直到按下write
按钮,并且ActionListener
将处理Event,设置为s = newWord.getText().trim();
并设置dialog
。
仅在处理了此事件(按write
)之后,才会执行dialog.setVisible(true)
之后的代码行,并且s
将包含newWord.getText().trim()
。
使用“普通”(非模式) dialog
您不会在dialog.setVisible(true)
处阻塞,因此
if (!s.contentEquals(""))
行将检查尚未设置的s
值(尚未按下write
按钮),测试将失败, if
块中的代码将不执行。
我建议您调试在if
行和write
按钮的ActionListener
中设置断点的代码。 然后,您将更好地理解执行代码的时间以及字段的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.