Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 打印到GUI文本字段?_Java_Swing_User Interface - Fatal编程技术网

Java 打印到GUI文本字段?

Java 打印到GUI文本字段?,java,swing,user-interface,Java,Swing,User Interface,我正在尝试用Java创建一个GUI彩票程序。彩票程序的实际代码运行得很好,我也创建了GUI。问题是,当按下Go按钮时,程序无法运行,并且相应的GUI文本字段中没有显示信息 以下是基本的乐透代码,完全不涉及GUI: package slots; import java.util.*; public class Slots { static int displaynum[] = new int[5]; static int compnum[] = new int[5]; stat

我正在尝试用Java创建一个GUI彩票程序。彩票程序的实际代码运行得很好,我也创建了GUI。问题是,当按下Go按钮时,程序无法运行,并且相应的GUI文本字段中没有显示信息

以下是基本的乐透代码,完全不涉及GUI:

    package slots;

    import java.util.*;

public class Slots {
static int displaynum[] = new int[5];
static int compnum[] = new int[5];
static int counter=0;
static int matchFound=0;
static int nummatch[] = new int[6];

public static void main(String[] args) {
    for(int z=0; z<5;z++) {
        Random i = new Random();
      //Change 10 to 60
        compnum[z]=i.nextInt((10 - 1) + 1) + 1;
    }
    System.out.println(" " + compnum[0] +"  " + compnum[1] +"  " + compnum[2] +"  " + compnum[3] +"  " + compnum[4]);

    while(nummatch[5]==0) {
        nextGo();
        matchFound=0;
        if(compnum[0]==displaynum[0]) {
            matchFound++;
        }
        if (compnum[1]==displaynum[1]){
            matchFound++;
        }
        if (compnum[2]==displaynum[2]){
            matchFound++;
        } 
        if (compnum[3]==displaynum[3]){
            matchFound++;
        }
        if (compnum[4]==displaynum[4]){
            matchFound++;
        }
        nummatch[matchFound]++;
    }
    System.out.println("  Zero Matches=" + nummatch[0] + "   One Matches=" + nummatch[1] +"   Two Matches=" +  nummatch[2]+ "   Three Matches=" + nummatch[3]+ "   Four Matches=" + nummatch[4]+ "   Total Draws=" + counter);

}


static void nextGo() {
    for(int x=0;x<5;x++) {
        Random i = new Random();
        //Change 10 to 60
        displaynum[x]=i.nextInt((10 - 1) + 1) + 1;
    }
    counter++;

    System.out.println("  " + displaynum[0] +"  " + displaynum[1] +"  " + displaynum[2] +"  " + displaynum[3] +"  " + displaynum[4]);
}
 }
因此,上面的代码显示了每个乐透图,并正确地显示了不同的匹配。但是我很难在GUI文本字段中显示这些相同的输出

下面是我尝试将上述代码与GUI结合起来的步骤:

    package slots;

    import java.awt.*; 
    import java.awt.event.*; 
    import java.util.Random;
    import java.util.*;

  public class LottoGUI extends Frame implements ActionListener {

private static TextField tfOne;
private static TextField tfTwo;
private static TextField tfThree;
private static TextField tfFour;
private static TextField tfFive;
private Label lblmnZero;
private static TextField mnZero;
private Label lblmnOne;
private static TextField mnOne;
private Label lblmnTwo;
private static TextField mnTwo;
private Label lblmnThree;
private static TextField mnThree;
private Label lblmnFour;
private static TextField mnFour;
private Label lbltfDraws;
private static TextField tfDraws;
private Button btnGo;
private Button btnClose;

public LottoGUI() {
    setLayout(new FlowLayout());

      tfOne = new TextField("", 2);
      tfOne.setEditable(false);
      add(tfOne);
      tfTwo = new TextField("", 2);
      tfTwo.setEditable(false);
      add(tfTwo);
      tfThree = new TextField("", 2);
      tfThree.setEditable(false);
      add(tfThree);
      tfFour = new TextField("", 2);
      tfFour.setEditable(false);
      add(tfFour);
      tfFive = new TextField("", 2);
      tfFive.setEditable(false);
      add(tfFive);

      lblmnZero = new Label("Zero Matches:");
      add(lblmnZero);
      mnZero = new TextField("");
      mnZero.setEditable(false);
      add(mnZero);
      lblmnOne = new Label("One Matches:");
      add(lblmnOne);
      mnOne = new TextField("");
      mnOne.setEditable(false);
      add(mnOne);
      lblmnTwo = new Label("Two Matches:");
      add(lblmnTwo);
      mnTwo = new TextField("");
      mnTwo.setEditable(false);
      add(mnTwo);
      lblmnThree = new Label("Three Matches:");
      add(lblmnThree);
      mnThree = new TextField("");
      mnThree.setEditable(false);
      add(mnThree);
      lblmnFour = new Label("Four Matches:");
      add(lblmnFour);
      mnFour = new TextField("");
      mnFour.setEditable(false);
      add(mnFour);
      lbltfDraws = new Label("Total Draws:");
      add(lbltfDraws);
      tfDraws = new TextField("");
      tfDraws.setEditable(false);
      add(tfDraws);

      btnGo = new Button("GO");
      add(btnGo);
      btnClose = new Button("CLOSE");
      add(btnClose);

      btnGo.addActionListener(this);
      btnClose.addActionListener(this);

      setTitle("Lotto");
        setSize(1000, 100);
        setVisible(true);
}

public static void main(String[] args) {
    new LottoGUI();

}

public static class Slots {
    static int displaynum[] = new int[5];
    static int compnum[] = new int[5];
    static int counter=0;
    static int matchFound=0;
    static int nummatch[] = new int[6];

    public static void main(String[] args) {
        for(int z=0; z<5;z++) {
            Random i = new Random();
          //Change 10 to 60
            compnum[z]=i.nextInt((10 - 1) + 1) + 1;
        }
        //System.out.println(" " + compnum[0] +"  " + compnum[1] +"  " + compnum[2] +"  " + compnum[3] +"  " + compnum[4]);
        Object[] obcm0 = {compnum[0]};
        mnZero.setText(Arrays.toString(obcm0));
        Object[] obcm1 = {compnum[1]};
        mnOne.setText(Arrays.toString(obcm1));
        Object[] obcm2 = {compnum[2]};
        mnTwo.setText(Arrays.toString(obcm2));
        Object[] obcm3 = {compnum[3]};
        mnThree.setText(Arrays.toString(obcm3));
        Object[] obcm4 = {compnum[4]};
        mnFour.setText(Arrays.toString(obcm4));

        while(nummatch[5]==0) {
            nextGo();
            matchFound=0;
            if(compnum[0]==displaynum[0]) {
                matchFound++;
            }
            if (compnum[1]==displaynum[1]){
                matchFound++;
            }
            if (compnum[2]==displaynum[2]){
                matchFound++;
            } 
            if (compnum[3]==displaynum[3]){
                matchFound++;
            }
            if (compnum[4]==displaynum[4]){
                matchFound++;
            }
            nummatch[matchFound]++;
        }
        //System.out.println("  Zero Matches=" + nummatch[0] + "   One Matches=" + nummatch[1] +"   Two Matches=" +  nummatch[2]+ "   Three Matches=" + nummatch[3]+ "   Four Matches=" + nummatch[4]+ "   Total Draws=" + counter);
        Object[] obnm0 = {nummatch[0]};
        mnZero.setText(Arrays.toString(obnm0));
        Object[] obnm1 = {nummatch[1]};
        mnOne.setText(Arrays.toString(obnm1));
        Object[] obnm2 = {nummatch[2]};
        mnTwo.setText(Arrays.toString(obnm2));
        Object[] obnm3 = {nummatch[3]};
        mnThree.setText(Arrays.toString(obnm3));
        Object[] obnm4 = {nummatch[4]};
        mnFour.setText(Arrays.toString(obnm4));
        Object[] obcn = {counter};
        tfDraws.setText(Arrays.toString(obcn));
    }


    static void nextGo() {
        for(int x=0;x<5;x++) {
            Random i = new Random();
            //Change 10 to 60
            displaynum[x]=i.nextInt((10 - 1) + 1) + 1;
        }
        counter++;

        //System.out.println("  " + displaynum[0] +"  " + displaynum[1] +"  " + displaynum[2] +"  " + displaynum[3] +"  " + displaynum[4]);
        Object[] obdn0 = {displaynum[0]};
        tfOne.setText(Arrays.toString(obdn0));
        Object[] obdn1 = {displaynum[1]};
        tfTwo.setText(Arrays.toString(obdn1));
        Object[] obdn2 = {displaynum[2]};
        tfThree.setText(Arrays.toString(obdn2));
        Object[] obdn3 = {displaynum[3]};
        tfFour.setText(Arrays.toString(obdn3));
        Object[] obdn4 = {displaynum[4]};
        tfFive.setText(Arrays.toString(obdn4));
    }
}

public void actionPerformed(ActionEvent e) {
    String str = e.getActionCommand();

     if(str.equals("GO"))
        new Slots();

     else if (str.equals("CLOSE"))
        System.exit(0);
    }

}
当我点击GO按钮时,什么也没有发生。也许我把打印命令放在了错误的代码部分,或者我没有做其他错误的事情?我真的很感谢您的指导


这也是我第一次在这个网站上发帖,所以如果我把事情搞砸了,请告诉我。我一直在寻求帮助,但找不到多少与我的问题有关的东西。谢谢大家!

你忘了给nextGo打电话了

替换

if(str.equals("GO"))
        new Slots();

这应该可以解决问题

更新1:


请从nextGo中删除static。当您从静态方法访问非静态对象时,是否确实编译了代码?

您似乎正在尝试将静态线性控制台程序与事件驱动GUI合并,这是行不通的。首先,while循环阻塞了Swing事件线程,这有可能使GUI无法运行。您需要重新编写程序逻辑,使其以事件驱动的方式工作。创建真正的对象,并使几乎所有的字段和方法都是非静态的

例如,我会使我的大部分字段(常量除外)都是非静态的。我会将我的大部分字段设置为私有,只将需要其他类调用的方法设置为公共。我将传递对需要调用原始对象方法的对象的引用。例如,这里有一个小程序,它可以做你想做的事情,但不完全是作弊,它可以给出我的想法:

import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleGui extends JPanel {
   private static final int TEXT_FIELD_COLUMNS = 3;
   private JTextField[] textFields = new JTextField[SimpleModel.VALUES_COUNT];
   private JButton goButton = new JButton(new GoAction("Go", KeyEvent.VK_G));
   private JButton exitButton = new JButton(new ExitAction("Exit",
         KeyEvent.VK_X));
   private SimpleModel simpleModel = new SimpleModel(this);

   public SimpleGui() {
      for (int i = 0; i < textFields.length; i++) {
         textFields[i] = new JTextField(TEXT_FIELD_COLUMNS);
         textFields[i].setEditable(false);
         textFields[i].setFocusable(false);
         add(textFields[i]);
      }
      add(goButton);
      add(exitButton);
   }

   public void setTextFieldText(int index, String text) {
      if (index < 0 || index >= textFields.length) {
         throw new IllegalArgumentException("index: " + index);
      } else {
         textFields[index].setText(text);
      }
   }

   private class GoAction extends AbstractAction {
      public GoAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         simpleModel.go();
      }
   }

   private class ExitAction extends AbstractAction {
      public ExitAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent e) {
         JButton btn = (JButton) e.getSource();
         Window win = SwingUtilities.getWindowAncestor(btn);
         win.dispose();
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("SimpleGui");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(new SimpleGui());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

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

class SimpleModel {
   public static final int MAX_VALUE = 100;
   public static final int VALUES_COUNT = 4;
   private Random random = new Random();
   private SimpleGui simpleGui;
   private int[] values = new int[VALUES_COUNT];

   public SimpleModel(SimpleGui simpleGui) {
      this.simpleGui = simpleGui;
   }

   public void go() {
      for (int i = 0; i < values.length; i++) {
         values[i] = random.nextInt(MAX_VALUE) + 1;
         simpleGui.setTextFieldText(i, String.valueOf(values[i]));
      }

      // TODO: use the values array here
   }
}
模型采用此引用并使用它设置GUI字段:

class SimpleModel {
   //....

   private SimpleGui simpleGui;

   // ...

   public SimpleModel(SimpleGui simpleGui) {
      this.simpleGui = simpleGui;
   }
然后模型的go方法调用GUI的公共方法来设置文本字段text:

public void go() {
  for (int i = 0; i < values.length; i++) {
     values[i] = random.nextInt(MAX_VALUE) + 1;
     simpleGui.setTextFieldText(i, String.valueOf(values[i]));
  }

  // TODO: use the values array here
}

请注意,如果这是真正的MVC,模型视图控制,那么模型根本不会调用GUI的方法,而是会通知侦听器状态的变化,但这是供以后讨论的。

您似乎试图将静态线性控制台程序与事件驱动GUI合并,但这永远不会起作用。首先,while循环阻塞了Swing事件线程,这有可能使GUI无法运行。您需要重新编写程序逻辑,使其以事件驱动的方式工作。创建真实的对象,并使几乎所有的字段和方法都是非静态的。非常感谢您提供的所有信息!我将继续对此进行研究,并使用上述代码作为参考。谢谢!这确实让一些数字显示在GUI中,但我还需要做更多的工作。
class SimpleModel {
   //....

   private SimpleGui simpleGui;

   // ...

   public SimpleModel(SimpleGui simpleGui) {
      this.simpleGui = simpleGui;
   }
public void go() {
  for (int i = 0; i < values.length; i++) {
     values[i] = random.nextInt(MAX_VALUE) + 1;
     simpleGui.setTextFieldText(i, String.valueOf(values[i]));
  }

  // TODO: use the values array here
}