How to represent double values as circles in a 2d matrix in java

醉酒当歌 提交于 2019-11-26 02:20:26

Here's an example of a custom renderer that implements the Icon interface to do the drawing. This approach permits easier control over the relative positioning of the text and icon. Note that the renderer scales based on the assumption of normalized values in the interval [0, 1); you may want to query your data model for the minimum and maximum values instead.

class DecRenderer extends DefaultTableCellRenderer implements Icon {

    private static final int SIZE = 32;
    private static final int HALF = SIZE / 2;
    DecimalFormat df;

    public DecRenderer(DecimalFormat df) {
        this.df = df;
        this.setIcon(this);
        this.setHorizontalAlignment(JLabel.RIGHT);
        this.setBackground(Color.lightGray);
    }

    @Override
    protected void setValue(Object value) {
        setText((value == null) ? "" : df.format(value));
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(
            RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
        g2d.setColor(Color.blue);
        double v = Double.valueOf(this.getText());
        int d = (int)(v * SIZE);
        int r = d / 2;
        g2d.fillOval(x + HALF - r, y + HALF - r, d, d);
    }

    @Override
    public int getIconWidth() {
        return SIZE;
    }

    @Override
    public int getIconHeight() {
        return SIZE;
    }
}

You will have to write your custom Cell Renderer.

The component will be used as a rubber stamp; the paint method is called for each cell.

Draw the circle in the paint method;

g.fillOval(x - radius / 2, y - radius / 2, radius, radius);

Will draw a circle of radius with center point at (x,y).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!