我正在尝试将JFrame窗口的形状设置为椭圆形,但是会引发以下错误:

java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at Splash.setShape(Splash.java:48)
    at Splash.<init>(Splash.java:25)
    at BackOffice.init(BackOffice.java:40)
    at sun.applet.AppletPanel.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)


问题是我要发送2个参数,并且该方法仅接受2个参数,所以我看不到从哪里得到此错误?错误指向的行是在这里说mSetWindowShape.invoke(this, shape);的行是相关的方法:

private void setShape() {
    Class<?> awtUtilitiesClass;
    try {
        awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
        Method mSetWindowShape = awtUtilitiesClass.getMethod("setWindowShape", Window.class, Shape.class);
        Shape shape = (Shape) new Ellipse2D.Double(0, 0, getWidth(), getHeight());
        mSetWindowShape.invoke(this, shape);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }

}


编辑:我起飞了一个参数,并得到了相同的错误(错误的参数数量)。然后,我输入3个参数(窗口,形状,0),并得到“参数类型不匹配”。然后,我尝试使用布尔值和字符串作为第三个参数,但这些参数也给出了“参数类型不匹配”。我不明白这一点,因为在本教程中它仅显示2个参数。现在显然有三个?

最佳答案

你的:

mSetWindowShape.invoke(this, shape);


应该:

mSetWindowShape.invoke(null, this, shape);


Method.invoke()方法将调用该方法的对象作为第一个参数。由于AWTUtilities.setWindowShape()是静态方法,因此第一个参数应为null。

另外,如果您可以将Java 7作为目标,请改用Frame.setShape(),因为它现在已正式成为API的一部分。 com.sun。*类将来可能会消失。

07-28 02:13
查看更多