1

This is a pretty simple program that just draws a white rectangle in a pop-up window. The program compiles and runs no problem, and the windoe pops up, but there is nothing in it, it's just grey. Why isn't anything drawing?

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

public class DrawPanel extends JPanel {
    public void paintcompnent(Graphics g) {
        int width = getWidth();
        int height = getHeight();

        super.paintComponent(g);
        g.setColor(Color.WHITE);
        g.fillRect(10, 10, 200, 200);
    }

    public static void main(String[] args) {
        DrawPanel panel = new DrawPanel();
        JFrame window = new JFrame();
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(panel);
        window.setSize(550,550);
        window.setVisible(true);
    }
}
4

3 回答 3

1
public void paintcompnent(Graphics g)

Should be

public void paintComponent(Graphics g)
于 2013-10-03T18:08:42.753 回答
1

You have not correctly overridden the method. It should be:

@Override
protected void paintComponent(Graphics g) {}

Note the use of the @Override annotation, which will prevent you from making this mistake in the future.

于 2013-10-03T18:11:10.060 回答
1

After fixing the overridden method name, it still won't paint anything because you are filling the rectangle in white and then painting white lines on top. You need to use setColor() to set something other than white to see the lines.

于 2013-10-03T18:15:48.860 回答