简体   繁体   中英

Putting sprites over background in a game

I'm having trouble loading a sprite into a game. I have the background done, but the sprite doesn't seem to be on the background. I want to assume you put it in the main constructor, but I don't think it will work.

package MyGamePKG;

import java.awt.BorderLayout;

public class GameJFrame extends JFrame {

private JPanel contentPane;
private int x,y,x_vel,y_vel;

/**
 * Launch the application.
 */
public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                GameJFrame frame = new GameJFrame();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public GameJFrame() {


    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 720, 520);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    GameJPanel Jpanel = new GameJPanel();
    Jpanel.setBounds(0, 0, 720, 480);
    contentPane.add(Jpanel);
    Jpanel.setLayout(null);

    JLabel lblNewLabel = new JLabel("New label");
    lblNewLabel.setIcon(new ImageIcon(GameJFrame.class.getResource("/Resources/gamemap.png")));
    lblNewLabel.setBounds(0, 0, 720, 480);
    contentPane.add(lblNewLabel);




}
}

The JPanel class

package MyGamePKG;

import java.awt.BasicStroke;

public class GameJPanel extends JPanel implements ActionListener, KeyListener {

private int frameRate = 30;
private int x=0;
private int y=460;
private int x_vel, y_vel;
private Image map;
private Image character;

/**
 * Create the panel.
 */
public GameJPanel() {
    character = new ImageIcon(getClass().getResource("/resources/sprite-concepts.png")).getImage();
    this.addKeyListener(this);
    this.setFocusable(true);
    Timer timer = new Timer(30, this);      
    timer.start();


}
@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    Graphics2D g2d = (Graphics2D) g;

    RenderingHints rh = new RenderingHints( RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);

    g2d.setRenderingHints(rh);
    this.setOpaque(false);
    myDrawBoxOvalsandRect(x,y,100,g2d);
    //myDrawArc(x+25,y+40,50,50,550,170,g2d);
} // paintComponent
public void myDrawBoxOvalsandRect( int x, int y, int scale, Graphics my_g)
{
    my_g.setColor(Color.cyan);
    my_g.fillOval(x, y, 15, 15); //face


}
public void myDrawArc(int x, int y, int height, int width, int angle1, int angle2, Graphics my_g)
{
    my_g.setColor(Color.red);
    my_g.drawArc(x, y, 50, 50, 550, 170); //happy face      
}
@Override
public void keyPressed(KeyEvent e) {
    // TODO Auto-generated method stub
    int c = e.getKeyCode();

    if(c == KeyEvent.VK_LEFT)
    {
        x_vel = -2;
        y_vel = 0;
    }
    if(c == KeyEvent.VK_UP)
    {
        x_vel = 0;
        y_vel = -2;
    }
    if( c == KeyEvent.VK_RIGHT)
    {
        x_vel = 2;
        y_vel = 0;
    }
    if( c == KeyEvent.VK_DOWN)
    {
        x_vel = 0;
        y_vel = 2;
    }
    repaint();

}
@Override
public void keyReleased(KeyEvent e) {
    // TODO Auto-generated method stub
    x_vel = 0;
    y_vel = 0;
    repaint();
}
@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}
@Override
public void actionPerformed(ActionEvent e) {
    // TODO Auto-generated method stub
    if(x < 0)
    {
        x_vel = 0;
        x = 0;
    }
    if(x > 720)
    {
        x_vel = 0;
        x = 720;
    }
    if(y < 0)
    {
        y_vel = 0;
        y = 0;
    }
    if(y > 480)
    {
        y_vel = 0;
        y = 480;
    }
    x = x + x_vel;
    y = y + y_vel;
    repaint();

}


}

I suspect a number of things...

  1. It's possible that the z-ordering of the components is rendering the background over the foreground components
  2. The reliance on null layouts means that it's possible the window borders are taking up more space then you are allowing for, covering up portions of the content.

Don't rely on a null layout and guess work. Each platform/Look and Feel has different requirements when it comes to the frame border (amongst other things). Instead, you should consider...

  • Overriding getPreferredSize to provide better sizing hints
  • Use an OverlayLayout manager
  • Use JFrame#pack to pack the frame around the content instead of using setBounds

Consider painting the entire game state using a single paintComponent method, this would mean rendering the background, middleground and foreground within GameJPanel 's paintComponent .

The benefit of this, is you gain complete control over the z-ordering process.

You should consider using key bindings over using KeyListener as it does not suffer from the same focus related issues and provides you with finer control over determining the level of focus that the component will raise key events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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