Skip to content
Advertisement

Java Swing Drawing A Rectangle [closed]

I’m trying to make a simple app that visualised sorting algorithms, but have gotten stuck trying to draw a rectangle (these will later represent each number in the array). I have tried alot of tutorials, and my code compiles, but it just makes an empty screen when ran. Have I missed something obvious?

import javax.swing.*;  
import java.util.ArrayList;
import java.util.Random;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

class DrawRectangle extends JComponent{
    public void paintComponent(Graphics g){
        Graphics2D g2=(Graphics2D) g;
        g2.setPaint(Color.PINK);
        Rectangle2D rect=new Rectangle2D.Double(50,50,200,200);
        g2.draw(rect);
        g2.fill(rect);
    }
}

public class Sorter {  
    static int numElements = 20; 
    static int width = 800;
    static int height = 500;

    public void newList(){

    }
    public static void main(String[] args) {  
        ArrayList<Integer> nums = new ArrayList<Integer>();
        Random rand = new Random();
        
        for(int i = 0; i <= numElements; i++){
            int randomNum = rand.nextInt(100);
            nums.add(randomNum);
        }

        // Create J Frame
        JFrame f=new JFrame(); 
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
        int arrWidth = width - 200;
        int eachCol = arrWidth / nums.size();
        for(int i = 0; i <= numElements; i++){

        }
        
        f.setSize(width,height);
        f.setLayout(null);//using no layout managers  
        f.setVisible(true);//making the frame visible  
        
        DrawRectangle rec= new DrawRectangle();
        f.add(rec);
        
        f.add(new DrawRectangle());
        f.repaint();
    }  
}

Advertisement

Answer

Your problem is that your DrawRectangle is never given any size (height & width). You could add

public Dimension getPreferredSize() {
  return new Dimension(200,200);
}

to DrawRectangle and turn the layoutmanger back on (preferred solution). Or you could manually setSize/setBounds of both the DrawRectangle and the Frame.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement