Override the protected void paintComponent(Graphics g) method inherited from JPanel, and, inside your new paintComponent method, draw graphically how the total number of books borrowed by all users of the library changes over time, as follows: • Compute the following variables (where history is the result of calling the getHistory method of the model): int min = historyMin(history); int range = historyRange(history); int maxX = getWidth() - 1; int maxY = getHeight() - 1; int zero = maxY + min * maxY / range; • Draw a blue line between the point (0, zero) and the point (maxX, zero) (this blue line then represents the horizontal “zero” axis). • For each value v at index i in the history arraylist that you want to draw: o Use x = 10 * i for the horizontal coordinate; o Use y = zero - v * maxY / range for the vertical coordinate; o Draw red lines between all the points (x, y) (if there is only one value in the arraylist then just draw a rectangle of size 1 by 1 at position (x, y)).
时间: 2023-12-04 22:06:15 浏览: 26
Here is an example implementation of the paintComponent method:
```
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
List<Integer> history = model.getHistory();
int min = historyMin(history);
int range = historyRange(history);
int maxX = getWidth() - 1;
int maxY = getHeight() - 1;
int zero = maxY + min * maxY / range;
// Draw zero axis
g.setColor(Color.BLUE);
g.drawLine(0, zero, maxX, zero);
// Draw data points
if (history.size() == 1) {
int x = 10;
int y = zero - history.get(0) * maxY / range;
g.setColor(Color.RED);
g.fillRect(x, y, 1, 1);
} else {
g.setColor(Color.RED);
for (int i = 1; i < history.size(); i++) {
int x1 = 10 * (i - 1);
int y1 = zero - history.get(i - 1) * maxY / range;
int x2 = 10 * i;
int y2 = zero - history.get(i) * maxY / range;
g.drawLine(x1, y1, x2, y2);
}
}
}
```
This implementation first calculates the necessary variables for scaling the data points to fit within the component's bounds. It then draws a blue line to represent the horizontal "zero" axis.
For each data point in the history arraylist, it calculates the x and y coordinates and draws a red line between the current point and the previous point (if applicable). If there is only one point in the arraylist, it draws a small rectangle at that point.
Note that this implementation assumes that the model's getHistory method returns a non-null List<Integer>. You may need to add null checks or other error handling as necessary.