Description: To generate a graph in Java, the JFreeChart library can be used, which provides a wide range of charting and graphing capabilities. First, include the JFreeChart library in the project, either by downloading it or by using a build tool like Maven. A dataset, such as `DefaultCategoryDataset` for bar charts or `XYSeries` for scatter plots, is created to hold the data that will be visualized. The graph is then created by passing the dataset to the corresponding chart type (e.g., `JFreeChart` for a line chart, bar chart, or pie chart). After the chart is created, it is added to a `ChartPanel`, which is a Swing component that displays the chart. The `ChartPanel` is then added to a `JFrame` to render the graph in the application window. Additional customization, such as axis labels, titles, and colors, can also be applied to enhance the graph's appearance.
for (int i = 0; i < data.length - 1; i++) { double x1 = PAD + i * xInc; double y1 = h - PAD - scale * data[i]; double x2 = PAD + (i + 1) * xInc; double y2 = h - PAD - scale * data[i + 1]; g2.draw(new Line2D.Double(x1, y1, x2, y2)); }
g2.setPaint(Color.blue); for (int i = 0; i < data.length; i++) { double x = PAD + i * xInc; double y = h - PAD - scale * data[i]; g2.fill(new Ellipse2D.Double(x - 2, y - 2, 4, 4)); } }
private int getMax() { int max = -Integer.MAX_VALUE; for (int i = 0; i < data.length; i++) { if (data[i] > max) { max = data[i]; } } return max; }
public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(new Graph()); f.setSize(600, 600); f.setLocation(200, 200); f.setVisible(true); } }
Screenshots
STEP 1: The graph is populated with data points and lines connecting them.