我是Java的新手,我正在尝试创建一个条形图,它从文本字段中获取5个值,并创建一个包含5个值的条形图。我有大部分工作正常,也许不是最有效的方式,但我使用drawString()遇到麻烦。我正在尝试输出每个条顶部每个条的高度以进行调试,因为最终我需要以10为单位标记整个y轴。但是,每次我传递相同的y值时, “height”,对于draw.String(),它输出到与矩形左上角不同的位置。我不确定为什么会这样。不应该传递相同的y值意味着输出将处于相同的高度?任何帮助,将不胜感激。我附上了我正在获得的输出图片。虽然,我没有在这里包含它,但我确实有两行代码来绘制x和y轴。
public void paint(Graphics g)
{
super.paint(g);
double v1 = Double.parseDouble(jTextField1.getText());
double v2 = Double.parseDouble(jTextField2.getText());
double v3 = Double.parseDouble(jTextField3.getText());
double v4 = Double.parseDouble(jTextField4.getText());
double v5 = Double.parseDouble(jTextField5.getText());
Graphics pg = jPanel2.getGraphics();
int[] values = {(int)v1,(int)v2,(int)v3,(int)v4,(int)v5};
double space = (jPanel2.getHeight()*.09);
//Space for the bottom
int spaceY = (int)space;
int bar;
double heightPortion;
int height;
double heightCalc;
double numHeight;
int numHeight2;
//5% of the top of the frame is open
double gap = getHeight()*.05;
int gapTrunc = (int)gap;
//Display each value
for (int i= 0; i < 5; i++){
bar = values[i];
//Calculate what portion of the max height of a bar each value is
heightPortion = 100-bar;
heightPortion = heightPortion/100;
//Use 86% of the graph for the bars
heightCalc = heightPortion *(.86)*jPanel2.getHeight() + gapTrunc;
height = (int)heightCalc;
//Debugging
System.out.println(height);
//Use different colors for different letters
if(0<= bar && bar < 20)
pg.setColor(Color.orange);
if(20 <= bar && bar < 40)
pg.setColor(Color.gray);
if(40 <= bar && bar < 60)
pg.setColor(Color.yellow);
if(60 <= bar && bar < 80)
pg.setColor(Color.blue);
if(80 <= bar && bar <= 100)
pg.setColor(Color.red);
String s = Integer.toString(bar);
//Draw bar
pg.fillRect(jPanel2.getWidth()-(jPanel2.getWidth()*(16-
3*i)/20),height,20,jPanel2.getHeight()-height-spaceY);
//Label bar with value, passing it the same height
g.drawString(s,jPanel2.getWidth()-(jPanel2.getWidth()*(16-
3*i)/20),height);
}
}
答案 0 :(得分:0)
documentation for drawString
如下所示(强调我的):
使用此图形上下文的当前字体和颜色绘制指定字符串给出的文本。 最左边字符的基线位于此图形上下文坐标系中的位置(x,y)。
documentation for fillRect
如下所示(强调我的):
填充指定的矩形。 矩形的左侧和右侧边缘位于x和x +宽度 - 1. 顶部和底部边缘位于y和y +高度 - 1.生成的矩形覆盖区域宽度像素宽,高度像素高。使用图形上下文的当前颜色填充矩形。
答案 1 :(得分:0)
您正在使用2种不同的图形上下文:
public void paint(Graphics g)
{
Graphics pg = jPanel2.getGraphics();
pg.fillRect(...);
g.drawString(s, ...);
使用相同的上下文g
,即传递给绘图例程的上下文。