在JPanel中未调用paintComponent [英] paintComponent is not being called in JPanel

查看:149
本文介绍了在JPanel中未调用paintComponent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

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) 
    {

    }
}

不调用paintComponent(),也不调用paint()甚至repaint().我究竟做错了什么?我已经尝试了在StackOverflow上找到的所有内容,但是没有任何效果.如何解决?谢谢.

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.

推荐答案

您错过了几件事:

您没有main方法(或者您有,但没有在问题中发布它),并且从未创建过HerniPole实例. 添加这样的main方法:

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);
}

您没有将HerniPole实例添加到JFrame中. 在构造函数中,在frame.setVisible(true);

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

 frame.add(this);

这篇关于在JPanel中未调用paintComponent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆