[英]Get a button to repeat an action
I am making a simple application for my first java project. 我正在为我的第一个Java项目制作一个简单的应用程序。 It combines various strings to produce output.
它结合了各种字符串以产生输出。 Eg - Names.
例如-名称。
However I have run into a snag, I have my GUI all laid out, and all my Strings made up, and they all make a random result and write it to the text labels when told, but if I click the button again - nada. 但是我遇到了麻烦,我的GUI都已布置好,我的所有Strings都编好了,它们都产生了一个随机结果,并在被告知时将其写到文本标签中,但是如果我再次单击按钮-nada。 Nothing.
没有。
My question is this - How can I make a button REPEAT the process I am making it do? 我的问题是-如何使按钮重复执行的过程? No one had been able to explain this to me.
没有人能够向我解释这一点。 I am not looking for a quick fix but rather a `how to,' because I wish to learn.
我不是在寻找快速解决方案,而是在寻找“方法”,因为我想学习。 :)
:)
Here is a simplified version of my code: 这是我的代码的简化版本:
public static String[] name1 = {
"a", "b", "c", "d", "e", "f", "g", "h", "i",
"j", "k", "l", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z"
};
public static String[] name2 = {
"oh noes", "its not working","sad face"
};
public static int name1length = name1.length;
public static int name2length = name2.length;
public static int rand1 = (int) (Math.random() * name1length);
public static int rand2 = (int) (Math.random() * name2length);
public static String phrase = name1[rand1] + " " + name2[rand2];
Think about two things: 考虑两件事:
The problem is that your variables are static, they are initialized just a single time so that means that your phrase is only evaluated once. 问题在于您的变量是静态的,它们仅初始化一次,因此这意味着您的短语仅被评估一次。
Assuming that you want a different phrase
each time then reinitialize them each time you click the button. 假设您每次都想要一个不同的
phrase
那么每次您单击该按钮时都要重新初始化它们。 Removing the word static
from rand1
, rand2
and phrase
and recompiling should point you in the right direction. 从
rand1
, rand2
和phrase
删除static
phrase
并重新编译应该为您指明正确的方向。
Perhaps something like 也许像
class RandomLabeller {
private static String[] name1 = "abcdefghijklmnopqrstuvwxyz".toCharArray();
private static String[] name2 = {"oh noes","its not working","sad face"};
private static int name1length = name1.length;
private static int name2length = name2.length;
private int rand1 = (int)(Math.random()*name1length);
private int rand2 = (int)(Math.random()*name2length);
public final String phrase = name1[rand1] + " " + name2[rand2];
}
Then use new RandomLabeller().phrase instead of whatever class .phrase. 然后使用新的RandomLabeller()。phrase代替任何类.phrase。 Better still, insulate these with a few methods like
getPhrase()
. 更好的是,使用
getPhrase()
类的一些方法来隔离它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.