如何将JTextField放入随机文本?

时间:2011-09-18 15:36:22

标签: java project jtextfield shuffle

我想在Textfield中显示随机播放的单词。 到目前为止,这是我的随机代码:

    public MyTextTwist(String w){
        if (w != null){
            word = getRandomWord();
                txtWord.setText(word);}

        GameOver = false;
    }

       private String getRandomWord(){
                ArrayList<Character> chars = new ArrayList<Character>(txtWord.getText().length());
                for ( char c : word.toCharArray() ) {
                    chars.add(c);
                }
                Collections.shuffle(chars);
                char[] shuffled = new char[chars.size()];
                for ( int i = 0; i < shuffled.length; i++ ) {
                    shuffled[i] = chars.get(i);

                }String shuffledWord = new String(shuffled);
                return shuffledWord;
        }

没有显示。

1 个答案:

答案 0 :(得分:2)

同样,如果你想把文本放回JTextField,代码必须通过在JTextField上调用setText(...)来做到这一点,但你不能在构造函数中这样做,因为当构造函数已经在调用时,用户没有机会在JTextField中输入任何文本。相反,您必须在对事件的响应中调用此方法,可能是在已添加到JButton的ActionListener中:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;

import javax.swing.*;

public class TestWordScramble extends JPanel {
   private JTextField txtWord = new JTextField(10);
   private JButton scrambleBtn = new JButton("Scramble");

   public TestWordScramble() {
      scrambleBtn.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            String word = getRandomWord(txtWord.getText());
            txtWord.setText(word);
         }
      });

      add(txtWord);
      add(scrambleBtn);
   }

   private String getRandomWord(String text) {
      ArrayList<Character> chars = new ArrayList<Character>();
      for (char c : text.toCharArray()) {
         chars.add(c);
      }
      Collections.shuffle(chars);
      char[] shuffled = new char[chars.size()];
      for (int i = 0; i < shuffled.length; i++) {
         shuffled[i] = chars.get(i);

      }
      String shuffledWord = new String(shuffled);
      return shuffledWord;
   }

   private static void createAndShowGui() {
      TestWordScramble mainPanel = new TestWordScramble();

      JFrame frame = new JFrame("TestWordScramble");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}