【发布时间】:2014-10-05 02:13:09
【问题描述】:
我最近使用 System.out.println() 构建并完成了与 IDE 配合使用的 java 程序的第一阶段;什么不是。现在,我想给这个程序一个 GUI,但我遇到了一个问题。这是我的 MCV 示例(或者至少我认为是,如果不是,请告诉我)。
import java.net.*;
import java.net.UnknownHostException;
import java.net.NoRouteToHostException;
import java.io.*;
import net.sf.json.*;
import org.apache.commons.lang.exception.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import java.awt.Component;
import java.awt.Container;
import java.util.Scanner;
public class WOT_PlayerComp_V2
{
public static JFrame f;
public static JLabel resultLabel;
public static JPanel p;
public static JTextField t;
public static String comparisonResults = "";
public static String holder = "";
public static String playerName = "";
public boolean gameIsStillRunning = true;
public static void testGUI()
{
f = new JFrame();
addComponentsToPane(f.getContentPane());
f.setSize(300, 400);
f.setLocation(200, 200);
// f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
public static void addComponentsToPane(Container c)
{
c.setLayout(new BoxLayout(c, BoxLayout.Y_AXIS));
p = new JPanel();
t = new JTextField(15);
//t.setDocument(new JTextField_wLimit(50));
//You can ignore this line, it is what I used to limit the input of my textfield
resultLabel = new JLabel();
//html makes the br have purpose, p makes it wrap
resultLabel.setHorizontalAlignment(SwingConstants.CENTER);
resultLabel.setVerticalAlignment(SwingConstants.TOP);
resultLabel.setSize(50, 50);
c.add(t);
c.add(resultLabel);
}
public WOT_PlayerComp_V2()
{
testGUI();
//... Lots of irrelevant code
resultLabel.setText("Enter your username.");
while(gameIsStillRunning)
{
//irrelevant code
playerName = t.getText();//scans user input
t.setText("");
//more irrelevant code
}
//if(playerName == null || playerName.equals(""))
//^^ it shouldn't go into here, I want my while loop to wait
//for user input like it did when i was using a Scanner object
//
}
public static void main(String[] args)
{
WOT_PlayerComp_V2 w = new WOT_PlayerComp_V2();
}
}
基本上,在我使用 JTextField 对象之前,我使用的是 Scanner 对象。 Scanner 对象实际上会停止我的 while 循环并运行该方法,然后继续。我想知道这是否可以通过 JTextField 实现。我希望能够在中间停止 for 循环并等待用户输入。我上面的 MCV 示例似乎没有那么大的问题,但是我使用的代码很大程度上基于输入,并且会响应用户输入 null 或空字符串。结果,它会做它应该做的事情,响应正确的用户输入,这只会持续一次迭代,然后它将继续从 JTextField 获取输入,因为它处于一个 while 循环中。那是我的问题。
【问题讨论】:
-
如果一切都失败了,我可能会使用 JButton 来接收输入,但即便如此,我仍然不知道如何停止 while 循环
标签: java swing user-interface jtextfield