Class SwingUtils
java.lang.Object
nl.colorize.util.swing.SwingUtils
Miscellaneous utility and convenience methods for working with Swing. This
generally relates to creating component with slightly different graphics
and/or behavior.
-
Method Summary
Modifier and TypeMethodDescriptionstatic voidattachPseudoActionListener(JComponent component, ActionListener listener) Attaches aMouseListenerto a Swing component and forwards "click" events to aActionListener.static booleancopyToClipboard(String text) Copies the specified text to the system clipboard.static JPanelcreateAddRemoveItemsPanel(Supplier<List<String>> itemSupplier, String header, Consumer<String> addButtonAction, Consumer<String> removeButtonAction) Deprecated.createComboBox(Collection<T> items, T selected) createComboBox(T[] items, T selected) static JPanelcreateCustomGraphicsPanel(BiConsumer<Graphics2D, Dimension> callback) Creates aJPanelthat uses the supplied callback function to draw its background graphics.static JButtoncreateHoverButton(String label, Color hoverColor) Creates a button that does not follow the platform's UI conventions and changes foreground color on hover.static JPanelcreateImagePanel(BufferedImage image) Creates a new panel with contents consisting of the specified image.static KeyListenercreateKeyPressedListener(Consumer<KeyEvent> callback) Creates aKeyListenerthat will only listen to key pressed events, and will invoke the specified callback when such events occur.static KeyListenercreateKeyReleasedListener(Consumer<KeyEvent> callback) Creates aKeyListenerthat will only listen to key released events, and will invoke the specified callback when such events occur.static JLabelcreateLabel(String text, Font font, Color textColor) Creates a label with the specified font and color.static JMenuItemcreateMenuItem(String label, int keycode, Runnable action) Returns a new menu item that will perform the specified action.static JMenuItemcreateMenuItem(String label, Runnable action) Returns a new menu item that will perform the specified action.static JMenuItemcreateMenuItem(JMenu parent, String label, int keycode) Deprecated.static JTextFieldcreateNumericTextField(float initialValue) Returns a text field that always returns a valid float when itsgetText()method is called.static JTextFieldcreateNumericTextField(int initialValue) Returns a text field that always returns a valid integer when itsgetText()method is called.static JButtoncreateOutlineButton(String label, Color normalColor, Color hoverColor) Creates a button that does not follow the platform's UI conventions, but only consists of a text label and an outline.static ComponentListenercreateResizeListener(Runnable callback) Creates aComponentListenerthat will only listen to component resize events, and will invoke the specified callback when such events occur.static JPanelcreateSpacerPanel(int width, int height) Creates aJPanelwithout any visible contents and a transparent background.static JPanelcreateSpacerPanel(int width, int height, Color backgroundColor) Creates aJPanelwithout any visible contents and a colored background.static <E> JList<E> createStripedList(List<E> elements) Creates aJTreethat paints rows in alternating background colors, if allowed by the platform's UI conventions.static JTreecreateStripedTree(DefaultTreeModel treeModel) Creates aJTreethat paints rows in alternating background colors, if allowed by the platform's UI conventions.static JButtoncreateTextButton(String label, Font font, Color color, Color highlight) Creates a button that does not use the platform's normal look-and-feel, and instead only consists of a text link in the specified color.static JButtoncreateToolBarButton(String label, BufferedImage icon) Creates a button suitable for usage in a toolbar.static JButtoncreateToolBarButton(String label, ImageIcon icon) Creates a button suitable for usage in a toolbar.static voiddoInBackground(Runnable task, Runnable swingCallback) Performstaskin a background thread, and when done callsswingCallbackon the Swing thread.static StringfindAvailableFontFamily(String... requestedFontFamilies) Looks through the available font families and returns the first match fromrequestedFontFamilieswhich is available on the system.static intgetAvailableHeight(Container parent) Returns the width available to child components within a container.static intgetAvailableWidth(Container parent) Returns the width available to child components within a container.static TranslationBundleReturns the resource bundle containing the user interface text for all custom Swing components provided by this library.static floatReturns the platform's user interface scale factor.static KeyStrokegetKeyStroke(int keycode) Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.static KeyStrokegetKeyStroke(int keycode, boolean shift) Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.static DimensionReturns the platform's current screen size.static intgetSelectedButton(List<? extends AbstractButton> radioButtons) static intgetSelectedButton(ButtonGroup buttonGroup) protected static Colorstatic ColorgetStripedRowColor(int rowIndex) Returns the appropriate row background color for components with a striped appearance, such as tables, lists, and trees.static voidgoFullScreen(JFrame window) Enables full-screen mode for the specified window.static voidInitializes Swing by selecting the best look-and-feel for the current platform.static booleanReturns true if the current platform is a "headless" (non-graphical) environment, and AWT/Swing/JavaFX are not supported.static FontloadFont(InputStream input, int style, float size) Loads a TrueType font and returns it as an AWT font.static FontloadFont(ResourceFile file, int style, float size) Loads a TrueType font and returns it as an AWT font.static ImageIconloadIcon(ResourceFile source) Loads an icon from the specified file.static ImageloadIconImage(ResourceFile source) Loads an icon from the specified file, for use injavax.swing.JFrame#setIconImage(Image).static booleanopenBrowser(String uri) Opens the platform's default browser with the specified URL.static booleanOpens the specified file in the platform's default application for that file type.static voidremoveLookAndFeel(JButton button, boolean keepPadding) Removes the platform's default look-and-feel from a button.static voidsetFocusable(JComponent component, boolean focusable) CallsComponent.setFocusable(boolean)recursively.static voidCallsJComponent.setFont(Font)on a component and then recursively on its child component.static voidsetOpaque(JComponent component, boolean opaque) CallsJComponent.setOpaque(boolean)recursively.static voidsetPreferredHeight(JComponent c, int height) Changes a component's preferred height without changing its preferred width.static voidsetPreferredSize(JComponent c, int width, int height) static voidsetPreferredWidth(JComponent c, int width) Changes a component's preferred width without changing its preferred height.static <T> ActionListenertoActionListener(Consumer<T> callback, Supplier<T> arg) Returns anActionListenerthat will invoke the specified callback function.static <T> ActionListenertoActionListener(Consumer<T> callback, T arg) Returns anActionListenerthat will invoke the specified callback function.static WindowListenertoCloseDelegate(Runnable action) static MouseListenertoHoverListener(Consumer<MouseEvent> enter, Consumer<MouseEvent> exit) Produces aMouseListenerthat performs the specified actions when the mouse enters or exits the component.static KeyListenertoKeyReleasedListener(Consumer<KeyEvent> callback) Returns aKeyListenerthat forwardskeyReleasedevents to the specified callback method.static MouseListenertoMouseReleasedListener(Consumer<MouseEvent> callback) Returns aMouseListenerthat forwardsmouseReleasedevents to the specified callback method.static JScrollPanewrapInScrollPane(JComponent component) static JScrollPanewrapInScrollPane(JComponent component, boolean flexibleScrollBars) static JScrollPanewrapInScrollPane(JComponent component, int height) static JScrollPanewrapInScrollPane(JComponent component, int width, int height)
-
Method Details
-
isHeadlessEnvironment
public static boolean isHeadlessEnvironment()Returns true if the current platform is a "headless" (non-graphical) environment, and AWT/Swing/JavaFX are not supported. -
initializeSwing
public static void initializeSwing()Initializes Swing by selecting the best look-and-feel for the current platform. On macOS this method also changes system properties so that menus appear at the top of the screen, instead of inside the window.This method must be called before the first window is shown.
- Throws:
RuntimeException- if changing the look-and-feel fails.
-
getCustomComponentsBundle
Returns the resource bundle containing the user interface text for all custom Swing components provided by this library. This bundle can be used to change and/or translate the text. -
getScreenSize
Returns the platform's current screen size. If the platform has multiple screens this will return the size of the primary screen. If the platform has no screens, or if the screen size cannot be determined, this method will return dimensions of 0x0. -
goFullScreen
Enables full-screen mode for the specified window. If native fullscreen mode is not supported by the current platform, this will instead maximize the window. -
loadIcon
Loads an icon from the specified file.- Throws:
RuntimeException- if no icon could be created from the file's contents.
-
loadIconImage
Loads an icon from the specified file, for use injavax.swing.JFrame#setIconImage(Image).- Throws:
RuntimeException- if no icon could be created from the file's contents.
-
loadFont
public static Font loadFont(InputStream input, int style, float size) throws IOException, FontFormatException Loads a TrueType font and returns it as an AWT font.- Throws:
IOException- if the font could not be loaded from the file.FontFormatException- if the file is not a valid TrueType font.
-
loadFont
public static Font loadFont(ResourceFile file, int style, float size) throws IOException, FontFormatException Loads a TrueType font and returns it as an AWT font.- Throws:
IOException- if the font could not be loaded from the file.FontFormatException- if the file is not a valid TrueType font.
-
createMenuItem
Deprecated.Creates a newJMenuItemwith the specified label and (optional) keyboard shortcut, and adds it to a menu.- Parameters:
parent- The new menu item will be added to this menu.label- The menu item's text label.keycode- One of theKeyEvent.VK_Xfields, or -1 for none.- Returns:
- The menu item that was created and added to the menu.
-
createMenuItem
-
createMenuItem
-
getKeyStroke
Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.- Parameters:
keycode- One of theKeyEvent.VK_Xfields, or -1 for none.
-
getKeyStroke
Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.- Parameters:
keycode- One of theKeyEvent.VK_Xfields, or -1 for none.
-
openBrowser
Opens the platform's default browser with the specified URL. If the platform has no browser or doesn't allow access to it this method does nothing. Returns false if the browser could not be opened.- Throws:
IllegalArgumentException- ifuriis not a valid URI.
-
openFile
Opens the specified file in the platform's default application for that file type. Returns false if the file could not be opened.- Throws:
IllegalArgumentException- if the provided file does not exist.
-
copyToClipboard
Copies the specified text to the system clipboard. If the platform does not have a clipboard or doesn't allow access to it this method does nothing.- Returns:
- True if the text was copied to the clipboard.
-
doInBackground
-
setPreferredWidth
Changes a component's preferred width without changing its preferred height. -
setPreferredHeight
Changes a component's preferred height without changing its preferred width. -
setPreferredSize
-
createSpacerPanel
-
createSpacerPanel
-
setOpaque
CallsJComponent.setOpaque(boolean)recursively. -
setFocusable
CallsComponent.setFocusable(boolean)recursively. -
setFont
CallsJComponent.setFont(Font)on a component and then recursively on its child component. -
toCloseDelegate
-
wrapInScrollPane
-
wrapInScrollPane
-
wrapInScrollPane
-
wrapInScrollPane
-
getAvailableWidth
Returns the width available to child components within a container. This excludes insets and other space used by the platform's look-and-feel. -
getAvailableHeight
Returns the width available to child components within a container. This excludes insets and other space used by the platform's look-and-feel. -
getSelectedButton
-
getSelectedButton
-
removeLookAndFeel
Removes the platform's default look-and-feel from a button.- Parameters:
keepPadding- If true, retains the padding the look-and-feel would normally leave around the button's text and icon.
-
findAvailableFontFamily
Looks through the available font families and returns the first match fromrequestedFontFamilieswhich is available on the system. If there are no matches the default font family of "SansSerif" (which is guaranteed to be available by Swing) is returned. -
attachPseudoActionListener
Attaches aMouseListenerto a Swing component and forwards "click" events to aActionListener. This can be used to make non-button components still behave like buttons. -
toActionListener
Returns anActionListenerthat will invoke the specified callback function.- Parameters:
arg- The argument that will be passed to the callback function.
-
toActionListener
Returns anActionListenerthat will invoke the specified callback function. The argument to the callback function is provided byargsupplier every time an action is performed. -
toKeyReleasedListener
Returns aKeyListenerthat forwardskeyReleasedevents to the specified callback method. -
toMouseReleasedListener
Returns aMouseListenerthat forwardsmouseReleasedevents to the specified callback method. -
createAddRemoveItemsPanel
@Deprecated public static JPanel createAddRemoveItemsPanel(Supplier<List<String>> itemSupplier, String header, Consumer<String> addButtonAction, Consumer<String> removeButtonAction) Deprecated.UsePropertyEditorinstead.Creates a component that consists of a list of items, plus buttons to add and/or remove items. Changes made using those buttons are immediately reflected in the list of items. After using one of the buttons the list is automatically updated.- Parameters:
itemSupplier- Used to populate the list of items, both initially and after updates.addButtonAction- Performed when the add button is used.removeButtonAction- Performed when the remove button is used.
-
createLabel
-
createToolBarButton
-
createKeyPressedListener
Creates aKeyListenerthat will only listen to key pressed events, and will invoke the specified callback when such events occur. -
createKeyReleasedListener
Creates aKeyListenerthat will only listen to key released events, and will invoke the specified callback when such events occur. -
createResizeListener
Creates aComponentListenerthat will only listen to component resize events, and will invoke the specified callback when such events occur. -
createToolBarButton
Creates a button suitable for usage in a toolbar. The size of the button and the size of the icon will depend on the platform's user interface conventions. -
createHoverButton
-
createOutlineButton
-
createTextButton
-
toHoverListener
Produces aMouseListenerthat performs the specified actions when the mouse enters or exits the component. -
createComboBox
-
createComboBox
-
createNumericTextField
Returns a text field that always returns a valid integer when itsgetText()method is called. If the value that was actually entered is not a number it will return 0 instead. -
createNumericTextField
Returns a text field that always returns a valid float when itsgetText()method is called. If the value that was actually entered is not a number it will return 0 instead. -
createCustomGraphicsPanel
Creates aJPanelthat uses the supplied callback function to draw its background graphics. The callback takes two arguments: the panel's graphics and the panel's dimensions. -
createImagePanel
Creates a new panel with contents consisting of the specified image. The image will be drawn at its original size, and the panel's dimensions will be set accordingly. -
getDesktopScaleFactor
public static float getDesktopScaleFactor()Returns the platform's user interface scale factor. On Mac, this always returns 1.0 because Mac OS applies a consistent scale factor to the entire desktop. On Windows, desktop resolution/scale factor and UI scale factor are two independent settings.This method returns the UI scale factor for the default screen. This could be different from the screen that is going to display the application, but we don't know this yet because this method is called before the window is even created.
-
getStripedRowColor
Returns the appropriate row background color for components with a striped appearance, such as tables, lists, and trees. -
getStripedRowBorderColor
-
createStripedList
-
createStripedTree
Creates aJTreethat paints rows in alternating background colors, if allowed by the platform's UI conventions.
-
PropertyEditorinstead.