Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java GUI better to remove or setVisible(false)? [closed]

I am coding up a relatively simple GUI application in Java using widgets from the Swing library. What is the common practice for 'conditionally' displaying certain items? Is it to .setVisible(false) on things that we want to temporarily hide; or is it to .add items as they are needed and then removing them when they are not to be shown any more?

like image 313
ttttcrngyblflpp Avatar asked Feb 13 '23 21:02

ttttcrngyblflpp


2 Answers

" I need to display (multiple) error messages that must go away when things are correct obviously"

Not sure how you're displaying your error messages, but seems like a simple JLabel with the simple use of setText() would be appropriate. Trying to add an remove or set visible will mess with the layout, causing a constantly changing layout, which may be undesirable or not very user friendly. Something as simple as;

String errorMessage = "Error";
String noErrorMessage = "  ";

....
if (error) {
    errorLabel.setText(errorMessage);
} else {
    errorLabel.setText(noErrorMessage);
}

I use the space for noErrorMessage as having no space will affect the preferred size and still effect the layout

like image 166
Paul Samsotha Avatar answered Feb 15 '23 14:02

Paul Samsotha


Usually such things depend on the designer's opinion, however it depends what what exactly you're trying to show/hide.

If you want to display a widget after a certain condition/method returns true then just use setVisible(true), this allows you to easily toggle on/off.

If you want to display the widget only once(and not hide it ever again) then just .add it when you need to so that it's displayed(condition/method).

All boils down to preference

like image 45
Juxhin Avatar answered Feb 15 '23 12:02

Juxhin