Package swingtree

Class UI


public final class UI extends UIFactoryMethods
This class is a static API for exposing swing tree builder types for wrapping and assembling various JComponent types to form a UI tree. Instances of these builder type expose an API based on chained methods designed around functional interfaces to enable building UI tree structures for Swing in an HTML-like nested fashion while also keeping a high degree of control and transparency by peeking into the underlying swing components or registering user actions through lambdas. Swing tree works especially well alongside MigLayouts, which is why this general purpose LayoutManager is integrated into this library. Simply pass String constraints to the UIForAnySwing.withLayout(String, String) and any given UIForAnySwing.add(String, UIForAnySwing[]) method or variant of, to make use of mig layouts.

Please take a look at the living swing-tree documentation where you can browse a large collection of examples demonstrating how to use the API of this class.

  • Method Details

    • currentLookAndFeel

      public static UI.LookAndFeel currentLookAndFeel()
      SwingTree tries to be compatible with different look and feels, which is why it maintains a set of constants for the most common look and feels through the UI.LookAndFeel enum. This method returns the current look and feel of the application or UI.LookAndFeel.OTHER if the look and feel is not recognized.
      Returns:
      One of or UI.LookAndFeel.OTHER if none of the above was recognized.
    • scale

      public static float scale()
      There are two types of strategies for achieving high DPI scaling in Swing. The first one is available since Java 9, and it uses the system property sun.java2d.uiScale to scale the AffineTransform of the Graphics2D graphics context. The second one is look and feel / client code dependent scaling, which is what this library uses.

      The factor returned by this method is determined by SwingTree automatically to ensure that the UI is DPI aware. All the SwingTree styles are scaled using this factor. Use this factor to scale your Graphics2D based painting operations. For configuring the scaling factor, see SwingTree.setUiScaleFactor(float) or SwingTree.initialiseUsing(SwingTreeConfigurator).

      Returns:
      The current UI scale factor, which is used for DPI aware painting and layouts.
    • scale

      public static float scale(float value)
      Multiplies the given float value by the user scale factor. See SwingTree for more information about how the user scale factor is determined.
      Parameters:
      value - The float value to scale.
      Returns:
      The scaled float value.
    • scale

      public static double scale(double value)
      Multiplies the given double value by the user scale factor. See SwingTree for more information about how the user scale factor is determined.
      Parameters:
      value - The double value to scale.
      Returns:
      The scaled double value.
    • scale

      public static int scale(int value)
      Multiplies the given int value by the user scale factor and rounds the result. See SwingTree for more information about how the user scale factor is determined.
      Parameters:
      value - The int value to scale.
      Returns:
      The scaled int value.
    • scaleRoundedDown

      public int scaleRoundedDown(int value)
      Similar as scale(int) but always "rounds down".

      For use in special cases. scale(int) is the preferred method.

      Parameters:
      value - The value to scale and then round down if the scaled result is not a whole number.
      Returns:
      The scaled and rounded down value.
    • unscale

      public static float unscale(float value)
      Divides the given float value by the user scale factor. See SwingTree for more information about how the user scale factor is determined.
      Parameters:
      value - The float value to unscale.
      Returns:
      The unscaled float value.
    • unscale

      public static int unscale(int value)
      Divides the given int value by the user scale factor and rounds the result. See SwingTree for more information about how the user scale factor is determined.
      Parameters:
      value - The int value to unscale.
      Returns:
      The unscaled int value.
    • scale

      public static void scale(Graphics2D g)
      If user scale factor is not 1, scale the given graphics context by invoking Graphics2D.scale(double, double) with user scale factor. See SwingTree for more information about how the user scale factor is determined.
      Parameters:
      g - The graphics context to scale.
    • scale

      public static Dimension scale(Dimension dimension)
      Scales the given dimension with the user scale factor.

      If user scale factor is 1, then the given dimension is simply returned. Otherwise, a new instance of Dimension or DimensionUIResource is returned, depending on whether the passed dimension implements UIResource. See SwingTree for more information about how the user scale factor is determined.

      Parameters:
      dimension - The dimension to scale.
      Returns:
      The scaled dimension.
    • scale

      public static Rectangle scale(Rectangle rectangle)
      Returns a rectangle from the given rectangle with the user scale factor applied.

      If user scale factor is 1, then the given rectangle is simply returned. Otherwise, a new instance of Rectangle or UIResource is returned. See SwingTree for more information about how the user scale factor is determined.

      Parameters:
      rectangle - The rectangle to scale.
      Returns:
      The scaled rectangle.
    • scale

      public static RoundRectangle2D scale(RoundRectangle2D rectangle)
      Returns a rectangle from the given rectangle with the user scale factor applied.

      If user scale factor is 1, then the given rectangle is simply returned. Otherwise, a new instance of Rectangle or UIResource is returned. See SwingTree for more information about how the user scale factor is determined.

      Parameters:
      rectangle - The rectangle to scale.
      Returns:
      The scaled rectangle.
    • scale

      public static Ellipse2D scale(Ellipse2D ellipse)
      Takes an ellipse and scales it with the user scale factor or returns the provided ellipse if the user scale factor is 1.
      Parameters:
      ellipse - The ellipse to scale to the current UI scale factor.
      Returns:
      The scaled ellipse.
    • scale

      public static Insets scale(Insets insets)
      Scales the given insets with the user scale factor.

      If user scale factor is 1, then the given insets is simply returned. Otherwise, a new instance of Insets or InsetsUIResource is returned, depending on whether the passed dimension implements UIResource.

      Parameters:
      insets - The insets to scale.
      Returns:
      The scaled insets.
    • run

      public static void run(Runnable runnable)
      A convenience method for
      
            if ( !UI.thisIsUIThread() )
                SwingUtilities.invokeLater(runnable);
            else
                runnable.run();
       
      , which causes runnable.run() to be executed asynchronously on the AWT event dispatching thread if this current thread is not already the AWT thread. The 'invokeLater' execution will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.
      Parameters:
      runnable - the instance of Runnable
      See Also:
    • runLater

      public static void runLater(Runnable runnable)
      A convenience method for SwingUtilities.invokeLater(Runnable), which causes a provided Runnable to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI. In the following example the runLater call queues the Runnable lambda on the event dispatching thread and then prints a message.
      
        UI.run( () -> System.out.println("Hello World on " + Thread.currentThread()) );
        System.out.println("This might well be displayed before the other message.");
       
      If runLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the Runnable will still be deferred until all pending events have been processed. Note that if the Runnable throws an uncaught exception the event dispatching thread will unwind (not the current thread).
      Parameters:
      runnable - the instance of Runnable
      See Also:
    • runLater

      public static void runLater(int delay, Runnable runnable)
      A convenience method for SwingUtilities.invokeLater(Runnable), which causes Runnable to be executed asynchronously on the AWT event dispatching thread after the specified delay. This method should be used when an application thread needs to update the GUI after a particular delay. In the following example the invokeLater call queues the Runnable lambda containing a print statement on the event dispatching thread and then prints a message.
      
        UI.runLater( 1000, () -> System.out.println("Hello World on " + Thread.currentThread()) );
        System.out.println("This might well be displayed before the other message.");
       
      If runLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the Runnable will still be deferred until the specified delay has passed. Note that if the Runnable throws an uncaught exception the event dispatching thread will unwind (not the current thread).
      Parameters:
      delay - The delay in milliseconds.
      runnable - the instance of Runnable
      See Also:
    • runLater

      public static void runLater(double delay, TimeUnit unit, Runnable runnable)
      A convenience method for SwingUtilities.invokeLater(Runnable), which causes Runnable to be executed asynchronously on the AWT event dispatching thread after the specified delay has passed in the given time unit. This method should be used when an application thread needs to update the GUI after a particular delay. In the following example the invokeLater call queues the Runnable lambda containing a print statement on the event dispatching thread and then prints a message.
      
        UI.runLater( 1000, TimeUnit.MILLISECONDS, () -> System.out.println("Hello World on " + Thread.currentThread()) );
        System.out.println("This might well be displayed before the other message.");
       
      If runLater is called from the event dispatching thread -- for example, from a JButton's ActionListener -- the Runnable will still be deferred until the specified delay has passed. Note that if the Runnable throws an uncaught exception the event dispatching thread will unwind (not the current thread).
      Parameters:
      delay - The delay in the given time unit.
      unit - The time unit of the delay parameter.
      runnable - the instance of Runnable
      See Also:
    • thisIsUIThread

      public static boolean thisIsUIThread()
      Returns true if the current thread is an AWT event dispatching thread.

      This method is just a cover for javax.swing.SwingUtilities.isEventDispatchThread() and indirectly also for java.awt.EventQueue.isDispatchThread().

      Returns:
      true if the current thread is an AWT event dispatching thread
    • runNow

      public static void runNow(Runnable runnable)
      A convenience method for SwingUtilities.invokeAndWait(Runnable), causes doRun.run() to be executed synchronously on the AWT event dispatching thread. This call blocks until all pending AWT events have been processed and (then) doRun.run() returns. This method should be used when an application thread needs to update the GUI. It shouldn't be called from the event dispatching thread. Here's an example that creates a new application thread that uses invokeAndWait to print a string from the event dispatching thread and then, when that's finished, print a string from the application thread.
      
           var appThread = new Thread(() -> {
                   try {
                       UI.runNow(() -> {
                          System.out.println("Hello World on " + Thread.currentThread());
                       });
                   }
                   catch (Exception e) {
                       e.printStackTrace();
                   }
                   System.out.println("Finished on " + Thread.currentThread());
               });
      
           appThread.start();
       
      Note that contrary to the SwingUtilities.invokeAndWait(Runnable) method, this method does not throw an exception if it is called from the event dispatching thread. Instead, it just executes the runnable immediately.
      Parameters:
      runnable - the instance of Runnable
      See Also:
    • runAndGet

      public static <T> T runAndGet(Supplier<T> supplier)
      A convenience method for SwingUtilities.invokeAndWait(Runnable), where the runnable is a lambda expression that has a return value. This causes the Supplier to be executed synchronously on the AWT event dispatching thread. This call blocks until all pending AWT events have been processed and (then) the Supplier returns. This method should be used when an application thread needs to update the GUI a get a return value from the GUI. It shouldn't be called from the event dispatching thread. Here's an example that creates a new application thread that uses runAndGet(..) to access the state of a JCheckBox from the event dispatching thread and then, when that's finished, print the state from the application thread.
      
           JCheckBox checkBox = new JCheckBox("Hello World");
           var appThread = new Thread(()->{
                  try {
                      boolean state = UI.runAndGet(() -> checkBox.isSelected());
                      System.out.println("CheckBox state is " + state);
                  }
                  catch (Exception e) {
                      e.printStackTrace();
                  }
                  System.out.println("Finished on " + Thread.currentThread());
              });
           appThread.start();
       
      Type Parameters:
      T - The return type of the result value produced by the supplier.
      Parameters:
      supplier - The supplier which should be executed on the UI thread.
      Returns:
      The result provided by the supplier.
    • sync

      public static void sync()
      Use this to synchronize with the UI thread from a non-UI thread. After calling this method, the current thread will be blocked until the UI thread has finished executing all of its pending events. This method should only be called from the application thread and not from the UI thread.