Java - 从不同的类调用paint方法? [英] Java - Calling paint method from different class?
问题描述
我有一个类扩展JFrame并创建一个窗口,它需要调用paint()方法,这是一个不同的类。我理解,如果他们在同一个类,setVisible(true)将调用paint方法,但由于他们在不同的类,它不是。我已经创建了Die类的对象(一个绘画),但我不知道如何使用它们来调用paint方法。
I have a class which extends JFrame and creates a window and it needs to call the paint() method which is in a different class. I understand that if they were in the same class, the setVisible(true) would call the paint method, but since they are in different classes, it does not. I have created objects of the Die class (the one painting), but I don't know how to use them to call the paint method.
这是创建窗口的类:
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,我使用:
And for the paint method in the other class called Die, I used:
public void paint(Graphics pane)
推荐答案
如果我理解你的问题,你可以通过 Die
实例插入游戏
构造函数
If I understand your question you could pass the Die
instance into the Game
constructor with something like
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
}
}
c $ c> new Game()您添加 Die
实例参数。这是在Java(以及其他OOP语言)中实施回调的相当常见的方法)。
Then, wherever you call new Game()
you add the Die
instance argument. This is a fairly common way to implement a callback in Java (and other OOP languages).
这篇关于Java - 从不同的类调用paint方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!