Java 在 JPanel 类之外绘制图像

发布于 2024-10-20 18:31:56 字数 227 浏览 1 评论 0原文

我有一个扩展 JPanel 的 WorldManager 类,并具有:

public void Paint(Graphics g) {}

我想做的是拥有单独的类,例如具有自己的绘制方法的世界类,并且是能够像这样调用该类的 Paint 方法:

public void Paint(Graphics g) { world1.paint();英雄.paint(); }

I have a WorldManager class that extends a JPanel and has:

public void paint(Graphics g) {}

What I would like to do is have separate classes, like a world class with its own paint method and be able to just call that classes paint method like so:

public void paint(Graphics g) { world1.paint(); hero.paint(); }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

筱武穆 2024-10-27 18:31:56

原则上,你的做法没有任何问题。

  1. 正如trashgod所指出的,您应该覆盖paintComponent方法而不是paint方法。

    其原因在链接的文章中指出by trashgod:这样,paintBorder()paintChildren() 方法就可以绘制边框和子元素组件,并且您可以自由地只考虑真实内容。

  2. 您的其他绘制方法也应该采用 Graphics 参数(或 Graphics2D,如果您需要它并且只想投射一次),然后被调用。

这是一个例子:

class WorldManager extends JPanel
{

    private World world1;
    private Person hero;

    public void paintComponent(Graphics g) {
         super.paintComponent(); // paints the background, if opaque
         world.paint(g);
         hero.paint(g);
    }
}

那么,你的问题实际上是什么?

In principle, there is nothing wrong with your approach.

  1. As trashgod noted, you should overwrite the paintComponent method instead of the paint method.

    The reason for this is noted in the article linked by trashgod: this way, the paintBorder() and paintChildren() method can do their painting of the border and the child components, and you are free to think only about the real content.

  2. Your other paint methods should also take a Graphics parameter (or Graphics2D, if you need this and want to cast only once), and then be invoked.

Here is an example:

class WorldManager extends JPanel
{

    private World world1;
    private Person hero;

    public void paintComponent(Graphics g) {
         super.paintComponent(); // paints the background, if opaque
         world.paint(g);
         hero.paint(g);
    }
}

So, what was your question, actually?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文