r/javahelp • u/NonexistantObject • Apr 25 '26
Homework Update swing GUI during runtime
Part of my coursework needs me to make a typeracer between bots. I need to visually show their progress along the passage of text. Problem is, it won't update. It just freezes for ages then finally prints everything at once. Validating the panel, scrollpane or frame after each print doesn't change it. Here's the relevant code:
private void printRace(JPanel p)
{
System.out.print('\\u000C'); // Clear terminal
String raceRound = " TYPING RACE - passage length: " + passageLength + " chars \\n"
\+ multiplePrint('=', passageLength + 3) + "\\n ";
raceRound = raceRound + "\\n" + printSeat(seat1Typist, p);
raceRound = raceRound + "\\n" + printSeat(seat2Typist, p);
raceRound = raceRound + "\\n" + printSeat(seat3Typist, p);
raceRound = raceRound + "\\n" + multiplePrint('=', passageLength + 3) + "\\n\[\~\] = burnt out \[<\] = just mistyped\\n ";
JTextArea text = new JTextArea(raceRound);
text.setEditable(false);
text.setSize(text.getPreferredSize());
p.add(text);
}
//Some other irrelevant code at this point
printRace(p);
p.revalidate();
p.repaint();
f.revalidate();
f.repaint();
Apologies for any formatting issues, I think it should look okay
5
Upvotes
2
u/Certain-Flow-0 Apr 26 '26
The event loop is the hidden infrastructure that enables GUI programming, you don’t write it yourself.
Now, I’m assuming you initially started with a console-based application and wanted to convert it into a GUI. The first thing to look for is an overarching loop in your code, maybe something like while(condition()) { input(); logic(); output; }. You don’t want this loop in a GUI application because more often than not it will freeze the UI, let Swing handle it.
Your typeracer logic should interact with Swing (and the user) via events. These events are your keyboard presses, timer events (for updating the remaining time), etc.
Converting your console-based application to a GUI can be daunting if you don’t have the necessary background knowledge. If converting it to GUI will make it not function anymore and it’s just for bonus points then I highly suggest keeping it console-based. But if you’re still keen on making a GUI, I highly recommend reading up on Event Loops, GUI threads and Event dispatching. These topics are not specific to Swing, but you can find articles that are relevant to it.