在我的JPanel中绘制简单的矩形不起作用

到目前为止,此代码的最终目标是绘制一堆矩形,这些矩形的高度逐渐增加(在整个窗口中从左到右),从而形成矩形的直角三角形,占据矩形的右下半部分。窗户。代码可以正常编译,但是运行时,所有窗口显示的都是一个JFrame,名为“ Selection Sort”,具有深灰色背景(一切正常,这是应该做的),并且没有矩形(不好)。 2类的代码:

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

public class SelectionSort extends JPanel {

    private Bar arr[];
    private JFrame frame; 
    private int amountBars;

    public SelectionSort(int amountBars) {
        frame = new JFrame("Selection Sort");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(700, 500);
        setBackground(Color.darkGray);
        frame.setContentPane(this);
        this.amountBars = amountBars;
        arr = new Bar[amountBars];
        for(int i = 0; i < arr.length; i++) {
            arr[i] = new Bar(new Color(i, i, i), i);
        }
        paintComponent(frame, getGraphics());
        }

    public void paintComponent(JFrame frame, Graphics g) {
        for(int i = 0; i < arr.length; i++) {
            g.setColor(arr[i].getColor());
            g.fillRect(i * ((int) getSize().getWidth() / arr.length), (int) getSize().getHeight(), (int) (getSize().getWidth() / arr.length), i * ((int) getSize().getHeight() / arr.length));
        }
    }

    private void delay(int ms) {
        try {
            Thread.sleep(ms);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SelectionSort sort = new SelectionSort(100);
        sort.repaint();
    }

}


public class Bar {

    private int size;
    private Color color;
    private int listNum;

    public Bar(Color color, int listNum) {
        this.color = color;
        this.listNum = listNum;
    }

    public Color getColor() {
        return color;
    }

    public int getListNum() {
        return listNum;
    }

    public void setColor(Color color) {
        this.color = color;
    }

    public void setListNum(int listNum) {
        this.listNum = listNum;
    }
}

I have some thoughts on how to do this differently, but I thought I'd just ask at this point to see. If this isn't solved, then would putting a drawRect method IN my Bar class, and then saying arr[i].draw(getGraphics) in the paintComponent method, or something like that work better? Note, the color of the bar is not important rn, but also how would I make it a rainbow gradient across the window? I don't think new Color(i, i, i) will work. Thanks!

评论