Java Swing。使用单个按钮读取txt文件并打印到文本区域
对不起,我是初学者。我正在构建一个密码生成器,它从txt文件中读取一个名词列表,然后随机选取一个并将其打印到文本字段
同样的过程将用于形容词列表。我计划的最终结果将是
- 随机名词+
- 随机形容词+
- 随机字符串(!?$等)
所有这些都是通过一个按钮完成的
我在动作监听器中使用了名词部分。但是出于组织的目的,我将动作移动到它们自己的单独方法中,然后将这些方法调用到动作侦听器中。在将名词部分移动到自己的方法之后,我无法让它继续工作
代码:最上面的部分是有效的,并且被注释掉了。底部部分是我试图将其分离为自己的方法,但我无法开始工作
Error: Exception in thread "AWT-EventQueue-0" java.lang.Error: Unresolved compilation problem:
The method nouns(String) in the type PassWord is not applicable for the arguments ()
Generate.addActionListener(new ActionListener() {
public void actionPerformed (ActionEvent arg0) {
nouns();
/*
File file = new File("nouns.txt");
try {
ArrayList<String> lines = new ArrayList<String>();
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if(line.length() > 0) {
lines.add(line);
//System.out.print(line);
Collections.shuffle(lines);
String pickNoun = lines.get(0);
output.setText(pickNoun);
}
}} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
}
});
}
public static void nouns(String noun) {
File file = new File("nouns.txt");
try {
ArrayList<String> lines = new ArrayList<String>();
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
if(line.length() > 0) {
lines.add(line);
//System.out.print(line);
Collections.shuffle(lines);
String pickNoun = lines.get(0);
String noun = pickNoun;
pickNoun = noun;
//noun.setText(pickNoun);
//output.setText(pickNoun);
}
}} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
# 1 楼答案
例外情况是准确地告诉您错误是什么:
你的方法是:
因此,它希望您将
String noun
传递给它(可能您正试图返回一个,因此应该将其更改为:你称之为:
内部没有参数,因此,或者从方法中移除String参数,或者将字符串传递给方法,我会移除String参数,因为您在方法中的任何地方都没有使用它
我在这里看到了几个错误:
您想从方法
nouns
返回一个String noun
正如您在上面看到的,我删除了
static
关键字,因为您应该在类实例(IMO)中使用它# 2 楼答案
我已经解决了这个问题。问题在于我对方法的命名和代码的结构。我的动作监听器在main方法中。我必须包含static,才能将它们传递给我想的侦听器。不知道我的解决方案是否是最优的,我是初学者,但就是这样
}