Skip to content
Advertisement

Refresh elements of GUI in java

I’m new to GUIs in java.

For example, I need to update just 1 element (e.g., JLabel). In Tkinter I would use something like root.update() or root.update_idletasks(). I wonder if a similar simple function exists in for applications made with swing. I’ve tried gui_element.SetVisible(false) and gui_element.SetVisible(true) and similar stuff, but not very successfully. I suspect something with javax.swing.Timer should work, but do not know how.

EDIT Here is the code. Please let me know if you find other errors. Thanks

JavaScript

Advertisement

Answer

Swing is event driven. All components work through the MVC pattern. You don’t need to explicitly repaint it by hiding/showing in order to update it’s representation on the screen.

You just do yourLabel.setText("your new text") and the new text will appear on the label.

Keep in mind that most GUI-updates (the setText is an exception) needs to be performed on the EDT, so use SwingUtilities.invokeLater etc if you’re update is triggered by, say, a network message.

If you do structural changes to the GUI you’ll have to revalidate()/repaint() though.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement