Java中的paintComponent()没有被调用[重复]

2023-12-23

我正在尝试绘制一个简单的矩形,但我认为 PaintComponent 方法没有被调用。 这是带有 main 方法的类的代码:

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

public class Painting  {       

    public static void main(String[] args) {
        JFrame jf;       
        jf = new JFrame("JUST DRAW A RECTANGLE");
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setLayout(null);
        jf.setLocationRelativeTo(null);
        jf.setSize(600,600);       
        jf.setVisible(true);
        Mainting maint = new Mainting();
        jf.add(maint);        
     }    
}

以及带有paintComponent()的类

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

public class Mainting extends JPanel {
    @Override  
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        g.drawRect(0, 0 , 200, 200);
        System.out.println("haha");
        g.setColor(Color.red);
    }
}

这里有什么问题,我无法弄清楚......


虽然已经提供的答案可能会导致出现矩形,但该方法并不是最佳的。此示例旨在展示更好的方法。阅读代码中的注释了解详细信息。

请注意,Swing/AWT GUI 应在 EDT 上启动。这留给读者作为练习。

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

public class Painting {

    public static void main(String[] args) {
        JFrame jf = new JFrame("JUST DRAW A RECTANGLE");
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // null layouts cause more problems than they solve. DO NOT USE!
        //jf.setLayout(null);
        jf.setLocationRelativeTo(null);
        /* if components return a sensible preferred size, 
        it's better to add them, then pack */
        //jf.setSize(600, 600);
        //jf.setVisible(true); //  as mentioned, this should be last
        Mainting maint = new Mainting();
        jf.add(maint);
        jf.pack(); // makes the GUI the size it NEEDS to be
        jf.setVisible(true);
    }
}

class Mainting extends JPanel {

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.RED); 
        g.drawRect(10, 10, 200, 200);
        System.out.println("paintComponent called");
        /* This does nothing useful, since nothing is painted
        before the Graphics instance goes out of scope! */
        //g.setColor(Color.red); 
    }

    @Override
    public Dimension getPreferredSize() {
        // Provide hints to the layout manager! 
        return new Dimension(220, 220);
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java中的paintComponent()没有被调用[重复] 的相关文章

随机推荐