matt matt - 5 months ago 36
Java Question

JFrame not displaying anything

I cannot seem to get a rectangle to be displayed in the JFrame. Per the parameters of this project, I have to have this class implement the Icon interface. When I run the code as is, I get the JFrame, but nothing shows up inside. It should display a black square. I'm assuming the problem has something to do with how I am initializing the graphics instance variable. I don't have much experience working with GUI graphics, so I'm not entirely clear on how to do this correctly.

And yes, I do know that the getIconWidth and getIconHeight methods are redundant since I am using constants, but I have to have these methods in order to implement the interface.

public class MugDisplay extends JFrame implements Icon {
private int width;
private int height;
private JPanel panel;
private Graphics graphics;

private static final int ICON_WIDTH = 100;
private static final int ICON_HEIGHT = 100;

public MugDisplay() {
this.panel = new JPanel();
this.panel.setLayout(new BorderLayout());
this.add(this.panel, BorderLayout.CENTER); = this.getGraphics();
int xPos = (this.panel.getWidth() - this.getIconWidth()) / 2;
int yPos = (this.panel.getHeight() - this.getIconHeight()) / 2;
this.paintIcon(this.panel,, xPos, yPos);

public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2 = (Graphics2D) g;
g2.fillRect(x, y, ICON_WIDTH, ICON_HEIGHT);

public int getIconWidth() {
return ICON_WIDTH;

public int getIconHeight() {

private void configureGui() {
this.setPreferredSize(new Dimension(600, 600));
this.getContentPane().setLayout(new BorderLayout());


In the interest of having a MCVE, here is the driver class that calls this class.

public class Main {

public static void main(String[] args) {
MugDisplay md = new MugDisplay();


Answer = this.getGraphics() is not how custom painting works in Swing. What you should do is create a panel, override its paintComponent method, make the call to super, and then do your painting. For instance:

panel = new JPanel() {
    protected void paintComponent(Graphics g) {
        int xPos = ...
        paintIcon(this, g, xPos, yPos);

Calling getGraphics will provide you with a short-lived Graphics object that can soon become invalid, which is why you should opt for overriding paintComponent instead, which will always give you a usable Graphics object. See Performing Custom Painting.

On a separate note, it looks like you're calling setVisible(true) before you're finished adding the necessary components to the JFrame. To ensure that your components show up, call setVisible(true) after adding them all to the frame.