简体   繁体   English

如何将JTextfield的Text设置为带数组的方法

[英]How to setText of JTextfield to a method with an array

I have a class called ShoutBox, and there it has this array and this method: 我有一个名为ShoutBox的类,它有这个数组和这个方法:

   String messages[] = new String[10];
    //declare 10 arrays
    messages[0] = "Miley";
    messages[1] = "Katy";
    messages[2] = "Gaga";
    messages[3] = "Beyonce";
    messages[4] = "Taylor";
    messages[5] = "Missy";
    messages[6] = "Nicki";
    messages[7] = "Adele";
    messages[8] = "Rihanna";
    messages[9] = "Selena";

    String x = new ShoutBox().shoutOutCannedMessage(messages);
    System.out.println(x);

    public String shoutOutCannedMessage(String[] messages) {
    for (int i = 0; i < messages.length; i++) {
        System.out.println(i+". "+messages[i]); 
    }

    System.out.print("Select a message: ");
    int n = scan.nextInt();
    String message = messages[n];
    return message;
    }

And then I have a another class for GUI, how to I make that result appear in a JTextField when an action is perform? 然后我有一个GUI的另一个类,当执行一个动作时,如何让结果出现在JTextField中?

    private void shoutOutMessageActionPerformed(java.awt.event.ActionEvent     evt) {                                                
  JTextArea.setText(????); 
}

Thanks! 谢谢!

Assuming that you want to show the next phrase in the array in response to an event and not show all phrases all at once: 假设您要显示数组中的下一个短语以响应事件而不是一次显示所有短语:

  • Give your class an int index counter field, such as private int shoutIndex and initialize it to 0. 为您的类提供一个int索引计数器字段,例如private int shoutIndex并将其初始化为0。
  • On any pertinent event (such as in an ActionListener), increment that index, eg, shoutIndex++ 在任何相关事件(例如在ActionListener中)中,递增该索引,例如shoutIndex++
  • Then make sure that the index is not larger than the length of the array using the remainder operator: shoutIndex %= messages.length 然后使用余数运算符确保索引不大于数组的长度: shoutIndex %= messages.length
  • Then get the corresponding item from the array using the index, messages[shoutIndex] , and use it to set the text of the JTextField. 然后使用索引, messages[shoutIndex]从数组中获取相应的项,并使用它来设置JTextField的文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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