java graphics 初始化_java – 如何初始化Graphics g?

你永远不会自己调用paint()或paintComponent(),你总是通过repaint()来处理设置相应的Graphics

只是为了展示@mKorbel所指的内容:

import java.awt.Color;

import java.awt.Dimension;

import java.awt.Graphics;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.net.MalformedURLException;

import java.net.URL;

import javax.swing.ImageIcon;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.SwingUtilities;

import javax.swing.Timer;

public class Lives extends JPanel {

private int lives;

private ImageIcon gameOverImage;

public Lives() {

try {

gameOverImage = new ImageIcon(new URL("http://imgup.motion-twin.com/dinorpg/0/f/77acf80b_989624.jpg"));

} catch (MalformedURLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

lives = 5;

}

public void removeLife() {

if (lives > 0) {

lives--;

System.out.println("Left lives: " + lives);

repaint();

}

}

@Override

protected void paintComponent(Graphics g) {

super.paintComponent(g);

if (lives > 0) {

System.out.println("Still have " + lives + " lives");

g.setColor(Color.WHITE);

g.fillRect(5 * 20,25 * 20,30);

g.setColor(Color.BLACK);

String result = "Lives: " + lives;

g.drawString(result,6 * 20,26 * 20);

} else if (gameOverImage != null) {

System.out.println("Game over");

int x = (getWidth() - gameOverImage.getIconWidth()) / 2;

int y = (getHeight() - gameOverImage.getIconHeight()) / 2;

g.drawImage(gameOverImage.getImage(),gameOverImage.getIconWidth(),gameOverImage.getIconHeight(),this);

}

}

@Override

public Dimension getPreferredSize() {

return new Dimension(800,600);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

@Override

public void run() {

JFrame frame = new JFrame(Lives.class.getSimpleName());

frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);

final Lives lives = new Lives();

frame.add(lives);

frame.pack();

frame.setVisible(true);

// Dummy timer that reduces the lives every second. For demo purposes only of course

Timer t = new Timer(1000,new ActionListener() {

@Override

public void actionPerformed(ActionEvent e) {

lives.removeLife();

}

});

t.start();

}

});

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值