我在重写 JPanel 子类 ChordEditor 中的 Paint() 方法时遇到问题。即使当我重写paint()方法,将其添加到框架中,并调用repaint()时,paint()方法也永远不会被调用。打印输出“进入绘画功能”不打印。谁能帮我解决这个问题吗?
我的和弦编辑器类:
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();
最佳答案
您发出 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
因为您没有创建此图形上下文。
调用sync
的电话和repaint
也应该是不必要的,我猜你添加它们是为了在这里解决这个问题。因此,一旦事情对你有用,你就可以删除它们。您还可以考虑在使其可见之前将所有组件添加到框架中。这样做将导致隐式验证,对于具有固定控件配置的窗口来说,这是更常见的方法。
关于java - JPanel 子类中的重写 Paint() 函数从未被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11828660/