JPanel paintComponent()不会在JFrame中绘制

时间:2019-05-14 01:03:21

标签: java swing jpanel paintcomponent

这里我有一个处理我的2048游戏的JPanel对象,但是当我尝试将其添加到JFrame时,paintComponent()不会执行任何操作。

我知道这不是paintComponent()的实现,因为我尝试绘制非常简单的东西(如下所示),并且我知道JPanel正在工作(因为它打印出“测试”)。

  import javax.swing.JFrame;

  public class GameEngine
  {
     public static void main(String[] args)
     {
        JFrame frame = new JFrame("2048");

        frame.setSize(700, 700);
        frame.setLocation(100, 50);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setContentPane(new newGamePanel());
        frame.setVisible(true);

     }
  }
          /******Different File******/

  import javax.swing.*;
  import java.awt.*;
  import java.awt.event.*;
     class newGamePanel extends JPanel{
       Color[] colorOfTiles = new Color[8];
       Color gridColor = new Color(187, 173, 160);
       Color backTileColor = new Color(204, 192, 180);
       Color twoFourText = new Color(238, 228, 218);
       Color notTwoFourText = new Color(255,255,255);
       int[][] tiles;

       public newGamePanel(){
       System.out.println("test");
       colorOfTiles[1] = new Color(238, 228, 218);colorOfTiles[2] = new 
       Color(236, 224, 200);
       colorOfTiles[3] = new Color(242, 177, 121);colorOfTiles[4] = new 
       Color(246, 141, 83);
       colorOfTiles[5] = new Color(245, 124, 95);colorOfTiles[6] = new 
       Color(233, 89, 55);
       colorOfTiles[7] = new Color(241, 208, 75);
       setLayout(new BorderLayout());
       setPreferredSize(new Dimension(700, 700));
       setFont(new Font("Arial", Font.BOLD, 48));
       setFocusable(true);

       JPanel subpanel = new JPanel();
       subpanel.setLayout(new GridLayout(4,4));
       add(subpanel, BorderLayout.CENTER);


       tiles = new int[4][4];

     }

      public void paintComponent(Graphics g){
        g.setColor(Color.black);
        g.fillRect(0, 0, 100 ,100);
     }
       //The rest of the methods are commented out
    }

我希望绘制一个黑色的填充矩形,但是JFrame上什么也没有出现。

0 个答案:

没有答案