Package sc.fiji.snt.gui
Class GuiUtils
java.lang.Object
sc.fiji.snt.gui.GuiUtils
Misc. utilities for SNT's GUI.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classUtility methods for creating and stylingJButtons, including SNT's notification and options buttons.static classSemantic UI colors (error/warning/link/selection/disabled) and a shared color chooser.static classUtility methods for creating and readingJSpinners andJTextFields.static classLook-and-feel constants and methods for setting/restoring SNT's activeLookAndFeel.static classstatic classA process-wide, persistent queue of pending notices for a notification-center UI element.static classUtility methods for creating and stylingJScrollPanes.static classUtility methods for creating and stylingJSplitPanes.static classUtility methods forJTableconfiguration and creation.static classUtility methods for wrapping, truncating, escaping, and lightly formatting plain/HTML text.static classUtility methods for expanding, collapsing, and scrollingJTrees.static classStateful "visiting zoom" helper used by widgets that navigate the canvas with "GoTo"-type of actions The default zoom is roughly two zoom steps above the current canvas magnification, falling back to 600% when no image is loaded. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic voidaddCloseShortcut(JFrame frame) static voidaddSeparator(JComponent component, String heading, boolean vgap, GridBagConstraints c) static voidaddSeparator(JComponent component, JLabel label, boolean vgap, GridBagConstraints c) static voidaddSeparator(JMenu menu, String header) static voidaddSeparator(JPopupMenu menu, String header) static voidaddTooltip(JComponent c, String text) voidadjustComponentThroughPrompt(Component container) static voidapplyRoundCorners(JComponent component) voidblinkingError(JComponent blinkingComponent, String msg) voidcenteredMsg(String msg, String title) voidcenteredMsg(String msg, String title, String buttonLabel) static voidcenterOnParent(Component parent, Window dialog) static voidcenterOnParent(Rectangle parentBounds, Window dialog) static voidcenterWindow(Window dialogToCenter, Window... windows) static voidstatic voidReleases one registration made byinitSplashScreen(); the splash only actually closes once every such registration has been released - seeSplashScreen#close()voidstatic StringctrlKey()static GridBagConstraintsdialog(String msg, JComponent component, String title) static voiddisplayBanner(String msg, Color background, Component parent) static voiddrawDragAndDropPlaceHolder(Component component, Graphics2D g) static voidenableComponents(Container container, boolean enable) static voidensureSameWidth(JComponent... components) Resizes components so that they all share the same preferred/minimum width (the largest among them), while each component keeps its own height.voidvoidvoidstatic voiderrorPrompt(String msg) static voiderrorPrompt(String msg, boolean centeredOnScreen) static JFileChooserfileChooser(String title, File file, int type, int selectionMode) floatingMsg(String msg, boolean autodismiss) static StringRewrites a common network-connectivity exception (unknown host, refused/timed-out connection) into a short, user-facing message, instead of the exception's own message, which for e.g.getChoice(String message, String title, String[] choices, String[] descriptions, String defaultChoice) Object[]getChoiceAndDouble(String message, String title, String[] choices, String defaultChoice, Double defaultValue) getChoiceRaceable(String message, String title, String[] choices, String defaultChoice, Future<?> task) LikegetChoice(String, String, String[], String), but the choices are shown as buttons and the prompt races a backgroundtask: if it completes before the user picks a button, the dialog is dismissed automatically/ Useful for "this is taking a while, keep waiting / open as-is / abort?"String[]getChoiceWithInput(String message, String title, String[] choices, String defaultChoice, String defaultInput) Object[]getChoiceWithOptionAndInfo(String title, String message, String[] choices, String defaultChoice, String infoText, String checkboxLabel, boolean checkboxDefault) Displays a dialog with radio button choices, optional info text, and an optional checkbox.Simplified color chooser.org.scijava.util.ColorRGBgetColorRGB(String title, org.scijava.util.ColorRGB defaultValue, String... panes) Simplified color chooser for ColorRGB.booleangetConfirmation(String msg, String title) booleangetConfirmation(String msg, String title, String yesLabel, String noLabel) getConfirmation2(String msg, String title, String yesLabel, String noLabel) boolean[]getConfirmationAndOption(String msg, String title, String checkboxLabel, boolean checkboxDefault) boolean[]getConfirmationAndOption(String msg, String title, String checkboxLabel, boolean checkboxDefault, String[] yesNoButtonLabels) static WindowgetCoordinates(String promptMsg, String promptTitle, SNTPoint defaultValue, int decimalPlaces, SNTPoint resetValue) getCoordinatesInternal(String promptMsg, String promptTitle, SNTPoint defaultValue, String[] labels, int decimalPlaces, SNTPoint resetValue) static JFileChoosergetDouble(String promptMsg, String promptTitle, double defaultValue, double min, double max, String unit) getImageFile(File file) getMultipleChoices(String title, String[] choices, String defaultChoice) Object[]getMultipleChoicesAndChoice(String title, String[] choices1, String defaultChoice1, boolean multipleSelectionAllowed1, String[] choices2, String defaultChoice2) getOpenFile(String title, File file, String... allowedExtensions) getOpenFileOrDirectory(String title, File file) AsgetOpenFile(String, File, String...), but the dialog also allows selecting a directory directly.getPercentage(String promptMsg, String promptTitle, int defaultValue) boolean[]getPersistentConfirmation(String msg, String title) getPersistentWarning(String msg, String title) float[]getReconstructionFile(File file, String extension) File[]getReconstructionFiles(File selectedFile) getSaveFile(String title, File file, String... allowedExtensions) Shows a "Save" dialog, honoringSNTPrefs.getUseNativeFileChooser(): either SNT's classicFileChooseror FlatLaf'sSystemFileChooser(native OS dialog).String[]getStrings(String promptTitle, String[] labels, String[] defaultValues, String optionalMsg) String[]getStringSet(String promptMsg, String promptTitle, Collection<String> defaultValues) static JTabbedPaneNumber[]getThreeNumbers(String promptMsg, String promptTitle, Number[] defaultValues, String[] labels, int decimalPlaces) static StringString[]getTwoChoices(String title, String choice1Label, String[] choices1, String defaultChoice1, String choice2Label, String[] choices2, String defaultChoice2) Number[]getTwoNumbers(String promptMsg, String promptTitle, Number[] defaultValues, String[] labels, int decimalPlaces) static StringgetWrappedText(JComponent c, String text, int maxWidth) Wrapstextin an HTML<div>capped atmaxWidth, so a long line wraps onto further lines instead of being clipped or silently growing its container.static voidRegisters one more caller that wants the loading splash screen open, showing it if it is not already showing.static booleanstatic JLabelleftAlignedLabel(String text, boolean enabled) static JLabelleftAlignedLabel(String text, String uri, boolean enabled) static JLabelleftAlignedLabel(String text, String uri, Runnable action, boolean enabled) AsleftAlignedLabel(String, String, boolean), but also (or instead of auri) running an in-app action on click -- e.g., for a label that should trigger something within the application, such as starting a wizard/tour, rather than (or in addition to) opening an external link.static JTextArealongSmallMsg(String msg, Component parent) static JTextArealongSmallMsg(String msg, String svgIconPath, boolean enabled, Component parent) static Stringstatic voidDisplays a floating notification in the upper corner of the active screen.static voidDisplays a floating notification in the upper corner of the active screen.static voidnotifyIfNewVersion(int msDelayBeforeShow) static voidnotifyIfOldVersion(int msDelayBeforeCheck) Checks for available SNT updates in the background by querying the Neuroanatomy update site.static voidstatic floatosScale()Returns the OS-level scale factor that is NOT already accounted for by Java's HiDPI awareness.static floatComponent-aware variant ofosScale(): uses the component's ownGraphicsConfigurationso the correct scale is returned on multi-monitor setups where screens may have different DPI.static voidremoveIcon(Object rootPaneContainerOrWindow) static StringscaledMicrometer(double umLength, int digits) Returns a more human-readable representation of a length in micrometers.voidsearchForum(String query) static voidsetAutoDismiss(JDialog dialog) static voidsetLocationRelativeTo(Window target, Window reference) Positions a target window relative to a reference window while preventing it from being hidden behind system docks, taskbars, or menu bars across macOS, Windows, and Linux.voidvoidstatic voidstatic voidsetSplashMessage(String message) Updates the loading splash screen's status text.static voidsetSplashStreamMode(boolean streamMode) Switches the loading splash screen to (or back from) its wider "SNT Stream" layout, for callers that will post longer, dynamic status messages viasetSplashMessage(String).static JLabelshortSmallMsg(String msg) static JLabelshortSmallMsg(String msg, boolean enabled) static JDialogstatic voidBrings the (scijava) console pane to frontvoidshowDirectory(File file) static voidshowHTMLDialog(String msg, String title) showHTMLDialog(String msg, String title, boolean modal) voidshowKeyboardShortcuts(InputMap[] inputMaps, ActionMap... actionMaps) Displays a sorted HTML table of all registered keyboard shortcuts in the specified inputMaps.voidvoidstatic voidstatic <T> Stringstatic floatstatic doubleuiScale()Returns the effective UI scale factor for the current display environment, accounting for HiDPI displays and user-configured scaling.voidintyesNoDialog(String msg, String title) intyesNoDialog(String msg, String title, String yesButtonLabel, String noButtonLabel) booleanyesNoHTMLDialog(String htmlMsg, String title, String yesLabel, String noLabel) org.scijava.ui.DialogPrompt.ResultyesNoPrompt(String message, String title)
-
Constructor Details
-
GuiUtils
-
GuiUtils
public GuiUtils()Create a new GuiUtils instance using active (focused) window as parent.
-
-
Method Details
-
setParentToActiveWindow
public void setParentToActiveWindow() -
setParent
-
error
-
error
-
warning
-
notifyIfNewVersion
public static void notifyIfNewVersion(int msDelayBeforeShow) -
notifyIfOldVersion
public static void notifyIfOldVersion(int msDelayBeforeCheck) Checks for available SNT updates in the background by querying the Neuroanatomy update site. If the site's content is newer than the local installation, a notification is displayed suggesting the user run the Fiji updater. Respects the Fiji updater's own preferences (e.g., "never remind me", "remind me later") and fails silently on any error (network, missing updater, etc.).- Parameters:
msDelayBeforeCheck- delay in ms before the background check starts
-
applyRoundCorners
-
floatingMsg
-
tempMsg
-
tempMsg
-
isLegacy3DViewerAvailable
public static boolean isLegacy3DViewerAvailable() -
notify
Displays a floating notification in the upper corner of the active screen.- Parameters:
msg- the message to be displayed. May include a minimal subset of Markdown for emphasis:**bold**/__bold__and*italic*/_italic_seeGuiUtils.Text.markdownToHtml(String). Anything else, including literal '<'/'>'/'&', is treated as plain text.- See Also:
-
notify
Displays a floating notification in the upper corner of the active screen.- Parameters:
msg- the message to be displayed. May include a minimal subset of Markdown for emphasis:**bold**/__bold__and*italic*/_italic_seeGuiUtils.Text.markdownToHtml(String). Anything else, including literal '<'/'>'/'&', is treated as plain text.msDelayBeforeShow- the amount (in ms) of time before notification should be displayed
-
getTimeStamp
-
yesNoDialog
-
yesNoDialog
-
yesNoPrompt
-
getConfirmation
-
error
-
getConfirmation
-
getConfirmation2
-
getChoice
-
getChoiceRaceable
public Optional<String> getChoiceRaceable(String message, String title, String[] choices, String defaultChoice, Future<?> task) throws InterruptedException LikegetChoice(String, String, String[], String), but the choices are shown as buttons and the prompt races a backgroundtask: if it completes before the user picks a button, the dialog is dismissed automatically/ Useful for "this is taking a while, keep waiting / open as-is / abort?" prompts wrapped around slow network fetches/- Parameters:
message- the prompt messagetitle- the dialog titlechoices- the button labels, shown in orderdefaultChoice- the button focused by default, ornullforchoices[0]task- the background task racing the prompt- Returns:
- the label of the button the user clicked, or
Optional.empty()iftaskcompleted on its own (or the dialog was closed without a button click) before the user answered - Throws:
InterruptedException- if the calling thread is interrupted while waiting
-
getTwoChoices
-
getChoiceWithInput
-
getChoiceAndDouble
-
getChoice
-
getMultipleChoices
-
getMultipleChoicesAndChoice
-
getPersistentConfirmation
-
getConfirmationAndOption
-
getConfirmationAndOption
-
getChoiceWithOptionAndInfo
public Object[] getChoiceWithOptionAndInfo(String title, String message, String[] choices, String defaultChoice, String infoText, String checkboxLabel, boolean checkboxDefault) Displays a dialog with radio button choices, optional info text, and an optional checkbox. Useful for operations that require a selection with additional context and options.- Parameters:
title- the dialog titlemessage- the message/prompt shown at the top (can be HTML)choices- array of choices to display as radio buttonsdefaultChoice- the initially selected choice (must be in choices array)infoText- optional informational text shown below the choices (null to hide)checkboxLabel- optional checkbox label (null to hide checkbox)checkboxDefault- default state of checkbox (ignored if checkboxLabel is null)- Returns:
- Object array: {selectedChoice (String), checkboxSelected (Boolean)}, or null if canceled. checkboxSelected is false if checkbox was hidden.
-
getPersistentWarning
-
getParent
-
getString
-
getStrings
-
getStrings
-
getStringSet
-
getColorRGB
public org.scijava.util.ColorRGB getColorRGB(String title, org.scijava.util.ColorRGB defaultValue, String... panes) Simplified color chooser for ColorRGB.- See Also:
-
getColor
Simplified color chooser.- Parameters:
title- the title of the chooser dialogdefaultValue- the initial color set in the chooserpanes- the panes a list of strings specifying which tabs should be displayed. In most platforms this includes: "Swatches", "HSB" and "RGB". Note that e.g., the GTK L&F may only include the default GtkColorChooser pane. Set to null to include all available panes.- Returns:
- the color
-
getDouble
-
getPercentage
-
getDouble
-
getInt
-
getTwoNumbers
-
getThreeNumbers
-
getCoordinates
-
getCoordinatesInternal
-
getRange
-
adjustComponentThroughPrompt
-
getOpenFile
-
getOpenFileOrDirectory
AsgetOpenFile(String, File, String...), but the dialog also allows selecting a directory directly. Needed for pointing directly at an N5/OME-Zarr container; a metadata file *inside* such a container (e.g.zarr.json,.zattrs) can still be selected too. Both resolve to the same container root,NB: unlike most
getXxxFile(s)methods above, this always uses the classic chooser and ignoresSNTPrefs.getUseNativeFileChooser()-- FlatLaf'sSystemFileChooser(the native alternative) does not support a mixed files-and-directories selection mode at all. -
getSaveFile
Shows a "Save" dialog, honoringSNTPrefs.getUseNativeFileChooser(): either SNT's classicFileChooseror FlatLaf'sSystemFileChooser(native OS dialog).- Parameters:
title- the dialog titlefile- a proposed file (name and/or directory) to pre-select, ornullallowedExtensions- the choosable extension(s) offered in the dialog's filter; if a single extension is given, it is appended to the chosen file if the user typed a name without it- Returns:
- the chosen
File, ornullif the dialog was cancelled
-
getReconstructionFiles
-
getFile
-
getImageFile
-
getReconstructionFile
-
fileChooser
-
centeredMsg
-
centeredMsg
-
dialog
-
centerOnParent
-
centerOnParent
-
setLocationRelativeTo
Positions a target window relative to a reference window while preventing it from being hidden behind system docks, taskbars, or menu bars across macOS, Windows, and Linux.Precondition: The target window must have its size initialized
- Parameters:
target- the window to be positioned (e.g., JFrame, JDialog); cannot be nullreference- the reference window to position relative to; if null or not visible, the target window centers on the primary screen launcher bounds
-
displayBanner
-
addTooltip
-
getWrappedText
Wrapstextin an HTML<div>capped atmaxWidth, so a long line wraps onto further lines instead of being clipped or silently growing its container. No-op iftextalready looks like HTML.- Parameters:
c- the component the text will be displayed in (used only for font metrics)text- the text to wrapmaxWidth- the maximum width, in pixels, of the wrapped text- Returns:
- the (possibly) HTML-wrapped text
-
blinkingError
-
shortSmallMsg
-
shortSmallMsg
-
longSmallMsg
-
longSmallMsg
-
showAboutDialog
-
showDirectory
-
toString
-
uiFontSize
public static float uiFontSize() -
uiScale
public static double uiScale()Returns the effective UI scale factor for the current display environment, accounting for HiDPI displays and user-configured scaling.The detection strategy is:
- FlatLaf's
UIScale.getUserScaleFactor()the most reliable source when FlatLaf is active, as it combines OS-level DPI with any user overrides - AWT's
GraphicsConfiguration.getDefaultTransform().getScaleX(), the platform-level fallback ij.Prefs.getGuiScale(): last resort
- Returns:
- the scale factor (1.0 = no scaling, 2.0 = 200%, etc.)
- FlatLaf's
-
osScale
public static float osScale()Returns the OS-level scale factor that is NOT already accounted for by Java's HiDPI awareness.On macOS and Windows, Java intercepts HiDPI natively: so this returns 1.0. On Linux with GDK_SCALE, the OS seems to scale everything before Java sees it: AWT/Swing stay at 1.0 scaling while
Uses the default screen device; preferuiScale()absorbs the GDK factor, so font sizes, etc. are in device pixels and must be divided by the returned value to reach FlatLaF logical units.osScale(Component)when a component is available so multi-monitor setups are handled correctly. -
osScale
Component-aware variant ofosScale(): uses the component's ownGraphicsConfigurationso the correct scale is returned on multi-monitor setups where screens may have different DPI. -
initSplashScreen
public static void initSplashScreen()Registers one more caller that wants the loading splash screen open, showing it if it is not already showing. Calls nest: the splash is only actually closed once everyinitSplashScreen()has been matched by acloseSplashScreen(). handled here -
setSplashMessage
Updates the loading splash screen's status text. Does nothing if the splash screen is not currently showing- Parameters:
message- the new status text
-
setSplashStreamMode
public static void setSplashStreamMode(boolean streamMode) Switches the loading splash screen to (or back from) its wider "SNT Stream" layout, for callers that will post longer, dynamic status messages viasetSplashMessage(String). Does nothing if the splash screen is not currently showing- Parameters:
streamMode- true for the wide "SNT Stream" layout, false for the default one
-
closeSplashScreen
public static void closeSplashScreen()Releases one registration made byinitSplashScreen(); the splash only actually closes once every such registration has been released - seeSplashScreen#close() -
addSeparator
public static void addSeparator(JComponent component, String heading, boolean vgap, GridBagConstraints c) -
addSeparator
public static void addSeparator(JComponent component, JLabel label, boolean vgap, GridBagConstraints c) -
addSeparator
-
addSeparator
-
leftAlignedLabel
-
leftAlignedLabel
-
leftAlignedLabel
AsleftAlignedLabel(String, String, boolean), but also (or instead of auri) running an in-app action on click -- e.g., for a label that should trigger something within the application, such as starting a wizard/tour, rather than (or in addition to) opening an external link.- Parameters:
text- the label's (HTML-formatted, if applicable) texturi- an optional URL to be opened on click, or nullaction- an optional action to be run on click (afteruri, if any, is opened), or nullenabled- whether the label starts off enabled (a disabled label ignores clicks)
-
searchForum
-
openURL
-
showKeyboardShortcuts
Displays a sorted HTML table of all registered keyboard shortcuts in the specified inputMaps. Action names are title-cased for readability.- Parameters:
inputMaps- The InputMap(s) to be listedactionMaps- If null, all key binding are listed, including those with no corresponding action (e.g. disabled or inherited Swing defaults) will be listed
-
ctrlKey
-
getConsole
-
showConsole
public static void showConsole()Brings the (scijava) console pane to front -
setRenderingHints
-
defaultGbc
-
removeIcon
-
enableComponents
-
ensureSameWidth
Resizes components so that they all share the same preferred/minimum width (the largest among them), while each component keeps its own height. Useful to align icon-driven controls (e.g., dropdown/options buttons) that live in unrelated panels but whose glyph-dependent widths would otherwise differ slightly- Parameters:
components- the components to resize; needs at least two to have an effect
-
micrometer
-
scaledMicrometer
Returns a more human-readable representation of a length in micrometers.E.g., scaledMicrometer(0.01,1) returns "1.0nm"
- Parameters:
umLength- the length in micrometersdigits- the number of output decimals- Returns:
- the scaled unit
-
errorPrompt
-
errorPrompt
-
friendlyErrorMessage
Rewrites a common network-connectivity exception (unknown host, refused/timed-out connection) into a short, user-facing message, instead of the exception's own message, which for e.g.UnknownHostExceptionis just the bare, unexplained hostname. Falls back tot.getMessage()for anything else.- Parameters:
t- the exception to inspect (its cause chain is also walked)- Returns:
- a friendly message describing
t
-
getDnDFileChooser
-
setAutoDismiss
-
tile
-
showHTMLDialog
-
showHTMLDialog
-
yesNoHTMLDialog
-
combineSNTChartPrompt
public void combineSNTChartPrompt() -
drawDragAndDropPlaceHolder
-
getTabbedPane
-
centerWindow
-
addCloseShortcut
-
closeAllPlots
public static void closeAllPlots()
-