Reputation: 1
I am making a simple application for my first java project. It combines various strings to produce output. E.g - 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. 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];
Upvotes: 0
Views: 565
Reputation: 26819
Think about two things:
Upvotes: 1
Reputation: 44706
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. Removing the word static
from rand1
, rand2
and phrase
and recompiling should point you in the right direction.
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. Better still, insulate these with a few methods like getPhrase()
.
Upvotes: 0