JPAnel子类中的Overriden paint()函数从未被调用过?

时间:2012-08-06 12:51:14

标签: java jpanel paint repaint

我在我的JPanel子类ChordEditor中覆盖paint()方法时遇到问题。即使我覆盖了paint()方法,也将它添加到框架中,并调用repaint(),从不调用paint()方法。打印输出“进入绘画功能”不打印。任何人都可以帮我这个吗?

My ChordEditor课程:

public class ChordEditor extends JPanel{

    ArrayList<Chord> chordArray = new ArrayList<Chord>();

    public ChordEditor() {
        this.repaint();
    }

    @Override
    public void paint(Graphics g) {
        System.out.println("entering paint function");
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        Toolkit.getDefaultToolkit().sync();
        System.out.println("drawing line");
        g2d.drawLine(10, 10, 40, 40);
        g.dispose();
    }
}

我将它添加到JFrame:

ChordEditor ce = new ChordEditor();
m_frame.getContentPane().removeAll();
m_frame.add(ce);
m_frame.getContentPane().repaint();

1 个答案:

答案 0 :(得分:2)

在添加组件后立即发出repaint这一事实表明您在已经可见的帧上执行此操作。 也许您应首先validate框架。以下内容适用于我:

import javax.swing.*;
import java.awt.*;

class ChordEditor extends JPanel {

    public ChordEditor() {
        this.repaint();
    }

    @Override
    public void paint(Graphics g) {
        System.out.println("entering paint function");
        super.paint(g);
        Graphics2D g2d = (Graphics2D) g;
        Toolkit.getDefaultToolkit().sync();
        System.out.println("drawing line");
        g2d.drawLine(10, 10, 40, 40);
        //g.dispose();
    }

    public static void main(String[] args) {
        JFrame m_frame = new JFrame();
        m_frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        m_frame.setSize(600, 400);
        m_frame.setVisible(true);
        ChordEditor ce = new ChordEditor();
        m_frame.getContentPane().removeAll();
        m_frame.add(ce);
        m_frame.getContentPane().repaint();
        m_frame.validate();
    }
}

正如您对问题的评论中所述,您应该覆盖paintComponent而不是paint,并且不应该调用dispose,因为您没有创建此图形上下文。

syncrepaint的调用也应该是不必要的,我猜你添加它们是为了试图解决这个问题。一旦事情适合你,你可能会删除它们。您还可以考虑在使框架可见之前将所有组件添加到框架中。这样做会导致隐式验证,并且是Windows的更常用方法,它们包含固定的控件配置。