如何在游戏方法中调用paint方法?
如果我用命令调用“new paint();”它不起作用
// Main
public Game() {
super();
setTitle("Breakout");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setLocationRelativeTo(null);
setIgnoreRepaint(true);
setResizable(false);
setVisible(true);
}
// Grafica
class paint extends JPanel {
public paint(Graphics2D g) {
super.paint(g);
g.setColor(Color.black);
}
}
答案 0 :(得分:0)
大多数程序员在JPanel超类中使用受保护的swing方法paintComponent(Graphics g)来匿名调用repaint()来改变游戏值并改变组件的视觉外观。使用SwingTimer将在预定的时间内更新结果。
public class game extends JPanel implements ActionListener{
int camX, camY;
int update_time = 5;// in milliseconds...
Graphics2D g2d;
Image image;
Timer t;
public game(){
t = new Timer(update_time, this);// given "this" is an ActionListener...
t.start();// calls actionPerformed method every 5ms...
}
public void actionPerformed(ActionEvent e){
repaint();//calls paintComponent() method...
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g2d = (Graphics2D)g;
g2d.drawImage(image, camX, camY, this);
//Do graphical stuff
}
}