Class SwingUtils

java.lang.Object
nl.colorize.util.swing.SwingUtils

public final class SwingUtils extends Object
Miscelleaneous utility and convenience methods for working with Swing. This generally relates to creating component with slightly different graphics and/or behavior.
  • 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

      public static TranslationBundle 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

      public static Dimension 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

      public static void goFullScreen(JFrame window)
      Enables full-screen mode for the specified window.
    • loadIcon

      public static ImageIcon loadIcon(ResourceFile source)
      Loads an icon from the specified file.
      Throws:
      RuntimeException - if no icon could be created from the file's contents.
    • loadIconImage

      public static Image loadIconImage(ResourceFile source)
      Loads an icon from the specified file, for use in javax.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

      public static JMenuItem createMenuItem(JMenu parent, String label, int keycode)
      Creates a new JMenuItem 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 the KeyEvent.VK_X fields, or -1 for none.
      Returns:
      The menu item that was created and added to the menu.
    • getKeyStroke

      public static KeyStroke getKeyStroke(int keycode, boolean shift)
      Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.
      Parameters:
      keycode - One of the KeyEvent.VK_X fields, or -1 for none.
    • getKeyStroke

      public static KeyStroke getKeyStroke(int keycode)
      Returns a keystroke for a key that uses the platform-specific modifier key for menu shortcuts.
      Parameters:
      keycode - One of the KeyEvent.VK_X fields, or -1 for none.
    • openBrowser

      public static boolean openBrowser(String uri)
      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 - if uri is not a valid URI.
    • openFile

      public static boolean openFile(File file)
      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

      public static boolean copyToClipboard(String text)
      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

      public static void doInBackground(Runnable task, Runnable swingCallback)
      Performs task in a background thread, and when done calls swingCallback on the Swing thread.
    • setPreferredWidth

      public static void setPreferredWidth(JComponent c, int width)
      Changes a component's preferred width without changing its preferred height.
    • setPreferredHeight

      public static void setPreferredHeight(JComponent c, int height)
      Changes a component's preferred height without changing its preferred width.
    • setPreferredSize

      public static void setPreferredSize(JComponent c, int width, int height)
    • createSpacerPanel

      public static JPanel createSpacerPanel(int width, int height)
      Creates a JPanel without any visible contents and a transparent background.
      Parameters:
      width - Preferred width, or -1 for default.
      height - Preferred height, or -1 for default.
    • createSpacerPanel

      public static JPanel createSpacerPanel(int width, int height, Color backgroundColor)
      Creates a JPanel without any visible contents and a colored background.
      Parameters:
      width - Preferred width, or -1 for default.
      height - Preferred height, or -1 for default.
    • setOpaque

      public static void setOpaque(JComponent component, boolean opaque)
    • setFocusable

      public static void setFocusable(JComponent component, boolean focusable)
    • setFont

      public static void setFont(JPanel component, Font font)
      Calls JComponent.setFont(Font) on a component and then recursively on its child component.
    • toCloseDelegate

      public static WindowListener toCloseDelegate(Runnable action)
    • wrapInScrollPane

      public static JScrollPane wrapInScrollPane(JComponent component, boolean flexibleScrollBars)
    • wrapInScrollPane

      public static JScrollPane wrapInScrollPane(JComponent component)
    • wrapInScrollPane

      public static JScrollPane wrapInScrollPane(JComponent component, int height)
    • wrapInScrollPane

      public static JScrollPane wrapInScrollPane(JComponent component, int width, int height)
    • getAvailableWidth

      public static int getAvailableWidth(Container parent)
      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

      public static int getAvailableHeight(Container parent)
      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

      public static int getSelectedButton(List<? extends AbstractButton> radioButtons)
    • getSelectedButton

      public static int getSelectedButton(ButtonGroup buttonGroup)
    • removeLookAndFeel

      public static void removeLookAndFeel(JButton button, boolean keepPadding)
      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

      public static String findAvailableFontFamily(String... requestedFontFamilies)
      Looks through the available font families and returns the first match from requestedFontFamilies 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

      public static void attachPseudoActionListener(JComponent component, ActionListener listener)
      Attaches a MouseListener to a Swing component and forwards "click" events to a ActionListener. This can be used to make non-button components still behave like buttons.
    • toActionListener

      public static <T> ActionListener toActionListener(Consumer<T> callback, T arg)
      Returns an ActionListener that will invoke the specified callback function.
      Parameters:
      arg - The argument that will be passed to the callback function.
    • toActionListener

      public static <T> ActionListener toActionListener(Consumer<T> callback, Supplier<T> arg)
      Returns an ActionListener that will invoke the specified callback function. The argument to the callback function is provided by arg supplier every time an action is performed.
    • toKeyReleasedListener

      public static KeyListener toKeyReleasedListener(Consumer<KeyEvent> callback)
      Returns a KeyListener that forwards keyReleased events to the specified callback method.
    • toMouseReleasedListener

      public static MouseListener toMouseReleasedListener(Consumer<MouseEvent> callback)
      Returns a MouseListener that forwards mouseReleased 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.
      Use PropertyEditor 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

      public static JLabel createLabel(String text, Font font, Color textColor)
      Creates a label with the specified font and color. If the font is null the label will use the platform's default font for the current look-and-feel.
    • createToolBarButton

      public static JButton createToolBarButton(String label, ImageIcon icon)
      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

      public static KeyListener createKeyPressedListener(Consumer<KeyEvent> callback)
      Creates a KeyListener that will only listen to key pressed events, and will invoke the specified callback when such events occur.
    • createKeyReleasedListener

      public static KeyListener createKeyReleasedListener(Consumer<KeyEvent> callback)
      Creates a KeyListener that will only listen to key released events, and will invoke the specified callback when such events occur.
    • createResizeListener

      public static ComponentListener createResizeListener(Runnable callback)
      Creates a ComponentListener that will only listen to component resize events, and will invoke the specified callback when such events occur.
    • createToolBarButton

      public static JButton createToolBarButton(String label, BufferedImage icon)
      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

      public 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.
    • createOutlineButton

      public 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.
    • createTextButton

      public 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.
    • toHoverListener

      public static MouseListener toHoverListener(Consumer<MouseEvent> enter, Consumer<MouseEvent> exit)
      Produces a MouseListener that performs the specified actions when the mouse enters or exits the component.
    • createComboBox

      public static <T> JComboBox<String> createComboBox(Collection<T> items, T selected)
    • createComboBox

      public static <T> JComboBox<String> createComboBox(T[] items, T selected)
    • createNumericTextField

      public static JTextField createNumericTextField(int initialValue)
      Returns a text field that always returns a valid integer when its getText() method is called. If the value that was actually entered is not a number it will return 0 instead.
    • createNumericTextField

      public static JTextField createNumericTextField(float initialValue)
      Returns a text field that always returns a valid float when its getText() method is called. If the value that was actually entered is not a number it will return 0 instead.
    • createCustomGraphicsPanel

      public static JPanel createCustomGraphicsPanel(BiConsumer<Graphics2D,Dimension> callback)
      Creates a JPanel 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

      public static JPanel createImagePanel(BufferedImage image)
      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

      public static Color getStripedRowColor(int rowIndex)
      Returns the appropriate row background color for components with a striped appearance, such as tables, lists, and trees.
    • getStripedRowBorderColor

      protected static Color getStripedRowBorderColor()
    • createStripedList

      public static <E> JList<E> createStripedList(List<E> elements)
      Creates a JTree that paints rows in alternating background colors, if allowed by the platform's UI conventions.
    • createStripedTree

      public static JTree createStripedTree(DefaultTreeModel treeModel)
      Creates a JTree that paints rows in alternating background colors, if allowed by the platform's UI conventions.