2017-03-06 98 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”。有很多方法可以做到这一点。