Java从不同的类调用绘画方法?

Java从不同的类调用绘画方法?,java,swing,class,paint,repaint,Java,Swing,Class,Paint,Repaint,我有一个扩展JFrame并创建窗口的类,它需要调用另一个类中的paint()方法。我知道,如果它们在同一个类中,setVisible(true)会调用paint方法,但由于它们在不同的类中,所以它不会。我已经创建了Die类的对象(一幅画),但是我不知道如何使用它们来调用paint方法 这是创建窗口的类: public class Game extends Frame { public void window() { setTitle("Roll");

我有一个扩展JFrame并创建窗口的类,它需要调用另一个类中的paint()方法。我知道,如果它们在同一个类中,setVisible(true)会调用paint方法,但由于它们在不同的类中,所以它不会。我已经创建了Die类的对象(一幅画),但是我不知道如何使用它们来调用paint方法

这是创建窗口的类:

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的类中的paint方法,我使用了:

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
  }
}

然后,无论在哪里调用
newgame()
都添加
Die
实例参数。这是在Java(和其他OOP语言)中实现a的一种相当常见的方法。

一般回答:您需要在
游戏
类中引用
Die
,方法是调用构造函数
Die=new Die()
,然后调用paint方法
Die.paint()
或在
Die
类中,您创建
paint()
方法
static
,然后这样调用它
Die.paint()
@nem已经尝试了第一个,第二个不起作用,因为我必须返回值?
paint()
方法具有
void
返回类型,因此在这两种情况下都不需要返回任何内容我不确定是否理解这一点。游戏类有一个骰子。我的想法是在游戏类中多次调用Die类,该类使用多种方法创建一个Die来创建一个Die。还应注意,在Die类中的paint方法之前有一个setup方法。@John Yes。这就建立了一种has-a关系。如果你已经有了,那么你的问题就没有意义了。如果您需要多次调用它,这很好,您已经有了一个。当我尝试创建一个新的Game()时,它告诉我构造函数Game()未定义。当我有一个新游戏(骰子)时,它告诉我骰子不能解析为变量。但是我仍然不知道在Die类中如何需要一个新的Game()?传递
Die
实例<代码>新游戏(new Die())
或您已初始化的
Die
实例<代码>新游戏(一些初始化的游戏)
哦,我明白了。但是现在我在main方法中调用什么呢?当我使用game myGameTable=newgame()时,它告诉我构造函数game是未定义的;myGameTable.window();