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

时间:2020-05-18 02:53:01

标签: java swing jframe jpanel awt

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

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;
    }
}

我对如何以不同的方式进行操作有一些想法,但是我想我现在只是想看看。如果仍然无法解决问题,那么可以在我的Bar类中放置一个drawRect方法,然后在paintComponent方法中说arr[i].draw(getGraphics),或者类似的方法效果更好? 请注意,条形的颜色并不重要,但是我如何在窗口上使它变成彩虹渐变呢?我认为new Color(i, i, i)不起作用。谢谢!

0 个答案:

没有答案