问题
Im trying to display the results of a search in a JOptionPane window so that when a certain search is found in a text file that it prints out the line in the text file. But it prints out every line in a separate window , is there any way I could print them all in the same window ??
public static void DisplayGrades() throws IOException
{
String line;
String stringToSearch = JOptionPane.showInputDialog(null, "Enter your student ID");
BufferedReader in = new BufferedReader( new FileReader("StudentResults.csv" ) );
line = in.readLine();
while (line != null)
{
if (line.startsWith(stringToSearch))
{
JOptionPane.showMessageDialog(null, line );
}
line = in.readLine();
}
in.close();
}
回答1:
You can use StringBuilder
to append all lines in one String and only after put it to JOptionPane
.
StringBuilder buff = new StringBuilder();
BufferedReader in = new BufferedReader( new FileReader("StudentResults.csv" ) );
line = in.readLine();
while (line != null)
{
if (line.startsWith(stringToSearch))
{
buff.append( line ).append("\n");
}
line = in.readLine();
}
in.close();
JOptionPane.showMessageDialog(null, buff.toString() );
As a side note:
Its not good idea to put csv results into JOptionPane
. I would write custom JDialog
来源:https://stackoverflow.com/questions/20180567/joptionpane-display-loop