简体   繁体   English

如何在JPanel上用Java绘制“类”

[英]How to Draw a “Class” in Java on a JPanel

Currently I am using a JFrame that has a JPanel in it. 目前我正在使用其中包含JPanel的JFrame。 In my JPanel I have overridden the paint component method, However, I want to "draw" a "Hero" class as a unit. 在我的JPanel中,我已经覆盖了paint组件方法,但是,我想“绘制”一个“Hero”类作为一个单元。 Let me elaborate. 让我详细说明一下。 The hero class as of right now has two parts: A health bar and an image. 现在的英雄类有两个部分:健康栏和图像。 Originally, in the paint component method of my JPanel, I was drawing the character and health bar individually. 最初,在我的JPanel的paint组件方法中,我正在单独绘制角色和健康栏。

public void paintComponent(Graphics g){
        g.drawImage(h.getImage(), h.getX(), h.getY(),null);
        g.setColor(Color.red);
        g.fillRect(h.getX()+7, h.getY()-16, 50, 10);
        g.drawLine(h.getX() + (h.getImage().getWidth(getFocusOwner())/2), h.getY()-40, h.getX() + (h.getImage().getWidth(getFocusOwner())/2), h.getY()+40);


    }

This properly aligned the health bar and character together, however, this seemed inefficient and messy. 这将健康栏和角色恰当地对齐在一起,然而,这看起来效率低下且杂乱无章。 So, is there anyway I could draw the two together as a unit? 那么,无论如何我可以将两者合并为一个整体吗? I pondered making them a separate JPanel, but realized that was a silly idea. 我考虑将它们作为一个单独的JPanel,但意识到这是一个愚蠢的想法。 Is there anyway to do this more efficiently? 无论如何更有效地做到这一点? One of the biggest reasons i am looking for a solution now is that i would like to be able to extend the character class with other classes IE: Monster, Knight, Goblin but when i draw them their respective health bars and images lined up. 我现在正在寻找一个解决方案的最大原因之一是我希望能够用其他类IE扩展角色类:Monster,Knight,Goblin但是当我绘制它们各自的健康栏和图像排成一行时。 If you need any further explanation please ask. 如果您需要任何进一步的解释,请询问。 Thank you! 谢谢!

Also, to spark any ideas that you might have, I'm imagining something like this. 另外,为了激发你可能拥有的任何想法,我想象的是这样的事情。 Another thing: Would using canvas be of any use? 另一件事:使用帆布会有用吗?

paint(Hero);

Thank you again! 再次感谢你!

In your Hero class define a drawing method which accepts a Graphics object: 在你的Hero类中定义一个接受Graphics对象的绘图方法:

public void drawHero(Graphics g)
{
    // implementation
}

Then in your main JPanel subclass draw the Hero with this drawing method: 然后在你的主要JPanel子类中用这个绘图方法绘制Hero

public void paintComponent(Graphics g)
{
    // other drawing code

    hero.drawHero(g);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM