Search code examples
javaswinggraphics2d

Why my rectangle shape is so small in java graphics 2d


So I am new in java graphics and I am creating a program that will show a rectangle. But when I run my program it only show like a small box and not the rectangle. I don't really know why it is happening.

Here is my code:

import javax.swing.*;

public class GraphicsEditor{

    
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();
        
        Rectangle rectangle = new Rectangle();
        
        frame.setSize(1280, 720);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        frame.setVisible(true);
        frame.add(panel);
        panel.add(rectangle);
        
    }
    
}

This is my rectangle class:

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;

public class Rectangle extends JPanel implements Shape {
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2D = (Graphics2D) g;
        g2D.fillRect(0, 0, 200, 130);
    }

}

This is my shape interface:

import java.awt.*;

public interface Shape {
    void paintComponent(Graphics g);
}

Solution

  • Here, try this

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.border.LineBorder;
    
    public class GraphicsEditor {
        
        public static void main(String[] args) {
            JFrame frame = new JFrame();
            Rectangle rectangle = new Rectangle();
            
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(rectangle);
            frame.pack();
            // center frame on screen
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            
        }
        
        
    }
    class Rectangle extends JPanel {
        
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2D = (Graphics2D) g;
            g2D.fillRect(0, 0, 200, 130);
        }
        
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(500, 500);
        }
    }
    

    A couple of things.

    • you don't need the interface.
    • unlike components, just painting a picture doesn't affect the layout manager, so the panel will be reduced to it's default size with out regard to any painting.
    • so you need to override getPreferredSize() in your JPanel.