java 调用paint,Java - 从不同的类调用paint方法?

本文讲述了如何在一个继承自JFrame的Game类中,即使paint方法在Die类中定义,也能通过创建Die对象并调用其paint方法。关键在于将Die实例传递给Game构造函数,并在适当时机调用Die的setVisible(true)。这是一种常见的回调实现方式。
摘要由CSDN通过智能技术生成

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.

This is the class which creates the window:

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

}

And for the paint method in the other class called Die, I used:

public void paint(Graphics pane)

解决方案

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

}

}

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).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值