我用java制作了一个游戏,我似乎无法paintComponent()
在我的游戏中调用该方法。这是代码:
public class TwinMoonTowers extends JPanel implements ActionListener{
private class TMTMenu extends MouseAdapter{
private Icon start, shop, quit;
private Icon main_bg;
public TMTMenu (){
System.out.println("starting menu...");
start = new Icon(TMTConstant.START_SOURCE,
TMTConstant.START_COORD_X, TMTConstant.START_COORD_Y);
shop = new Icon (TMTConstant.SHOP_SOURCE,
TMTConstant.SHOP_COORD_X, TMTConstant.SHOP_COORD_Y);
quit = new Icon (TMTConstant.EXIT_SOURCE,
TMTConstant.EXIT_COORD_X, TMTConstant.EXIT_COORD_Y);
main_bg = new Icon (TMTConstant.MAIN_MENU_BG, 0, 0);
}
@Override
public void mousePressed(MouseEvent me){
int x = me.getX();
int y = me.getY();
System.out.println("coord: "+x+","+y);
if (me.getButton() == MouseEvent.BUTTON1){
if (x > start.x && x < start.x + start.getIcon().getWidth(null)
&& y > start.y && y < start.y + start.getIcon().getHeight(null)){
curState = TMTConstant.MODE_STATE;
}
else if (x > quit.x && x < quit.x + quit.getIcon().getWidth(null)
&& y > quit.y && y < quit.y + quit.getIcon().getHeight(null)){
curState = TMTConstant.EXIT_STATE;
}
else if (x > shop.x && x < shop.x + shop.getIcon().getWidth(null)
&& y > shop.y && y < shop.y + shop.getIcon().getHeight(null)){
curState = TMTConstant.SHOP_STATE;
}
}
}
}
private class TMTModeSelector extends MouseAdapter{
private Icon TwinTower, TripleTower, back;
public TMTModeSelector(){
}
@Override
public void mousePressed(MouseEvent e){
}
}
private String testDebug;
private int curState;
private TMTMenu menu;
public TwinMoonTowers (){
menu = new TMTMenu();
curState = TMTConstant.MAIN_MENU_STATE;
System.out.println("creating panel..");
this.setVisible(true);
this.setDoubleBuffered(true);
this.setSize(TMTConstant.WINDOW_WIDTH, TMTConstant.WINDOW_HEIGHT);
this.addMouseListener(menu);
}
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
this.repaint();
}
@Override
public void paintComponent (Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
System.out.println("preparing canvas..");
switch(curState){
case TMTConstant.MAIN_MENU_STATE :
g2d.drawImage(menu.main_bg.getIcon(), menu.main_bg.x, menu.main_bg.y, this);
g2d.drawImage(menu.start.getIcon(), menu.start.x, menu.start.y, null);
g2d.drawImage(menu.quit.getIcon(), menu.quit.x, menu.quit.y, null);
g2d.drawImage(menu.shop.getIcon(), menu.shop.x, menu.shop.y, null);
break;
case TMTConstant.GAME_STATE :
break;
case TMTConstant.SHOP_STATE :
break;
case TMTConstant.MODE_STATE :
break;
}
System.out.print("render image...");
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
}
而类图标是这样的:
public class Icon{
private Image pic;
public int x, y;
public Icon (String path, int x, int y){
ImageIcon ii = new ImageIcon (path);
pic = ii.getImage();
this.x = x;
this.y = y;
}
public Image getIcon() {return pic;}
}
这里的基础是绘制一个包含 3 个按钮(开始、购物、退出)的菜单
但是,paintComponent 方法没有被调用(system.out.println 没有显示)