2017-03-06 51 views
2

我有一個隨機字符串發生器:移動值的JTextField

public class string{ 
private static final String dCase = "abcdefghij"; 
private static Random r = new Random(); 
private static String pass = ""; 

public static void main (String[] args) { 
    while (pass.length() != 1){ 
     int rPick = r.nextInt(4); 
     if (rPick == 0){ 
      int spot = r.nextInt(10); 
      pass += dCase.charAt(spot); 
     } 
    } 
    System.out.println (pass); 
} 
} 

我怎麼會得到一個什麼樣的位置印入我的JTextField的結果呢?

public void mouseClicked(MouseEvent arg0) { 
      string s = new string(); 
      textField_tf1.setText(); //This is the bit I'm unsure on 
      } 

回答

1

請在string類返回pass的方法:

public class string{ 
private static final String dCase = "abcdefghij"; 
private static Random r = new Random(); 
private static String pass = ""; 

public static String randomString() { //method 
    while (pass.length() != 1){ 
     int rPick = r.nextInt(4); 
     if (rPick == 0){ 
      int spot = r.nextInt(10); 
      pass += dCase.charAt(spot); 
     } 
    } 
    return pass; //return 
} 
} 

而只是把它在你的mouseClicked(MouseEvent arg0)

public void mouseClicked(MouseEvent arg0) { 
    string s = new string(); 
    textField_tf1.setText(s.randomString()); //use 
} 
1

將param(String)放入setText()中。在這種情況下,你可以做.setText(「」+ spot);

編輯該值是私人的,所以只需寫一個retun方法並調用它來代替「spot」。有很多方法可以做到這一點。