gpt4 book ai didi

java - 如何从小程序类获取宽度?

转载 作者:行者123 更新时间:2023-12-01 13:12:35 25 4
gpt4 key购买 nike

例如

头等舱:

class Stuck {

private int i;

public void WhatIwant(){
i = FirstClass.getWidht();
}
}

主类:

public class FirstClass extends applet{

@Override
public void init() {
setSize(500, 500);
}
}

我尝试创建新的 FirstClass 但显示 0?请帮助我,我被困住了。我首先在 Google 中尝试。

最佳答案

就像我在评论中解释的那样,当您调用 FirstClass.getWidth() 时,Appletinit() 方法没有还没被叫到呢而且,更重要的是,您无法像这样访问 FirstClass非静态 getWidth() 方法!。确保您创建了一个 FirstClass 对象来访问它,如下所示:

FirstClass fc = new FirstClass();
fc.init(); // Not recommended.
// Now, you can get the width.

但不建议这样做。因此,您应该采用这种方法:

1. Create a method "getPreferredSize()" in the "FirstClass". Declare and
initialize two private variables namely "width" and "height":

public class FirstClass extends Applet {
private int width = 400;
private int height = 300;
...
@Override
public void Dimension getPreferredSize() {
return new Dimension(width,height);
}
...

2. Or you can directly return the preferred width as:

...
public int getPreferredWidth() {
return width;
// OR:
// return (int)getPreferredSize().getWidth();
} //and the same for height

关于java - 如何从小程序类获取宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22740716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com