Painting Graphics2D in a JFrame

2019-07-21 08:07发布

问题:

I'm making a 2d vertical shooter game, in which everything is coded (and working) but the graphics. I have not used the Graphics classes before, so this is all new to me. The following is the code I use to paint everything to the 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);
}

The first line "Graphics h = new Graphics2D();" produces an error because Graphics2d is abstract, but I have no idea where to go from here.

I need the code to take all the images that I have and paint them to the points in the JFrame. I remind you that I have never done this before, so please tell me if this is the wrong way to do this.

回答1:

in connections with Will's second thread (my helicopter view) about same thing Error with timer and JFrame

and correct intuition by Andrew Thompson's magics globe then

I added (I hope that's correctly, because I'm not familair with paint, paintComponent or paintComponents together with custom Graphics)

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


回答2:

Override paintComponent() instead; it will supply the Graphics context. You can cast it to a Graphics2D.

Graphics2D g2d = (Graphics2D) g;

Addendum: This assumes that you are overriding paintComponent() in a JComponent, which is then added to the JFrame.