gpt4 book ai didi

java - 自定义 java BarChart 缩放问题

转载 作者:行者123 更新时间:2023-12-02 11:48:23 25 4
gpt4 key购买 nike

我一直在尝试用 Java 为一个学校项目制作一个自定义条形图,但由于某种原因它有一些奇怪的缩放问题。这是代码。

static class BarChart extends JPanel
{
private int[] chartValues;
private String[] chartLabels;
private String chartTitle;

public BarChart(String title,int[] values,String[]labels)
{
this.chartTitle = title;
this.chartValues = values;
this.chartLabels = labels;
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);

Random r = new Random();

if(this.chartValues == null || this.chartValues.length==0)
{
return;
}

Dimension chartDimension = this.getSize();
int panelWidth = chartDimension.width;
int panelHeight = chartDimension.height;
int barWidth = panelWidth / this.chartValues.length;
int maxValue = this.chartValues[0];
int minValue = this.chartValues[0];
for(int tempValue:this.chartValues)
{
maxValue = Math.max(maxValue, tempValue);
minValue = Math.min(minValue, tempValue);
}

Font titleFont = new Font("Book Antiqua", Font.BOLD, 15);
FontMetrics titleFontMetrics = g.getFontMetrics(titleFont);

Font labelFont = new Font("Book Antiqua", Font.PLAIN, 14);
FontMetrics labelFontMetrics = g.getFontMetrics(labelFont);

int titleWidth = titleFontMetrics.stringWidth(this.chartTitle);
int stringHeight = titleFontMetrics.getAscent();
int stringWidth = (panelWidth - titleWidth) / 2;
g.setFont(titleFont);
g.drawString(this.chartTitle, stringWidth, stringHeight);

int top = titleFontMetrics.getHeight();
int bottom = labelFontMetrics.getHeight();

if(maxValue==minValue)
{
return;
}

double barScale = (panelHeight - top - bottom)/(maxValue - minValue);

stringHeight = panelHeight - labelFontMetrics.getDescent();

int xPos = 5;
g.setFont(labelFont);
for(int i=0; i<this.chartValues.length;i++)
{
int tempValue = this.chartValues[i];
int barHeight = (int) ( (double)tempValue * barScale);
int yPos = top;

if(tempValue>=0)
{
yPos += (int) ((maxValue - tempValue)* barScale);
}
else
{
yPos += (int) (maxValue * barScale);
barHeight = - barHeight;
}

g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));

g.fillRect(xPos, yPos, barWidth, barHeight);
g.setColor(Color.BLUE);
g.drawRect(xPos, yPos, barWidth, barHeight);

xPos += barWidth;
}

g.setColor(Color.BLACK);
g.drawString("Xronos", stringWidth, stringHeight);


}
}

但是当我使用值 {1,5,4,7,120} 的 main 运行它时,我会根据屏幕分辨率得到这个值。 Wrong image (the height between bars and label is too much). Correct height between bars and label 。我真的很感谢任何帮助。如果这个愚蠢的问题是一个问题,我很抱歉。

最佳答案

您在这里进行整数除法:

double barScale = (panelHeight - top - bottom)/(maxValue - minValue);

尝试

double barScale = (panelHeight - top - bottom)/(double)(maxValue - minValue);

相反

关于java - 自定义 java BarChart 缩放问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48052061/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com