2011-03-29 57 views
0

我正在爲我的第一個java項目做一個簡單的應用程序。 它結合了各種字符串來產生輸出。例如 - 名稱。獲得一個按鈕來重複一個動作

但是我碰到了一個障礙,我把所有的GUI都佈置好了,我所有的字符串都組成了,他們都做了一個隨機的結果,並在告訴時把它寫到文本標籤上,但是如果我點擊按鈕再次 - 納達。沒有。

我的問題是這樣的 - 我如何做一個按鈕重複我正在做的過程?沒有人能夠向我解釋這一點。我不是在尋找一個快速解決方案,而是尋找一個'如何',因爲我想學習。 :)

這裏是我的代碼的簡化版本:

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]; 
+1

你能否把你的代碼放在「代碼中」樣本「,以便更容易閱讀 – brent777 2011-03-29 10:59:17

+0

我做過,但它不能格式化它。 謝謝你修復它。 :) – 2011-03-29 11:05:49

回答

0

的問題是,你的變量是靜態的,這樣就意味着你的那句只計算一次它們被初始化只是一個單一的時間。

假設您想要每次不同的phrase然後每次單擊按鈕時重新初始化它們。從rand1rand2phrase中刪除單詞static,重新編譯應指向正確的方向。

也許類似

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]; 
} 

然後使用新的RandomLabeller()語句,而不是什麼類.phrase。更好的是,用getPhrase()這幾種方法來隔離這些。

+0

這聽起來像即時通訊想達到。 因此,爲這個特質創造一個新的課堂。 我如何將結果調用到文本字符串? – 2011-03-29 11:03:52

+0

新的RandomLabeller()。短語每次都會給你一個唯一的短語作爲一個字符串。 – 2011-03-29 12:05:11

1

想想兩件事情:

  1. 你的目的創建對象,不要用那麼多的靜態字段 - 這是邪惡的,可以讓你許多麻煩後
  2. Write方法復位(),它設置你的如果你想重複「process」,只需調用start()