PaintComponent未被称为netbeans GUI

0 java swing paintcomponent

我是netbean的图形系统的新手,并且一直在努力学习java教科书.我正在尝试制作一个简单的程序来显示一些东西,并按照它的要求完全按照本书.我在研究中发现了其他一些有类似问题的人.这些人倾向于被告知使用维度和preferredSize方法,尽管在我试图在java中重现的书的部分中没有提到这些.以下是我的代码:

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame(); //create frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes x button end program
        frame.setSize(300,200); //determine the size of the frame
        ImageIcon image = new ImageIcon("panda.jpg");
        ColorPanel p = new ColorPanel(Color.pink, image);
        Container pane = frame.getContentPane();
        pane.add(p);
        frame.setVisible(true); //make frame show up
    }

}

public class ColorPanel extends JPanel {

    ImageIcon image;

    public ColorPanel(Color c, ImageIcon i){
        setBackground(c);
        image = i;
    }

    @Override
    public void paintComponents(Graphics g){
        super.paintComponents(g);
        setPreferredSize(new Dimension(100,100));
        System.out.println("Blah!");
        g.setColor(Color.blue);
        g.drawRect(10,25,40,30);
    }
}
Run Code Online (Sandbox Code Playgroud)

How*_*ard 5

我想你的代码中有一个小错字.你绝对想要覆盖paintComponent()而不是paintComponents().第一个用于绘制组件,第二个用于绘制面板中包含的所有组件.由于没有,它不会被调用.