paintComponent is not being called in JPanel

2020-04-30 17:39发布

问题:

I have following code:

package hra;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class HerniPole extends JPanel implements KeyListener
{
    public int velikostPole;
    HerniPole(int velikostPole)
    {
        this.velikostPole = velikostPole;

        Color background = new Color(187, 173, 163);
        EventQueue.invokeLater(new Runnable() 
        {
            @Override
            public void run() 
            {
                try 
                {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex)
                {
                    System.err.println("Error!");
                }
            }
        });
        JFrame frame = new JFrame();
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setTitle("2048");
        frame.getContentPane().setBackground(background);
        frame.setSize(450, 450);
        frame.addKeyListener(this);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    @Override
    public void paintComponent(Graphics g)
    {
        System.out.println("xD");
        g.setColor(Color.BLACK);
        g.drawRect(20, 20, 20, 20);
        g.setColor(Color.yellow);
    }

    @Override
    public void keyTyped(KeyEvent ke) 
    {
        System.out.println(ke.getKeyCode());
    }
    @Override
    public void keyPressed(KeyEvent ke) 
    {

    }
    @Override
    public void keyReleased(KeyEvent ke) 
    {

    }
}

And paintComponent() is not being called, nor paint() or even repaint(). What am I doing wrong? I've tried everything I found on StackOverflow, but nothing is working. How to fix that? Thanks.

回答1:

You missed a few things:

You don't have a main method (or may be you have but didn't post it in your question) and never created an HerniPole instance. Add a main method like this:

public static void main(String[] args) {
    new HerniPole(0);
}

You didn't add your HerniPole instance to your JFrame. Do that in the constructor, somewhere before frame.setVisible(true);

 frame.add(this);