使用调用方法paintComponet(Graphics g)在类Snake中进行渲染

时间:2016-04-10 02:23:32

标签: java swing graphics jframe jpanel

我是java games的新手。我正在尝试在渲染类中调用paintComponent,使用下面的代码从Snake类扩展JPanel。但我不知道我哪里出错了。它能够调用render的构造函数而不是paintComponent方法。

public class Snake implements ActionListener 
{
    public Timer t=new Timer(20,this);
    public Render render;
    public JFrame frame;
    public Toolkit toolkit;
    public static Snake s;
    public Snake()
    {
     toolkit=Toolkit.getDefaultToolkit();
     frame=new JFrame();
     //MenuBar menubar=new MenuBar();
     render=new Render();
     frame.setTitle("Nikitha's Snake");
     frame.setVisible(true);
     frame.setSize(800,700);
     frame.setLocation(toolkit.getScreenSize().width/2,            toolkit.getScreenSize().height/2);
     frame.setLocationRelativeTo(null);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.add(render);

//------------------------------------------------------------------------------
      JMenuBar menubar=new JMenuBar(); 
      JMenu file=new JMenu("File");
      menubar.add(file);
      JMenuItem newgame=new JMenuItem("new game");
      file.add(newgame);
      JMenu edit=new JMenu("Edit");
      menubar.add(edit);
      JMenuItem exit=new JMenuItem("Exit");
      edit.add(exit);
      frame.setJMenuBar(menubar);   


      exit.addActionListener(new ActionListener()
      {
          //@Override
          public void actionPerformed(ActionEvent e){
          System.exit(0);}
      });
//------------------------------------------------------------------------------
   t.start();
    }


    public static void main(String[] args) 
    {

        s = new Snake();
    }

    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        //System.out.println("a");
        render.repaint();
    }  
}




package snake;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

@SuppressWarnings("Serial")
public class Render extends JPanel{

public static int curcolor=0;    
  public void PaintComponent(Graphics g)
        {      
        super.paintComponent(g);
        System.out.println("i am inside render class");
        g.setColor(Color.RED);
        g.fillRect(0, 0, 800, 700);
        }
}

1 个答案:

答案 0 :(得分:1)

PaintComponent!= paintComponent

请记住,Java区分大小写。

强烈建议在重写方法时使用@Override注释,因为如果出错,会产生编译错误。

public class Render extends JPanel{ 

    @Override
    public void paintComponent(Graphics g) {