当显示WorldPanel时,我想获得(Graphics g)。多亏了stackoverflow,我看到了应该在哪里使用getGraphics方法(ComponentListener.componentShown)的答案,但是以某种方式,我的侦听器无法捕获componentShown。

我怎么了?在代码段的底部,无法显示“ hello”。

public class MainPanel extends javax.swing.JPanel implements ComponentListener {
    private CWorldPanel WorldPanel; // extends JPanel

    private void initGUI() {
        try {
            ...
            this.setLayout(thisLayout);
            {
                WorldPanel = new CWorldPanel();
                WorldPanel.addComponentListener(this);
...
    @Override
    public void componentShown(ComponentEvent e) {
        System.out.println("hello");

    }


请参阅页面底部的我的解释和感谢(cscsaba)

最佳答案

如果要获取Graphics对象以便在组件可见时立即进行绘制,则不要。只需覆盖要显示的对象的paintComponent方法,然后在其中绘画即可。

(我不知道为什么您的ComponentListener不起作用,并且由于您的示例不完整而无法尝试。)

10-07 16:33