BoldDesk®Customer service software offering ticketing, live chat, and omnichannel support, starting at $49/mo. for 10 agents. Try it for free.
// add your additional code here
public primaryXAxis: Object = {
valueType: "DateTime",
labelFormat: "dd/MM/yyyy<br>hh:mm:ss",
intervalType: "Years",
edgeLabelPlacement: "Shift",
majorGridLines: { width: 0 }
};
// add your additional code here
|
I also want the same requirement using java swing JFreeChart for the following java swing code
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import java.util.Iterator;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import org.jfree.chart.axis.DateAxis;
import java.awt.Font;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.text.DateFormat;
import java.time.format.DateTimeFormatter;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
public class LineGraphWithExcelCSVData extends JFrame {
private List<LocalDateTime> dateTimes = new ArrayList<>();
private List<Integer> tempSV = new ArrayList<>();
private List<Integer> tempPV = new ArrayList<>();
TimeSeries seriesX, seriesY;
public LineGraphWithExcelCSVData() throws IOException {
// super(title);
// ImageIcon icon = new ImageIcon(getClass().getResource("/image/cornet.png"));
// setIconImage(icon.getImage());
// Show the file open dialog and get the selected file
File selectedFile = showFileOpenDialog();
if (selectedFile != null) {
// Load data from the selected file (either CSV or XLSX)
loadDataFromFile(selectedFile.getAbsolutePath());
// Create a dataset using the loaded data
TimeSeriesCollection dataset = createDataset();
Date firstDate = seriesY.getTimePeriod(0).getStart(); // Get the first date
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
String year = yearFormat.format(firstDate);
// Create the chart
JFreeChart chart = ChartFactory.createTimeSeriesChart(
"", // Title
"Date and Time", // X-axis label
"Temperature", // Y-axis label
dataset, // Dataset
true, // Include legend
true, // Tooltips
false // URLs
);
DateAxis dateAxis = (DateAxis) chart.getXYPlot().getDomainAxis();
DateFormat dateTimeFormat = new DateFormat() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yy");
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition fieldPosition) {
// Split date and time into two lines
String dateString = dateFormat.format(date);
String timeString = timeFormat.format(date);
// Append date and time in two lines
toAppendTo.append(dateString); // First line with the date
toAppendTo.append("\r\n"); // Add a newline
toAppendTo.append(timeString); // Second line with the time
return toAppendTo;
}
@Override
public Date parse(String source, java.text.ParsePosition pos) {
return null; // Not needed in this case, since we are only formatting the date
}
};
dateAxis.setDateFormatOverride(dateTimeFormat);
dateAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 10));
// Customize chart appearance (optional)
ChartPanel chartPanel = new ChartPanel(chart);
XYPlot plot = (XYPlot) chart.getPlot();
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, java.awt.Color.GREEN);
chart.getPlot().setBackgroundPaint(java.awt.Color.black);
ValueAxis xAxis = plot.getDomainAxis();
xAxis.setLabelFont(new Font("Arial", Font.BOLD, 12));
ValueAxis yAxis = plot.getRangeAxis(); // Y-axis
yAxis.setLabelFont(new Font("Arial", Font.BOLD, 12));
yAxis.setTickLabelFont(new Font("Arial", Font.PLAIN, 10));
setUndecorated(true);
chartPanel.setBackground(java.awt.Color.red);
chartPanel.revalidate();
chartPanel.repaint();
setContentPane(chartPanel);
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
System.exit(0); // Exit the application
}
}
});
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
// Set the size of the JFrame based on screen size (let's use the full screen size)
int width = (int) (screenSize.width);
int height = (int) (screenSize.height);
// Set the JFrame size
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
} else {
JOptionPane.showMessageDialog(this, "No File Selected.");
System.exit(1);
}
}
// Method to load data from both CSV and XLSX files
private void loadDataFromFile(String filePath) throws IOException {
if (filePath.endsWith(".xlsx")) {
loadDataFromExcel(filePath);
} else if (filePath.endsWith(".csv")) {
loadDataFromCSV(filePath);
} else {
JOptionPane.showMessageDialog(this, "Unsupported file type.");
}
}
// Load data from an Excel file (.xlsx)
private void loadDataFromExcel(String filePath) throws IOException {
FileInputStream fis = new FileInputStream(new File(filePath));
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0); // Assuming data is in the first sheet
Iterator<Row> rowIterator = sheet.iterator();
// Skip the header row
if (rowIterator.hasNext()) {
rowIterator.next(); // Skip header row
}
// Iterate over the rows and read data
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Cell dateCell = row.getCell(0); // DateTime
Cell tempSVCell = row.getCell(1); // TEMPE SV
Cell tempPVCell = row.getCell(2); // TEMPE PV
LocalDateTime dateTime = null;
// Parse the DateTime, TEMPE SV and TEMPE PV values
if (dateCell != null && dateCell.getCellType() == CellType.NUMERIC) {
dateTime = dateCell.getDateCellValue().toInstant()
.atZone(java.time.ZoneId.systemDefault())
.toLocalDateTime();
dateTimes.add(dateTime); // Add DateTime to the list
if (tempSVCell != null && tempSVCell.getCellType() == CellType.NUMERIC) {
tempSV.add((int) tempSVCell.getNumericCellValue()); // Add TEMPE SV to the list
}
if (tempPVCell != null && tempPVCell.getCellType() == CellType.NUMERIC) {
tempPV.add((int) tempPVCell.getNumericCellValue()); // Add TEMPE PV to the list
}
}
}
fis.close();
}
// Load data from a CSV file
private void loadDataFromCSV(String filePath) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
// Skip the header row
if ((line = br.readLine()) != null) {
// Optionally, print the header or just skip
System.out.println("Header: " + line);
}
// Read the CSV rows
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
// Trim any leading/trailing whitespace from the date string
String dateString = data[0].trim();
try {
// Print the raw date string for debugging
System.out.println("Parsing Date: " + dateString);
// Use the custom formatter to parse the date
LocalDateTime dateTime = LocalDateTime.parse(dateString, formatter); // Using formatter for the custom format
dateTimes.add(dateTime);
// Parse the numeric values for TEMPE SV and TEMPE PV
tempSV.add((int) Double.parseDouble(data[1])); // TEMPE SV (should be a Double)
tempPV.add((int) Double.parseDouble(data[2])); // TEMPE PV (also a Double)
} catch (Exception e) {
// Print error with the problematic data for debugging
System.err.println("Error parsing line: " + line);
e.printStackTrace();
}
}
br.close();
}
// Create a dataset for the chart
private TimeSeriesCollection createDataset() {
seriesX = new TimeSeries("Set Value");
seriesY = new TimeSeries("Present Value");
// Add data points to the series
for (int i = 0; i < dateTimes.size(); i++) {
LocalDateTime dateTime = dateTimes.get(i);
// Convert LocalDateTime to Second (which is used by TimeSeries)
Second timePeriod = new Second(dateTime.getSecond(), dateTime.getMinute(), dateTime.getHour(),
dateTime.getDayOfMonth(), dateTime.getMonthValue(), dateTime.getYear());
// Add data points using addOrUpdate
seriesX.addOrUpdate(timePeriod, tempSV.get(i));
seriesY.addOrUpdate(timePeriod, tempPV.get(i));
}
// Create a dataset with both series
TimeSeriesCollection dataset = new TimeSeriesCollection();
dataset.addSeries(seriesX);
dataset.addSeries(seriesY);
return dataset;
}
// Main method to run the application
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
// Create the application with a chart displaying data from Excel or CSV
LineGraphWithExcelCSVData chart = new LineGraphWithExcelCSVData();
// Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
//
// // Set the size of the JFrame based on screen size (let's use the full screen size)
// int width = (int) (screenSize.width);
// int height = (int) (screenSize.height);
//
// // Set the JFrame size
// chart.setSize(width, height);
// chart.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// chart.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
});
}
// Function to show the file open dialog and select a .xlsx or .csv file
private static File showFileOpenDialog() {
JFileChooser fileChooser = new JFileChooser();
// Set the file filter to accept both .xlsx and .csv files
fileChooser.setFileFilter(new javax.swing.filechooser.FileNameExtensionFilter("Excel and CSV Files (*.xlsx, *.csv)", "xlsx", "csv"));
// Set the initial directory (optional, could be the user's home directory or current working directory)
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
// Show the dialog and check if the user selected a file
int result = fileChooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
return fileChooser.getSelectedFile();
} else {
return null;
}
}
}
Hi Ramanan,
We do not have chart in Java. However, We have chart for Typescript, Javascript, Angular, React, Vue, ASP.NET MVC, and ASP.NET Core. You can explore more details here:
https://ej2.syncfusion.com/home/
Kindly revert us if you have any concerns.
Regards,
Nishanthi