简体   繁体   中英

Get a button to repeat an action

I am making a simple application for my first java project. 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. 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:

  1. Create Object for your purpose, don't use so many static fields - it's evil and can make you many troubles later
  2. Write method reset() which set your fields to default values and start() which begin your "process" and include reset() then if you'll want repeat "process" just call start()

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM