开发者

How to put JTextField a random text?

I want to show the shuffle word inside the Textfield. so far this is my random code:

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

It Doesn't show.


Again, if you want to put the text back into the JTextField, the code must do this by calling setText(...) on the JTextField, but you can't do this in the constructor since when the constructor has been called, the user hasn't had a chance to enter any text into the JTextField. Instead you must call this method in the response to an event, perhaps in an ActionListener that has been added to a JButton:

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();
         }
      });
   }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜