当我运行此程序时,我在文本框中输入信息,按下搜索按钮,但没有任何反应。程序就在那里,直到我按下Cntrl C来打破它。它看起来应该可以工作,但我无法弄清楚是什么挂起了程序。
这是代码: 头等舱:
import java.io.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class NameGameFrame extends JFrame
{
public static String name;
static JTextField textfield = new JTextField(20);
static JTextArea textarea = new JTextArea(30,30);
public static String num;
public static String [] fields;
public static int [] yearRank;
public static boolean match;
public static int getInts, marker, year, max;
public static void main( String[] args)
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Name Game");
frame.setLocation(500,400);
frame.setSize(800,800);
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JLabel label = new JLabel("Enter the Name or Partial Name to search:");
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,2,2,2);
panel.add(label,c);
c.gridx = 0;
c.gridy = 1;
panel.add(textarea,c);
JButton button = new JButton("Search");
c.gridx = 1;
c.gridy = 1;
panel.add(button,c);
c.gridx = 1;
c.gridy = 0;
panel.add(textfield,c);
frame.getContentPane().add(panel, BorderLayout.NORTH);
frame.pack();
frame.setVisible(true);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
name = textfield.getText();
java.io.File file = new java.io.File("namesdata.txt");
try
{
Scanner input = new Scanner(file);
num = input.nextLine();
NameRecord nr = new NameRecord(name);
while (input.hasNext())
{
if(match = num.toLowerCase().contains(name.toLowerCase()))
{
nr.getRank();
nr.getBestYear(marker);
}
}
}
catch(FileNotFoundException e)
{
System.err.format("File does not exist\n");
}
textarea.setText(fields[0]);
}
});
}
}
这是第二堂课:
import java.io.*;
import java.util.*;
public class NameRecord
{
public NameRecord( String name)
{
}
public static int getBestYear(int marker)
{
switch (marker)
{
case 1:
year = 1900;
break;
case 2:
year = 1910;
break;
case 3:
year = 1920;
break;
case 4:
year = 1930;
break;
case 5:
year = 1940;
break;
case 6:
year = 1950;
break;
case 7:
year = 1960;
break;
case 8:
year = 1970;
break;
case 9:
year = 1980;
break;
case 10:
year = 1990;
break;
case 11:
year = 2000;
break;
}
return year;
}
public static int getRank()
{
fields = num.split(" ");
max = 0;
for (int i = 1; i<12; i++)
{
getInts = Integer.parseInt(fields[i]);
if(getInts>max)
{
max = getInts;
marker = i;
}
}
return max;
}
}
答案 0 :(得分:2)
我认为问题是,当使用hasNext()
结果时,由于调用hasNextLine()
而非nextLine()
,您可能无法完成Event Dispatch Thread的循环(见button.addActionListener(new ActionListener()
)。
无论如何,你应该调用SwingWorker或类似的东西来创建一个线程来进行需要很长时间的处理,然后使用EDT来显示结果。它将使未来的问题更容易调试,并且是正确的事情。