多次调用java.awt.Toolkit.getDefaultToolkit方法获得是同一个单例的Toolkit

多次调用java.awt.Toolkit.getDefaultToolkit方法获得是同一个单例的Toolkit

java.awt.Toolkit.getDefaultToolkit()
import java.awt.Toolkit;

public class 多次调用Toolkit的getDefaultToolkit方法获得是同一个单例的Toolkit {
	
	static public void main (String...arguments)throws Exception{
		
		System.out.println("Toolkit.getDefaultToolkit()获得的java.awt.Toolkit是不是同一个? 是否为单例设计模式?");
		System.out.println("Toolkit.getDefaultToolkit()==Toolkit.getDefaultToolkit()的结果是");
		System.out.println(Toolkit.getDefaultToolkit()==Toolkit.getDefaultToolkit());
		
		for(int r=0; r<100; r++) {
			for(int c=0; c<100; c++) {
				System.out.print(Toolkit.getDefaultToolkit()==Toolkit.getDefaultToolkit());
			}
			System.out.println();
		}
		
	}

}

在这里插入图片描述

jdk17源码去掉注释的


    private static Toolkit toolkit;

    public static synchronized Toolkit getDefaultToolkit() {
        if (toolkit == null) {
            toolkit = PlatformGraphicsInfo.createToolkit();
            if (GraphicsEnvironment.isHeadless() &&
                !(toolkit instanceof HeadlessToolkit)) {
                toolkit = new HeadlessToolkit(toolkit);
            }
            if (!GraphicsEnvironment.isHeadless()) {
                loadAssistiveTechnologies();
            }
        }
        return toolkit;
    }

private static Toolkit toolkit; 一个镜头变量保存实例, 如果保存实例的变量为空, 才创建新实例. 所以是单例

jdk17源码带注释的

    /**
     * The default toolkit.
     */
    private static Toolkit toolkit;

   /**
     * Gets the default toolkit.
     * <p>
     * If a system property named {@code "java.awt.headless"} is set
     * to {@code true} then the headless implementation
     * of {@code Toolkit} is used,
     * otherwise the default platform-specific implementation of
     * {@code Toolkit} is used.
     * <p>
     * If this Toolkit is not a headless implementation and if they exist, service
     * providers of {@link javax.accessibility.AccessibilityProvider} will be loaded
     * if specified by the system property
     * {@code javax.accessibility.assistive_technologies}.
     * <p>
     * An example of setting this property is to invoke Java with
     * {@code -Djavax.accessibility.assistive_technologies=MyServiceProvider}.
     * In addition to MyServiceProvider other service providers can be specified
     * using a comma separated list.  Service providers are loaded after the AWT
     * toolkit is created.
     * <p>
     * If the list of assistive technology providers as provided through system
     * property "{@systemProperty javax.accessibility.assistive_technologies}"
     * is the empty string or contains only
     * {@linkplain Character#isWhitespace(int) white space} characters it is
     * ignored. All other errors are handled via an AWTError exception.
     * <p>
     * The names specified in the assistive_technologies property are used to query
     * each service provider implementation.  If the requested name matches the
     * {@linkplain AccessibilityProvider#getName name} of the service provider, the
     * {@link AccessibilityProvider#activate} method will be invoked to activate the
     * matching service provider.
     *
     * @implSpec
     * If assistive technology service providers are not specified with a system
     * property this implementation will look in a properties file located as follows:
     * <ul>
     * <li> {@code ${user.home}/.accessibility.properties}
     * <li> {@code ${java.home}/conf/accessibility.properties}
     * </ul>
     * Only the first of these files to be located will be consulted.  The requested
     * service providers are specified by setting the {@code assistive_technologies=}
     * property.  A single provider or a comma separated list of providers can be
     * specified.
     *
     * @return     the default toolkit.
     * @throws  AWTError in case of an error loading assistive technologies.
     * @see java.util.ServiceLoader
     * @see javax.accessibility.AccessibilityProvider
     */
    public static synchronized Toolkit getDefaultToolkit() {
        if (toolkit == null) {
            toolkit = PlatformGraphicsInfo.createToolkit();
            if (GraphicsEnvironment.isHeadless() &&
                !(toolkit instanceof HeadlessToolkit)) {
                toolkit = new HeadlessToolkit(toolkit);
            }
            if (!GraphicsEnvironment.isHeadless()) {
                loadAssistiveTechnologies();
            }
        }
        return toolkit;
    }

注释翻译

获取默认工具包。

如果名为“java.awt.headless”的系统属性设置为 true,则使用 Toolkit 的无头实现,否则使用 Toolkit
的默认平台特定实现。

如果此工具包不是无头实现,并且如果它们存在,则如果由系统属性javax.accessibility.assistive_technologies指定,则将加载javax.accessibility.AccessibilityProvider的服务提供者。

设置此属性的一个示例是使用
-Djavax.accessibility.assistive_technologies=MyServiceProvider 调用 Java。除了 MyServiceProvider 之外,还可以使用逗号分隔的列表指定其他服务提供程序。创建
AWT工具包后,将加载服务提供商。

如果通过系统属性“{@systemProperty
javax.accessibility.assistive_technologies}”提供的辅助技术提供程序列表是空字符串或仅包含空格字符,则忽略它。所有其他错误都通过
AWTError 异常进行处理。

assistive_technologies属性中指定的名称用于查询每个服务提供程序实现。如果请求的名称与服务提供商的名称匹配,则将调用
AccessibilityProvider.activate 方法来激活匹配的服务提供程序。 返回:默认工具包。抛出:AWTError -
在加载辅助技术时出错。另请参阅:java.util.ServiceLoaderjavax.accessibility.AccessibilityProviderImpl
规范:如果未使用 systemproperty 指定辅助技术服务提供程序,则此实现将在位于以下属性文件中查找: •
${user.home}/.accessibility.properties} •
${java.home}/conf/accessibility.properties} 只会查阅要找到的第一个文件。通过设置
assistive_technologies=属性来指定请求的服务提供程序。可以指定单个提供程序或以逗号分隔的提供程序列表。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用反射机制来动态地获取和设置类中的字段值,可以将原来的直接引用图片的方式改为通过反射获取图片对象。 以下是代码示: ```java package com.hh.utils; import java.awt.*; import java.lang.reflect.Field; public class GameUtils { //蛇头 public static Image upImg; public static Image downImg; public static Image leftImg; public static Image rightImg; //蛇身 public static Image bodyImg; //食物 public static Image foodImg; //关卡 public static int level = 1; static { // 使用反射初始化图片对象 try { Field field = GameUtils.class.getDeclaredField("upImg"); field.setAccessible(true); field.set(null, Toolkit.getDefaultToolkit().getImage("img/up.png")); field = GameUtils.class.getDeclaredField("downImg"); field.setAccessible(true); field.set(null, Toolkit.getDefaultToolkit().getImage("img/down.png")); field = GameUtils.class.getDeclaredField("leftImg"); field.setAccessible(true); field.set(null, Toolkit.getDefaultToolkit().getImage("img/left.png")); field = GameUtils.class.getDeclaredField("rightImg"); field.setAccessible(true); field.set(null, Toolkit.getDefaultToolkit().getImage("img/right.png")); field = GameUtils.class.getDeclaredField("bodyImg"); field.setAccessible(true); field.set(null, Toolkit.getDefaultToolkit().getImage("img/body.png")); field = GameUtils.class.getDeclaredField("foodImg"); field.setAccessible(true); field.set(null, Toolkit.getDefaultToolkit().getImage("img/food.png")); } catch (Exception e) { e.printStackTrace(); } } //绘制文字 public static void drawWord(Graphics g, String str, Color color, int size, int x, int y) { g.setColor(color); g.setFont(new Font("宋体", Font.BOLD, size)); g.drawString(str, x, y); } } ``` 在调用图片的地方可以直接使用类中已经初始化好的字段对象,如: ```java if (!"down".equals(direction)) { direction = "up"; img = GameUtils.upImg; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kfepiza

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值