Package nl.colorize.util.swing
Class SwingUtils
java.lang.Object
nl.colorize.util.swing.SwingUtils
Miscelleaneous 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 void
attachPseudoActionListener
(JComponent component, ActionListener listener) Attaches aMouseListener
to a Swing component and forwards "click" events to aActionListener
.static boolean
copyToClipboard
(String text) Copies the specified text to the system clipboard.static JPanel
createAddRemoveItemsPanel
(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 JPanel
createCustomGraphicsPanel
(BiConsumer<Graphics2D, Dimension> callback) Creates aJPanel
that uses the supplied callback function to draw its background graphics.static JButton
createHoverButton
(String label, Color hoverColor) Creates a button that does not follow the platform's UI conventions and changes foreground color on hover.static JPanel
createImagePanel
(BufferedImage image) Creates a new panel with contents consisting of the specified image.static KeyListener
createKeyPressedListener
(Consumer<KeyEvent> callback) Creates aKeyListener
that will only listen to key pressed events, and will invoke the specified callback when such events occur.static KeyListener
createKeyReleasedListener
(Consumer<KeyEvent> callback) Creates aKeyListener
that will only listen to key released events, and will invoke the specified callback when such events occur.static JLabel
createLabel
(String text, Font font, Color textColor) Creates a label with the specified font and color.static JMenuItem
createMenuItem
(JMenu parent, String label, int keycode) Creates a newJMenuItem
with the specified label and (optional) keyboard shortcut, and adds it to a menu.static JTextField
createNumericTextField
(float initialValue) Returns a text field that always returns a valid float when itsgetText()
method is called.static JTextField
createNumericTextField
(int initialValue) Returns a text field that always returns a valid integer when itsgetText()
method is called.static JButton
createOutlineButton
(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 ComponentListener
createResizeListener
(Runnable callback) Creates aComponentListener
that will only listen to component resize events, and will invoke the specified callback when such events occur.static JPanel
createSpacerPanel
(int width, int height) Creates aJPanel
without any visible contents and a transparent background.static JPanel
createSpacerPanel
(int width, int height, Color backgroundColor) Creates aJPanel
without any visible contents and a colored background.static <E> JList
<E> createStripedList
(List<E> elements) Creates aJTree
that paints rows in alternating background colors, if allowed by the platform's UI conventions.static JTree
createStripedTree
(DefaultTreeModel treeModel) Creates aJTree
that paints rows in alternating background colors, if allowed by the platform's UI conventions.static JButton
createTextButton
(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 JButton
createToolBarButton
(String label, BufferedImage icon) Creates a button suitable for usage in a toolbar.static JButton
createToolBarButton
(String label, ImageIcon icon) Creates a button suitable for usage in a toolbar.static void
doInBackground
(Runnable task, Runnable swingCallback) Performstask
in a background thread, and when done callsswingCallback
on the Swing thread.static String
findAvailableFontFamily
(String... requestedFontFamilies) Looks through the available font families and returns the first match fromrequestedFontFamilies
which is available on the system.static int
getAvailableHeight
(Container parent) Returns the width available to child components within a container.static int
getAvailableWidth
(Container parent) Returns the width available to child components within a container.static TranslationBundle
Returns the resource bundle containing the user interface text for all custom Swing components provided by this library.static float
Returns the platform's user interface scale factor.static KeyStroke
getKeyStroke
(int keycode) Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.static KeyStroke
getKeyStroke
(int keycode, boolean shift) Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.static Dimension
Returns the platform's current screen size.static int
getSelectedButton
(List<? extends AbstractButton> radioButtons) static int
getSelectedButton
(ButtonGroup buttonGroup) protected static Color
static Color
getStripedRowColor
(int rowIndex) Returns the appropriate row background color for components with a striped appearance, such as tables, lists, and trees.static void
goFullScreen
(JFrame window) Enables full-screen mode for the specified window.static void
Initializes Swing by selecting the best look-and-feel for the current platform.static boolean
Returns true if the current platform is a "headless" (non-graphical) environment, and AWT/Swing/JavaFX are not supported.static Font
loadFont
(InputStream input, int style, float size) Loads a TrueType font and returns it as an AWT font.static Font
loadFont
(ResourceFile file, int style, float size) Loads a TrueType font and returns it as an AWT font.static ImageIcon
loadIcon
(ResourceFile source) Loads an icon from the specified file.static Image
loadIconImage
(ResourceFile source) Loads an icon from the specified file, for use injavax.swing.JFrame#setIconImage(Image)
.static boolean
openBrowser
(String uri) Opens the platform's default browser with the specified URL.static boolean
Opens the specified file in the platform's default application for that file type.static void
removeLookAndFeel
(JButton button, boolean keepPadding) Removes the platform's default look-and-feel from a button.static void
setFocusable
(JComponent component, boolean focusable) CallsComponent.setFocusable(boolean)
recursively.static void
CallsJComponent.setFont(Font)
on a component and then recursively on its child component.static void
setOpaque
(JComponent component, boolean opaque) CallsJComponent.setOpaque(boolean)
recursively.static void
setPreferredHeight
(JComponent c, int height) Changes a component's preferred height without changing its preferred width.static void
setPreferredSize
(JComponent c, int width, int height) static void
setPreferredWidth
(JComponent c, int width) Changes a component's preferred width without changing its preferred height.static <T> ActionListener
toActionListener
(Consumer<T> callback, Supplier<T> arg) Returns anActionListener
that will invoke the specified callback function.static <T> ActionListener
toActionListener
(Consumer<T> callback, T arg) Returns anActionListener
that will invoke the specified callback function.static WindowListener
toCloseDelegate
(Runnable action) static MouseListener
toHoverListener
(Consumer<MouseEvent> enter, Consumer<MouseEvent> exit) Produces aMouseListener
that performs the specified actions when the mouse enters or exits the component.static KeyListener
toKeyReleasedListener
(Consumer<KeyEvent> callback) Returns aKeyListener
that forwardskeyReleased
events to the specified callback method.static MouseListener
toMouseReleasedListener
(Consumer<MouseEvent> callback) Returns aMouseListener
that forwardsmouseReleased
events to the specified callback method.static JScrollPane
wrapInScrollPane
(JComponent component) static JScrollPane
wrapInScrollPane
(JComponent component, boolean flexibleScrollBars) static JScrollPane
wrapInScrollPane
(JComponent component, int height) static JScrollPane
wrapInScrollPane
(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
Creates a newJMenuItem
with 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_X
fields, or -1 for none.- Returns:
- The menu item that was created and added to the menu.
-
getKeyStroke
Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.- Parameters:
keycode
- One of theKeyEvent.VK_X
fields, 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_X
fields, 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
- ifuri
is 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
Performstask
in a background thread, and when done callsswingCallback
on the Swing thread. -
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
Creates aJPanel
without any visible contents and a transparent background.- Parameters:
width
- Preferred width, or -1 for default.height
- Preferred height, or -1 for default.
-
createSpacerPanel
Creates aJPanel
without any visible contents and a colored background.- Parameters:
width
- Preferred width, or -1 for default.height
- Preferred height, or -1 for default.
-
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 fromrequestedFontFamilies
which 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 aMouseListener
to a Swing component and forwards "click" events to aActionListener
. This can be used to make non-button components still behave like buttons. -
toActionListener
Returns anActionListener
that will invoke the specified callback function.- Parameters:
arg
- The argument that will be passed to the callback function.
-
toActionListener
Returns anActionListener
that will invoke the specified callback function. The argument to the callback function is provided byarg
supplier every time an action is performed. -
toKeyReleasedListener
Returns aKeyListener
that forwardskeyReleased
events to the specified callback method. -
toMouseReleasedListener
Returns aMouseListener
that forwardsmouseReleased
events to the specified callback method. -
createAddRemoveItemsPanel
@Deprecated public static JPanel createAddRemoveItemsPanel(Supplier<List<String>> itemSupplier, String header, Consumer<String> addButtonAction, Consumer<String> removeButtonAction) Deprecated.UsePropertyEditor
instead.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
Creates a label with the specified font and color. If the font isnull
the label will use the platform's default font for the current look-and-feel. -
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. -
createKeyPressedListener
Creates aKeyListener
that will only listen to key pressed events, and will invoke the specified callback when such events occur. -
createKeyReleasedListener
Creates aKeyListener
that will only listen to key released events, and will invoke the specified callback when such events occur. -
createResizeListener
Creates aComponentListener
that 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
Creates a button that does not follow the platform's UI conventions and changes foreground color on hover. -
createOutlineButton
Creates a button that does not follow the platform's UI conventions, but only consists of a text label and an outline. -
createTextButton
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. -
toHoverListener
Produces aMouseListener
that 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 aJPanel
that 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
Creates aJTree
that paints rows in alternating background colors, if allowed by the platform's UI conventions. -
createStripedTree
Creates aJTree
that paints rows in alternating background colors, if allowed by the platform's UI conventions.
-
PropertyEditor
instead.