2

我正在制作一个 2d 垂直射击游戏,其中除了图形之外,所有东西都是编码(和工作)的。我以前没有使用过 Graphics 类,所以这对我来说是全新的。以下是我用来将所有内容绘制到 JFrame 的代码:

public void paintAll()
{
    Graphics h = new Graphics2D();
    for(Bullet j : GameState.getEnBullets()){
        h.drawImage(j.getImage(),j.getX(), j.getY(), null);}
    for(Enemy j : GameState.getEnemies()){
        h.drawImage(j.getImage(),j.getX(), j.getY(), null);}
    for(Bullet j : GameState.getPlayBullets()){
        h.drawImage(j.getImage(),j.getX(), j.getY(), null);}
    this.paint(h);
}

第一行“图形 h = new Graphics2D();” 产生错误,因为 Graphics2d 是抽象的,但我不知道从这里去哪里。

我需要代码来获取我拥有的所有图像并将它们绘制到 JFrame 中的点。我提醒您,我以前从未这样做过,所以请告诉我这是否是错误的方法。

4

2 回答 2

6

paintComponent()改为覆盖;它将提供Graphics上下文。您可以其转换为Graphics2D.

Graphics2D g2d = (Graphics2D) g;

附录:这假设您paintComponent()在 a中覆盖JComponent,然后将其添加到JFrame.

于 2011-06-07T04:01:57.113 回答
4

与 Will 的第二个线程(我的直升机视图)有关定时器和 JFrame 的错误

然后通过 Andrew Thompson 的魔法地球仪正确的直觉

我补充说(我希望这是正确的,因为我不熟悉paint、paintComponent 或paintComponents 以及自定义图形)

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class MinimumSize extends JFrame {

    private static final long serialVersionUID = 1L;

    public MinimumSize() {
        setTitle("Custom Component Test");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void display() {
        add(new CustomComponent());
        pack();        
        setMinimumSize(getSize());// enforces the minimum size of both frame and component
        setVisible(true);
    }

    public static void main(String[] args) {
        MinimumSize main = new MinimumSize();
        main.display();
    }
}

class CustomComponent extends JComponent {

    private static final long serialVersionUID = 1L;

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(100, 100);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 300);
    }

    @Override
    public void paintComponent(Graphics g) {
        int margin = 10;
        Dimension dim = getSize();
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
    }
}
于 2011-06-07T10:27:31.793 回答