【问题标题】:Draw Graphics on program start; PaintComponent never called在程序启动时绘制图形; PaintComponent 从未被调用
【发布时间】:2015-02-05 07:05:42
【问题描述】:

这似乎是一个如此简单的问题,但不知何故我无法用谷歌搜索答案。教程似乎从一开始就略过,我看不出他们的程序与我的程序有何不同。我要做的就是创建一个 JPanel 并在程序启动时使用 Graphics 类在其上绘制东西。

我创建了一个同样不起作用的程序的超级简化版本:

public class Thing 
{
    public static void main(String[] args) 
    {
        JFrame mainFrame = new JFrame("Test");
        mainFrame.setResizable(false);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        OtherThing panel = new OtherThing();

        mainFrame.getContentPane().add(panel);
        mainFrame.pack();
        mainFrame.setVisible(true);
    }
}

public class OtherThing extends JPanel
{
    public OtherThing()
    {
        setBackground(Color.black);
        setPreferredSize(new Dimension(400,400));
        repaint();
    }
    public void PaintComponent(Graphics g)
    {
        super.paintComponents(g);
        setBackground(Color.red);
        setForeground(Color.red);
        System.out.println("start");
        g.drawOval(0,0,50,50);
        g.drawLine(0,0 , 100, 100);
        g.drawString("This is my custom Panel!",10,20);
        System.out.println("After");

    }
}

Sytem.out.println 永远不会被打印出来。 PaintComponent 永远不会被调用。在我看过的一些教程中,它们听起来就像 repaint 调用paintcomponent 一样简单,但在我的程序中,paintcomponent 永远不会被调用。

我只想在启动时绘制图形。

【问题讨论】:

  • public void PaintComponent(Graphics g) 更改为 @Override public void PaintComponent(Graphics g) 以获得有用的编译器消息..
  • 我很困惑...它告诉我没有什么可以覆盖的? JPanel 没有 PaintComponent?

标签: java swing graphics paintcomponent


【解决方案1】:

Java 对键敏感。

public void PaintComponent(Graphics g)

必须是

public void paintComponent(Graphics g)

【讨论】:

  • 并且不需要是public
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多