简体   繁体   English

在JPanel中未调用paintComponent

[英]paintComponent is not being called in JPanel

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(). 而且paintComponent()不会被调用,paint()甚至repaint()都不会被调用。 What am I doing wrong? 我究竟做错了什么? I've tried everything I found on StackOverflow, but nothing is working. 我已经尝试了在StackOverflow上找到的所有内容,但是没有任何效果。 How to fix that? 如何解决? Thanks. 谢谢。

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. 您没有main方法(或者也许有,但没有在问题中发布它),并且从未创建过HerniPole实例。 Add a main method like this: 添加这样的main方法:

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

You didn't add your HerniPole instance to your JFrame . 您没有将HerniPole实例添加到JFrame Do that in the constructor, somewhere before frame.setVisible(true); frame.setVisible(true);之前的构造函数中执行此操作frame.setVisible(true);

 frame.add(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM