简体   繁体   English

使用while循环创建Java GUI的问题

[英]Issues creating java GUI with while loop

I am creating a java GUI which is a fortune teller. 我正在创建一个Java GUI,它是一个算命先生。 The GUI will spit out one of twelve fortunes every time you click the "get my fortune" button, the strings will never repeat back to back, can can repeat later after other strings have gone before it. 每次您单击“获取我的财富”按钮时,GUI都会吐出十二种财富之一,这些字符串永远不会背靠背重复,可以在其他字符串消失之前再重复一次。 I have made already for the most part. 我已经做了大部分。 But now I am having some trouble creating the while loops to display the strings without repeating. 但是现在我在创建while循环来显示字符串而不重复时遇到了一些麻烦。 I have looked at my book which didn't really help. 我看了看我的书,并没有真正的帮助。 If you guys could point me in the right direction,it would be much appreciated. 如果你们能指出我正确的方向,将不胜感激。 Thanks! 谢谢! I entered all of the code so you can see the variables used. 我输入了所有代码,因此您可以看到使用的变量。 But my question starts at class RndButtonListener. 但是我的问题始于RndButtonListener类。

package FortuneTellerRunner;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


/**
 *
 * @author a3cal_000
 */
class FortuneTellerFrame extends JFrame
{
  final private JPanel mainPnl, titlePnl, displayPnl, buttonPnl, imagePnl;
  final private JButton quitBtn, rndBtn;
  final private JLabel titleLbl, iconLbl;
  final private JTextArea displayTa;
  final private JScrollPane scroller; 
  public String[] fortune = new String [12];
  int newIndex, oldIndex;
  private static final int HEIGHT = 250;
  private static final int WIDTH = 450;

public FortuneTellerFrame()
{
  setSize(WIDTH, HEIGHT);  
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  mainPnl = new JPanel();
  mainPnl.setLayout(new BorderLayout());

  displayPnl = new JPanel();
  buttonPnl = new JPanel();
  titlePnl = new JPanel();
  ImageIcon icon = new ImageIcon("FortuneTellerIcon.JPEG");
  iconLbl = new JLabel(icon);  
  titleLbl = new JLabel("Fortune Teller!");
  displayTa = new JTextArea();  
  imagePnl = new JPanel();
  scroller = new JScrollPane();
  // Create the layout of the title panel
  titlePnl.setLayout(new GridLayout(2,1));

  add(mainPnl);

  // Set the label to the panel.
  titlePnl.add(titleLbl);
  titlePnl.add(iconLbl);  


    // add the panel to the main panel.
    mainPnl.add(titlePnl, BorderLayout.NORTH);
    mainPnl.add(scroller, BorderLayout.CENTER);
    mainPnl.add(displayTa, BorderLayout.CENTER);       

    // Create the "Get my fortune button.
    rndBtn = new JButton("Get My Fortune!");
    quitBtn = new JButton("Quit");



    // Add the buttons to the buttonPnl in grid layout.
    buttonPnl.add(rndBtn);
    buttonPnl.add(quitBtn);

    // Create the grid layout for the button panel.
    buttonPnl.setLayout( new GridLayout(1, 2));

    // Add the button panel to the grid layout, South.
    mainPnl.add(buttonPnl, BorderLayout.SOUTH);    




    ActionListener listener = new RndButtonListener();
    rndBtn.addActionListener(listener);
    quitBtn.addActionListener(listener);

}


class RndButtonListener implements ActionListener
{
    public void actionPerformed(ActionEvent evt)
    {
        fortune[0] = "He who throws dirt is losing ground.";
        fortune[1] = "You will find the love of your life in food.";
        fortune[2] = "Do or do not, there is no try.";
        fortune[3] = "Tomorrow is a better day to try anything of importance.";
        fortune[4] = "Life's not about how hard you can hit, but how hard you can get hit and keep moving forward.";
        fortune[5] = "You can't be late until you show up.";
        fortune[6] = "If you think things can't get worse it's probably only because you lack sufficent imagination.";
        fortune[7] = "If youre at the top it means you have further to fall.";
        fortune[8] = "Even in last place, youre still in the race.";
        fortune[9] = "The road to riches is paved on the failures of others.";
        fortune[10] = "If you feel like your going no where, get off the treadmill.";
        fortune[11] = "Thinking about going to the gym is just as good as going.";       

        Random rnd = new Random(fortune.length);
        do
        {
        newIndex = rnd.nextInt(fortune.length);

        }
          while(newIndex == oldIndex);

        do
        {
            System.out.println(fortune[newIndex]);

            displayTa.append(fortune[newIndex] + "||");
            displayTa.updateUI();
            mainPnl.updateUI();
            oldIndex = newIndex;

        } 
            while(newIndex != oldIndex);

        class QuitButtonListener implements ActionListener
        {
            public void actionPerformed(ActionEvent evt)
            {
                System.exit(0);
            }        

        }

     }
 }

} }

The basic problem is you are re-creating the Random with the same seed each time, which is generally creating the same random sequence over and over again. 基本的问题是您每次都用相同的种子重新创建Random ,这通常一次又一次地创建相同的随机序列。

Instead try using... 而是尝试使用...

do {
    newIndex = (int) Math.round(Math.random() * (fortune.length - 1));
} while (newIndex == oldIndex);

You also don't need the second loop, it's just clutter that confuses the situation. 您也不需要第二个循环,只是混乱使情况变得混乱。

You may also find that... 您可能还会发现...

 displayTa.append(fortune[newIndex] + "\n");

produces nicer output (IMHO) 产生更好的输出(恕我直言)

You may also wish to take a look at How to use Scroll Panes 您可能还希望看看如何使用滚动窗格

Your program run fine, but this is a problem, fortune.length is a random seed which return me only 6 and 8 when I later called Random.nextInt(). 您的程序运行良好,但这是一个问题,fortune.length是一个随机种子,当我以后调用Random.nextInt()时,它仅返回6和8。

Random rnd = new Random(fortune.length);

Do it this way 这样做

Random rnd = new Random();

and also consider the formatting solution given by MadProgrammer. 并考虑MadProgrammer提供的格式化解决方案。

Random() gives you same number pattern. Random()为您提供相同的数字模式。 Try Random(System.currentTimeMillis()). 尝试使用Random(System.currentTimeMillis())。 It uses current time as seed, so you can get real random numbers. 它使用当前时间作为种子,因此您可以获得真实的随机数。

I did something similar to this just today, so let's see if I can remember... I made an ArrayList of type int of how many items I had (fortunes) 我今天做了类似的事情,所以让我看看是否可以记住...我做了一个int类型的ArrayList,它显示了我拥有多少项(财富)

ArrayList<Integer> fortuneSeq = new ArrayList<Integer>();

Then add in some numbers starting from 0 to code for the fortunes. 然后添加一些从0开始的数字,代表命运。

for(int i = 0; i < fortune.length; i++) {
    fortuneSeq.add(i);
}

Then I used the shuffle() method from the Collections class to randomize the list. 然后,我使用了Collections类中的shuffle()方法将列表随机化。

Collections.shuffle(fortuneSeq);

After that, just loop through to access the fortunes. 之后,只需循环访问即可。

for(int i = 0; i < fortune.length; i++) {
    System.out.println(fortune[fortuneSeq.get(i)]);
    //...
}

Edit: Silly autocorrect, you don't like programmers. 编辑:愚蠢的自动更正,您不喜欢程序员。

Edit: Fixed some furtunes instead of fortunes and fixed println statement. 编辑:修复了某些问题而不是命运,并修复了println语句。

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

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