0

我对netbean的图形系统完全陌生,并且一直在努力学习Java教科书。我正在尝试制作一个简单的程序来显示一些东西,并且完全按照本书的要求进行操作。我在研究中发现了很多其他人也有类似的问题。这些人往往被告知要使用维度和首选大小方法,尽管在我试图用 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);
    }
}
4

2 回答 2

5

我想您的代码中有一个小错字。您肯定是要覆盖paintComponent()而不是paintComponents(). 第一个被调用来绘制组件,第二个被调用来绘制面板中包含的所有组件。因为没有,所以不会被调用。

于 2011-06-02T17:15:38.800 回答
2

这些人往往被告知使用维度和首选大小方法

您不应该真正使用 setPreferredSize()。相反,您应该重写 getPreferredSize() 方法以返回正确的值。

此外,您永远不应在 paintComponent() 方法中调用 setPreferredSize() 或在 paintComponent() 方法中更改类的任何属性。

于 2011-06-02T19:04:36.720 回答