我有一个扩展JFrame并创建窗口的类,它需要调用另一个类中的paint()方法。我知道,如果它们在同一个类中,setVisible(true)会调用paint方法,但由于它们在不同的类中,所以不会。我已经创建了Die类的对象(一幅画),但我不知道如何使用它们来调用绘制方法。
这是创建窗口的类:
public class Game extends Frame
{
public void window()
{
setTitle("Roll"); // Title of the window
setLocation(100, 100); // Location of the window
setSize(900, 600); // Size of the window
setBackground(Color.lightGray); // Color of the window
setVisible(true); // Make it appear and call paint
}
对于另一个名为Die的类中的绘制方法,我使用了:
public void paint(Graphics pane)
如果我理解你的问题,你可以用之类的东西将Die
实例传递到Game
构造函数中
public class Game extends Frame {
private Die die;
public Game(Die die) {
this.die = die;
}
public void window() {
setTitle("Roll"); // Title of the window
setLocation(100, 100); // Location of the window
setSize(900, 600); // Size of the window
setBackground(Color.lightGray); // Color of the window
setVisible(true); // Make it appear and call paint
die.setVisible(true); // The same
}
}
然后,无论在哪里调用new Game()
,都会添加Die
实例参数。这是在Java(和其他OOP语言)中实现回调的一种相当常见的方法。