问题描述:

Does anyone know why the bars on my bargraph are showing up upside down?and what code i could add to leave a bit of room between each bar drawn? When i say upside down i mean the bars are even at the top and going down they vary in length

import java.awt.*;

import javax.swing.*;

public class Panel extends JPanel

{

int []nums;

String[]cat;

String t;

int max=0;

int width=0;

int height=0;

public Panel(int []x,String[]y,String a)

{

for(int i=0;i<x.length;i++)

{

if(x[i]>max)

max=x[i];

}

nums=x;

cat=y;

t=a;

width=nums.length*100+nums.length*10;

height=max*10+500;

setSize(width,height);

}

public void paint(Graphics g)

{

Font title=new Font("TimesNewRoman",Font.BOLD,20);

FontMetrics titl=g.getFontMetrics(title);

g.setFont(title);

g.drawString(t,width/2,20);

Font label=new Font("TimesNewRoman",Font.BOLD,15);

FontMetrics labl=g.getFontMetrics(label);

g.setFont(label);

for(int j=0;j<nums.length;j++)

{

g.setColor(new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256)));

g.drawString(cat[j],(nums.length*100)-((nums.length-j)*100)+22,height-20);

g.fillRect(j*100,height-400,100,nums[j]*15);

}

}

}

网友答案:

The main issue is ...

g.fillRect(j * 100, height - 400, 100, nums[j] * 15);

Basically, this says to draw a rect from j * 100 x height - 400 that is 100 wide and nums[j] * 15 high...

The rectangle is drawn right/down from the x/y position

You need to offset the y position from the height by the height of the bar...

g.fillRect(j * 100, height - (nums[j] * 15), 100, nums[j] * 15);

Don't override paint, it's not the best method to use, consider using paintComponentand make sure you call super.paintComponent before you perform any custom painting. See Performing Custom Painting for more details.

Don't use setSize on components, any values you pass it will be reset by the parent container's layout manager. Override the getPreferredSize of the JPanel instead.

Never assume anything about the actual size of the component from within the paint method, what you want and what you get won't always be the same thing.

Use getWidth and getHeight to determine the actual size of the viewable area.

网友答案:

From the docs for fillRect() (with my empasis):

The left and right edges of the rectangle are at x and x + width - 1. The top and bottom edges are at y and y + height - 1.

So x increases to the right and y - down.

相关阅读:
Top