我正在尝试为学校制作一个天气小程序,但在将类(class)调用到主类(class)时遇到问题。最后,我需要 3 个永久组件(位置、温度、降水),然后在图像框中我想做一个 if 语句,从组件中的数据中获取适当的图像。
布局思路
主类代码
// The "Weather" class.
import java.applet.*;
import javax.swing.*;
import java.awt.*;
public class Weather extends Applet
{
//TempBar Intergers
//int x=
//int y=
//int H= //H = Heat
//PercipBar Intergers
//int x2=
//int y2=
//int P = //P = pericipitation
public void init ()
{
GridLayout umm = new GridLayout(0,2);
PercipBar percip = new PercipBar();
getContentPane.addItem (percip());
}
public void paint (Graphics g)
{
}
}
PercipBar 代码
import java.awt.*;
import java.applet.*;
public class PercipBar extends Applet
{
int x2 =2;
int y2 =2;
int P =80;//P = percipitation will be declared in main file
public void paint (Graphics g)
{
g.setColor (Color.black);
g.drawRect (x2, y2, 100, 20);//outline of bar
g.setColor (Color.blue);
g.fillRect (x2+1, y2+4, P, 14 ); //indicator bar (+4 puts space beetween outline bar)
}
}
最佳答案
该 GUI 似乎非常适合包含在 BorderLayout
中.
location gui
将被放置在BorderLayout.PAGE_START
位置
image
将放入BorderLayout.CENTER
temp
将放入BorderLayout.LINE_END
percip
(拼写为precip
)将置于BorderLayout.PAGE_END
位置
请注意,降水栏应该是另一个小程序!它应该只是一个组件
。
为了在 BorderLayout
中分配空间,自定义绘制组件需要返回合理的首选尺寸。
最好不要自定义绘制此类内容,而只需使用 Label
来显示文本。这样,我们就不需要重写 paint
方法或 getPreferredSize
。 GUI 将从标签的自然尺寸中获取提示。
关于java - 将类调用到网格中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21128209/