Reputation: 577
I'm doing a game in java, and my problem is setting the background.
I've tried using g.drawImage()
but as its repaints every time, cause fps to drop a lot. So i fixed this fps issue by setting background with JLabel
and ImageIcon
. But the label overlay the graphics, how can I fix this?
public class GameScreen extends Screen implements Observer {
private static GameScreen gamescreen;
private Game game;
private JLabel label = new JLabel();
private ImageIcon icon = new ImageIcon("./res/img/bg1.png");
private GameScreen() {
setGame(Game.getInstance());
setLayout(null);
label.setIcon(icon);
label.setBounds(0, 0, 600, 600);
add(label);
}
public static GameScreen getInstance() {
if(getGameScreen() == null) {
setGameScreen(new GameScreen());
}
return getGameScreen();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//PaintWorld
new DrawableWorld().draw(g, getWidth(), getHeight());
//Paint players
new DrawablePlayer().draw(g, getWidth(), getHeight(), getGame().getPlayers());
//Paint hud
new DrawableHud().draw(g, getWidth(), getGame().getPlayers());
}
@Override
public void update(Observable o, Object arg) {
repaint();
}
//getters & setters..
Example:
PS: All DrawableClasses extends Screen that extends JPanel
Upvotes: 1
Views: 915
Reputation: 577
Following @serg.nechaev answer.
public class GameScreen extends Screen implements Observer {
private static GameScreen gamescreen;
private Game game;
//New static vars
private static BufferedImage image;
private static Image img;
private static int w = 0;
private static int h = 0;
private GameScreen() {
setGame(Game.getInstance());
setImage();
}
public static GameScreen getInstance() {
if(getGameScreen() == null) {
setGameScreen(new GameScreen());
}
return getGameScreen();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
//Scaling once
if(w != getWidth() || h != getHeight()) {
img = getImage().getScaledInstance(getWidth(), getHeight(), Image.SCALE_SMOOTH);
w = getWidth();
h = getHeight();
}
else{
g.drawImage(getImg(), 0, 0, this);
}
//PaintWorld
new DrawableWorld().draw(g, getWidth(), getHeight());
//Paint players
new DrawablePlayer().draw(g, getWidth(), getHeight(), getGame().getPlayers());
//Paint hud
new DrawableHud().draw(g, getWidth(), getGame().getPlayers());
}
@Override
public void update(Observable o, Object arg) {
repaint();
}
//getters & setters..
public BufferedImage getImage() {
return image;
}
public void setImage() {
try {
GameScreen.image = ImageIO.read(new File("./res/img/bg1.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Image getImg() {
return GameScreen.img;
}
Result with good fps:
Upvotes: 0
Reputation: 1321
g.drawImage is a very fast (to an extent) operation. Do you scale the image while drawing? Do you use "maximum quality" rendering hints?
Upvotes: 1