我正在设计一个条形图,但它没有显示。它的封装 JFrame 正在显示,并且paintComponent()
正在被调用,但没有出现灰色网格线。为什么是这样?
class ChartArea extends JPanel {
private int Yscl, Xscl;
private static final Color BACKGROUND_COLOR = Color.BLACK;
private static final Color LINE_COLOR = Color.GREEN;
private static final Color GRIDLINE_COLOR = Color.GRAY;
ChartArea() {
setBackground(BACKGROUND_COLOR);
setForeground(LINE_COLOR);
Yscl = 20;
Xscl = 20;
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
int height = getHeight();
int width = getWidth();
double max = data.getMax(); //gets the maximum value in the data set
try {
g2d.setStroke(new BasicStroke(1f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
//put the origin in the bottom right. Positive is up and left
g2d.translate(width, height);
g2d.scale(-1d, -1d);
//if the data set exceeds the window height, scale it down
if (max > height) {
g2d.scale(1, height / max);
}
paintGrid(g2d);
paintLine(g2d);
} finally {
g2d.dispose();
}
}
private void paintGrid(Graphics2D g) {
g.setPaint(GRIDLINE_COLOR);
//Vertical Lines
for (double pos = 0; pos > getWidth(); pos += Xscl) {
Line2D line = new Line2D.Double(pos, 0d, pos, getHeight());
g.draw(line);
}
//Horizontal Lines
for (double pos = 0; pos > getHeight(); pos += Yscl) {
Line2D line = new Line2D.Double(0d, pos, getWidth(), pos);
g.draw(line);
}
}
private void paintLine(Graphics2D g) {
g.setPaint(LINE_COLOR);
Path2D plot2 = new Path2D.Double();
if (!data.isEmpty()) {
plot2.moveTo(0.0, data.get(0));
for (int i = 1; i < data.size(); i++) {
plot2.lineTo((double) i, data.get(i));
}
g.draw(plot2);
}
}