Adding a x and y axis line in jfreechart/crosshairs - java

I would like to add y and x axis lines to my graph. I have tried by setting domain cross hairs by true, but it doesn't appear. Please could i have some help? when I run the program the graph comes up the x and y lines don't appear at x = 0 and y = 0:
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
package Grava;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.paint.Color;
import org.jfree.chart.axis.NumberAxis;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.fx.ChartViewer;
import org.jfree.chart.panel.CrosshairOverlay;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.Crosshair;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.statistics.Regression;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import java.awt.*;
public class ScatterAdd extends Application {
private final XYSeries series = new XYSeries("Voltage");
private final XYSeries trend = new XYSeries("Trend");
private final XYSeriesCollection dataset = new XYSeriesCollection(series);
ChoiceBox<String> domainLabels = new ChoiceBox<>();
ChoiceBox<String> rangeLabels = new ChoiceBox<>();
private JFreeChart createChart() {
XYSeriesCollection dataset = new XYSeriesCollection();
dataset.addSeries(series);
return ChartFactory.createScatterPlot("VI Characteristics", "Current", "Voltage", dataset);
}
#Override
public void start(Stage stage) {
Image image = new Image("Grava.logo.png");
stage.getIcons().add(image);
XYPlot plot = createChart().getXYPlot();
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
XYLineAndShapeRenderer r = (XYLineAndShapeRenderer) plot.getRenderer();
r.setSeriesLinesVisible(1, Boolean.TRUE);
r.setSeriesShapesVisible(1, Boolean.FALSE);
var equation = new TextField();
series.addChangeListener((event) -> {
double[] coefficients = Regression.getOLSRegression(dataset, 0);
double b = coefficients[0]; // intercept
double m = coefficients[1]; // slope
equation.setText("y = " + m + " x + " + b);
});
JFreeChart chart = createChart();
domainLabels.getSelectionModel().selectedItemProperty().addListener((ov, s0, s1) -> {
chart.getXYPlot().getDomainAxis().setLabel(s1);
});
rangeLabels.getSelectionModel().selectedItemProperty().addListener((ov, s0, s1) -> {
chart.getXYPlot().getRangeAxis().setLabel(s1);
});
domainLabels.getItems().addAll("Current", "Seconds");
domainLabels.setValue("Current");
rangeLabels.getItems().addAll("Voltage", "Metres");
rangeLabels.setValue("Voltage");
var xSpin = new Spinner<Double>(-10000000.000, 10000000.000, 0, 0.1);
xSpin.setEditable(true);
xSpin.setPromptText("Xvalue");
var ySpin = new Spinner<Double>(-10000000.000, 10000000.000, 0, 0.1);
ySpin.setEditable(true);
ySpin.setPromptText("Yvalue");
var button = new Button("Add");
button.setOnAction(ae -> series.add(xSpin.getValue(), ySpin.getValue()));
HBox xBox = new HBox();
xBox.getChildren().addAll(domainLabels);
HBox yBox = new HBox();
yBox.getChildren().addAll(rangeLabels);
var enter = new ToolBar(xBox, xSpin, yBox, ySpin, button, equation);
BorderPane.setAlignment(enter, Pos.CENTER);
BorderPane root = new BorderPane();
root.setCenter(new ChartViewer(chart));
root.setBottom(enter);
stage.setTitle("ScatterAdd");
stage.setScene(new Scene(root, 720, 480));
stage.show();
}
/*
private void adjustAxis(NumberAxis axis, boolean vertical) {
axis.setRange(-3.0, 3.0);
axis.setTickUnit(new NumberTickUnit(0.5));
axis.setVerticalTickLabels(vertical);
}
*/
public static void main(String[] args) {
launch(args);
}
}

The crosshairs do not appear because you invoke createChart() twice, updating one instance while displaying the other. Instead, create and update a single instance:
public void start(Stage stage) {
//XYPlot plot = createChart().getXYPlot();
var chart = createChart();
XYPlot plot = chart.getXYPlot();
plot.setDomainCrosshairVisible(true);
plot.setRangeCrosshairVisible(true);
…
//JFreeChart chart = createChart();
…
}
Incidentally, adding the SeriesChangeListener before creating the chart, as you did here, risks causing Regression to
throw new IllegalArgumentException("Not enough data.");
Consider limiting the effect to two or more items:
series.addChangeListener((event) -> {
if (series.getItemCount() > 1) {
…
}
});

Related

printing from a ListView Javafx

I hava a javafx application where the user enters some details in test fields and it is shown on a listview. I now have a button to print using the printjob but everytime I hit the print button the printer prints garbage data like jhsjs6sh3#uhbsbkahi instead of the real values from the ListView. below is my codes for the print functon
public void print (final Node node) {
Printer printer = Printer.getDefaultPrinter();
PageLayout pageLayout = printer.createPageLayout(Paper.A4, PageOrientation.PORTRAIT, Printer.MarginType.HARDWARE_MINIMUM);
final double scaleX = pageLayout.getPrintableWidth() / node.getBoundsInParent().getWidth();
final double scaleY = pageLayout.getPrintableHeight() / node.getBoundsInParent().getHeight();
node.getTransforms().add(new Scale(scaleX, scaleY));
PrinterJob job =PrinterJob.createPrinterJob();
if (job != null ){
boolean success = job.printPage(node);
System.out.println("printed");
if (success){
System.out.println(success);
job.endJob();
}
}
}
#FXML

 private void printOps(ActionEvent event){
 
 print(billingDataList);

}
I use a MacBook for my development and HP printer.
You will have to figure out the scaling. This prints using SnapShot and awt. Using code from here.
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.IOException;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.SnapshotParameters;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
/**
*
* #author blj0011
*/
public class JavaFXApplication61 extends Application
{
#Override
public void start(Stage primaryStage)
{
ListView<String> list = new ListView<>();
ObservableList<String> items = FXCollections.observableArrayList("A", "B", "C", "D");
list.setItems(items);
VBox root = new VBox();
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction((event) ->
{
WritableImage image = list.snapshot(new SnapshotParameters(), null);
File file = new File("nodeImage.png");
try
{
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
Image imageToPrint = new Image(file.toURI().toString());
BufferedImage bufferedImage = SwingFXUtils.fromFXImage(imageToPrint, null);
printImage(bufferedImage);
}
catch (IOException ex)
{
System.out.println(ex.toString());
}
});
root.getChildren().add(btn);
root.getChildren().add(list);
Scene scene = new Scene(root, 1080, 720);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
private void printImage(BufferedImage image)
{
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable((Graphics graphics, PageFormat pageFormat, int pageIndex) ->
{
// Get the upper left corner that it printable
int x = (int) Math.ceil(pageFormat.getImageableX());
int y = (int) Math.ceil(pageFormat.getImageableY());
if (pageIndex != 0)
{
return NO_SUCH_PAGE;
}
graphics.drawImage(image, x, y, image.getWidth(), image.getHeight(), null);
return PAGE_EXISTS;
});
try
{
printJob.print();
}
catch (PrinterException e1)
{
e1.printStackTrace();
}
}
}

Why is the slider for this Java program is not working?

This is a fan program where use a slider to increase and decrease the speed of the fan. I do not need the increase and decrease button, I only have them as a guide to help the slider figure out what happens when you scroll left or right. I will delete those later. My slider is not showing and I can't test it out. Where did I go wrong here?
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;
import javafx.scene.control.Slider;
public class module2 extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
// Create fan pane
FanPane fanPane = new FanPane(100);
Slider mSlider = new Slider();
HBox scrollPane = new HBox(mSlider);
KeyFrame keyFrame = new KeyFrame(Duration.millis(10), e-> fanPane.spin());
Timeline fanTimeline = new Timeline(keyFrame);
fanTimeline.setCycleCount(Timeline.INDEFINITE);
// Buttons pause, resume, increase, decrease, reverse
Button pause = new Button("Pause");
pause.setOnAction(e-> fanTimeline.pause());
Button resume = new Button("Resume");
resume.setOnAction(e-> fanTimeline.play());
//fanPane.increase()
Button increase = new Button("Increase");
increase.setOnAction(e -> {
fanTimeline.setRate(fanTimeline.getCurrentRate() + 1);
mSlider.setValue(fanTimeline.getCurrentRate());
});
Button decrease = new Button("Decrease");
decrease.setOnAction(e -> {
fanTimeline.setRate(
(fanTimeline.getCurrentRate() - 1 < 0) ? 0 : fanTimeline.getCurrentRate() - 1);
mSlider.setValue(fanTimeline.getCurrentRate());
});
Button reverse = new Button("Reverse");
reverse.setOnAction(e-> fanPane.increment *= -1);
HBox hButtons = new HBox(pause,resume,reverse);
hButtons.setSpacing(10);
hButtons.setAlignment(Pos.CENTER);
hButtons.setPadding(new Insets(10, 10, 10, 10));
BorderPane borderPane = new BorderPane(fanPane, null, null, hButtons, null);
primaryStage.setScene(new Scene(borderPane));
primaryStage.setTitle("Spinning fan");
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
private class FanPane extends Pane {
private Circle c;
private Arc[] blades = new Arc[4];
private double increment = 1;
Slider mSlider = new Slider();
HBox scrollPane = new HBox(mSlider);
FanPane(double radius) {
setMinHeight(400);
setMinWidth(400);
c = new Circle(200,200,radius,Color.BLUE);
c.setStroke(Color.BLACK);
double bladeRadius = radius * 0.9;
for (int i = 0; i < blades.length; i++) {
blades[i] = new Arc(
c.getCenterX(), c.getCenterY(), // center point
bladeRadius, bladeRadius, // X and Y radius
(i * 90) + 30, 35); // start angle and length
blades[i].setFill(Color.YELLOW);
blades[i].setType(ArcType.ROUND);
}
getChildren().addAll(c);
getChildren().addAll(blades);
}
private void spin() {
for (Arc blade : blades) {
double prevStartAngle = blade.getStartAngle();
blade.setStartAngle(prevStartAngle + increment);
}
}
}
}

Sorting XYChart Series Data

Hello I have added data to a XYSeries and am trying to get that data sorted from shortest length to largest. I don't know how to manipulate this data, Can anyone help me out. This is my code:
xLabel = "Link Id";
yLabel = "Length (Km)";
bc = new BarChart<>(xAxis,yAxis);
bc.setTitle(gTitle);
//Set x/y Axis Label
//xAxis.setLabel(xLabel);
yAxis.setLabel(yLabel);
//double[] lengthArray = new double[linkIds.length];
XYChart.Series series1 = new XYChart.Series();
series1.setName(xLabel);
for (Integer m = 0; m < linkIdsOTS.length; m++) {
double length = netPlan.getLinkLengthInKm(otsLayerId, m);
//lengthArray[i] = length;
series1.getData().add(new XYChart.Data(m.toString(), length));
}
bc.getData().addAll(series1);
Assuming your Series and Data are properly typed, you should be able to do
series1.getData().sort(Comparator.comparingDouble(d -> d.getYValue().doubleValue()));
SSCCE:
import java.util.Comparator;
import java.util.Random;
import java.util.stream.Stream;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart.Data;
import javafx.scene.chart.XYChart.Series;
import javafx.stage.Stage;
public class BarChartSortTest extends Application {
#Override
public void start(Stage primaryStage) {
Random rng = new Random();
BarChart<String, Number> chart = new BarChart<>(new CategoryAxis(), new NumberAxis());
String cats = "ABCDEFGH" ;
Series<String, Number> series = new Series<>();
series.setName("Random data");
chart.getData().add(series);
Stream.of(cats.split(""))
.map(cat -> new Data<String, Number>(cat, rng.nextDouble()))
.forEach(series.getData()::add);
series.getData().sort(Comparator.comparingDouble(d -> d.getYValue().doubleValue()));
primaryStage.setScene(new Scene(chart, 600, 600));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

How to draw a spiderchart above a existing JfreeChart

I have one a jfree chart which I can generate everytime I run the code.
Now i want to override few more spider graphs on the same chart. please help me how to do that
Above this i need to add one more spider chart using jfree.
Here is my code for doing this chart.
package com.rectrix.exide.pdfbox;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Paint;
import java.awt.PaintContext;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.ColorModel;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.*;
public class DemoChart extends ApplicationFrame {
public DemoChart(String s)
{
super(s);
JPanel jpanel = createDemoPanel();
jpanel.setPreferredSize(new Dimension(500, 270));
setContentPane(jpanel);
}
private static CategoryDataset createDataset()
{
String s1 = "First";
String s2 = "Second";
String s3 = "Third";
String s4 = "Forth";
String s5 = "Fivth";
String s6 = "Sixth";
String s7 = "Seventh";
String s8 = "Eighth";
String s9 = "Ninth";
String s10 = "Tenth";
DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
int count = 5;
int value = 0;
//String keyRow="s";
for (int i=1;i<=10;i++){
value = i*4;
Comparable colKey = 0;
String keyRow = "s"+i;
for(int j=1;j<=count;j++){
colKey = j;
defaultcategorydataset.addValue(value, keyRow, colKey);
}
}
return defaultcategorydataset;
}
public static JFreeChart createChart1(CategoryDataset categorydataset,double d) {
SpiderWebPlot plot = new SpiderWebPlot(categorydataset);
Color bckColor1 = Color.decode("#4282CE"); //Light blue
Paint p = new GradientPaint(0, 1, bckColor1, 0, 1, bckColor1);
plot.setSeriesPaint(p);
JFreeChart chart = new JFreeChart("", plot);
return chart;
}
public static JPanel createDemoPanel()
{
JFreeChart jfreechart = createChart1(createDataset(), 10D);
return new ChartPanel(jfreechart);
}
public static void main(String args[])
{
DemoChart spiderwebchartdemo1 = new DemoChart("JFreeChart: SpiderWebChartDemo1.java");
spiderwebchartdemo1.pack();
RefineryUtilities.centerFrameOnScreen(spiderwebchartdemo1);
spiderwebchartdemo1.setVisible(true);
}
}
Please help me as soon as possible i need to send this build by tomorrow
Thank u in advance for helping and taking efforts to see this.
I want to override few more spider graphs on the same chart.
It may help to examine how a spider web plot is used to display multivariate data. The simplified example below compares just two OBSERVATIONS, each having five VARIABLES named A .. E, with random values in the range 1 .. 3. By chance, the values for variable B coincide; the rest differ. You can adjust the value of OBSERVATIONS to see the effect, but the result becomes progressively more muddled as the number of observations grows. You may want to alter series visibility, as suggested here, or consider these alternatives.
import java.awt.EventQueue;
import java.util.Random;
import javax.swing.JPanel;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.SpiderWebPlot;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.ApplicationFrame;
/** #see https://stackoverflow.com/a/32885067/230513 */
public class SpiderChart extends ApplicationFrame {
private static final int OBSERVATIONS = 2;
private static final int VARIABLES = 5;
private static final Random r = new Random();
public SpiderChart(String s) {
super(s);
add(createDemoPanel());
}
private static CategoryDataset createDataset() {
DefaultCategoryDataset dataset = new DefaultCategoryDataset();
for (int i = 1; i <= OBSERVATIONS; i++) {
String rowKey = "Observation " + i;
for (int j = 1; j <= VARIABLES; j++) {
Comparable colKey = Character.valueOf((char)(j+64));
dataset.addValue(r.nextInt(3) + 1, rowKey, colKey);
}
}
return dataset;
}
public static JFreeChart createChart(CategoryDataset dataset) {
SpiderWebPlot plot = new SpiderWebPlot(dataset);
JFreeChart chart = new JFreeChart("Test", plot);
return chart;
}
public static JPanel createDemoPanel() {
JFreeChart jfreechart = createChart(createDataset());
return new ChartPanel(jfreechart);
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> {
SpiderChart demo = new SpiderChart("SpiderWebChart");
demo.pack();
demo.setDefaultCloseOperation(EXIT_ON_CLOSE);
demo.setVisible(true);
});
}
}

Mark arrow on bar chart [duplicate]

Hi i want to draw cross hair on this barchar .Can somone help me.I jst want the cross hair to print X and y cordinates where my mouse is pointing or clicking.I m fine even if the cross hair prints X and Y cordinates on console .here's my code
import java.awt.Color;
import java.awt.Dimension;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.swing.JPanel;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.CombinedDomainXYPlot;
import org.jfree.chart.plot.Marker;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.HighLowRenderer;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
import org.jfree.data.xy.IntervalXYDataset;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RefineryUtilities;
public class PriceVolumeChart2 extends ApplicationFrame {
final static String filename = "D:\\CL.txt";
/**
* Default constructor
*/
public PriceVolumeChart2(String title) {
super(title);
JPanel panel = createDemoPanel();
panel.setPreferredSize(new Dimension(1200, 800));
setContentPane(panel);
}
private static OHLCDataset createPriceDataset(String filename) {
// the following data is taken from http://finance.yahoo.com/
// for demo purposes...
OHLCSeries s1 = new OHLCSeries(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse(st.nextToken());
double open = Double.parseDouble(st.nextToken());
double high = Double.parseDouble(st.nextToken());
double low = Double.parseDouble(st.nextToken());
double close = Double.parseDouble(st.nextToken());
s1.add(new Day(date), open, high, low, close);
//t1.add(new Day(date), close);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
OHLCSeriesCollection dataset = new OHLCSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
private static JFreeChart createCombinedChart() {
OHLCDataset data1 = createPriceDataset(filename);
System.out.println(data1.getItemCount(0));
HighLowRenderer renderer1 = new HighLowRenderer();
renderer1.setTickLength(3);
renderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator
(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
renderer1.setSeriesPaint(0, Color.blue);
DateAxis domainAxis = new DateAxis("Date");
NumberAxis rangeAxis = new NumberAxis("Price");
rangeAxis.setNumberFormatOverride(new DecimalFormat("$0.00"));
rangeAxis.setAutoRange(true);
rangeAxis.setAutoRangeIncludesZero(false);
ChartColor chartColor=new ChartColor(0, 0, 0);
XYPlot plot1 = new XYPlot(data1, domainAxis, rangeAxis, renderer1);
plot1.getRangeCrosshairPaint();
plot1.setRangePannable(true);
JFreeChart chart = new JFreeChart("NSE NIFTY", JFreeChart.DEFAULT_TITLE_FONT, plot1, false);
//ChartUtilities.applyCurrentTheme(chart);
return chart;
}
// create a panel
public static JPanel createDemoPanel() {
JFreeChart chart = createCombinedChart();
return new ChartPanel(chart);
}
public static void main(String[] args) {
// TODO code application logic here
PriceVolumeChart2 demo = new PriceVolumeChart2("JFreeChart");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
// Download data from web
}
this is my output.N i want crosshair to tell me the x and y coordinates according to given values in X and Y axis
You can enable the trace feature to follow the mouse, as shown here. You can add a ChartMouseListener to see the ChartEntity under the mouse, as shown here.
Addendum: Given a these instatiations,
JFreeChart chart = new JFreeChart(…);
chartPanel = new ChartPanel(chart);
This complete example enables trace:
chartPanel.setHorizontalAxisTrace(true);
chartPanel.setVerticalAxisTrace(true);
This complete example adds a ChartMouseListener:
chartPanel.addChartMouseListener(new ChartMouseListener() {
#Override
public void chartMouseClicked(ChartMouseEvent e) {
final ChartEntity entity = e.getEntity();
System.out.println(entity + " " + entity.getArea());
}
#Override
public void chartMouseMoved(ChartMouseEvent e) {
}
});
Hey guys i found the answer to this ..Thanks trashgod for helping me out..The following code helps to draw a barchart with a moving cross hair and the y coordinate is displayed on a JLabel.The CL.txt file contains nothing but date,open,close,high,low (all are double values).
import java.awt.Color;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.io.BufferedReader;
import java.io.FileReader;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import javax.swing.JLabel;
import org.jfree.chart.ChartColor;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartMouseEvent;
import org.jfree.chart.ChartMouseListener;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.HighLowRenderer;
import org.jfree.data.time.Day;
import org.jfree.data.time.ohlc.OHLCSeries;
import org.jfree.data.time.ohlc.OHLCSeriesCollection;
import org.jfree.data.xy.OHLCDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.ApplicationFrame;
import org.jfree.ui.RectangleEdge;
import org.jfree.ui.RefineryUtilities;
/**
* An example showing how to convert the mouse location to chart coordinates.
*/
public class MouseListenerDemo4 extends ApplicationFrame
implements ChartMouseListener {
private JFreeChart chart;
private ChartPanel chartPanel;
private JLabel priceLabel;
public MouseListenerDemo4(String title) {
super(title);
priceLabel=new JLabel("");
priceLabel.setBounds(5000, 5, 50, 20);
String chartTitle = "Mouse Listener Demo 4";
String file="D:\\CL.txt";
OHLCDataset data2 = createPriceDataset(file);
System.out.println(data2.getItemCount(0));
HighLowRenderer renderer1 = new HighLowRenderer();
renderer1.setTickLength(3);
renderer1.setBaseToolTipGenerator(new StandardXYToolTipGenerator
(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));
renderer1.setSeriesPaint(0, Color.blue);
DateAxis domainAxis = new DateAxis("Date");
NumberAxis rangeAxis = new NumberAxis("Price");
rangeAxis.setNumberFormatOverride(new DecimalFormat("$0.00"));
rangeAxis.setAutoRange(true);
rangeAxis.setAutoRangeIncludesZero(false);
ChartColor chartColor=new ChartColor(0, 0, 0);
XYPlot plot1 = new XYPlot(data2, domainAxis, rangeAxis, renderer1);
plot1.getRangeCrosshairPaint();
plot1.setBackgroundPaint(Color.white);
plot1.setDomainGridlinePaint(Color.magenta);
plot1.setRangeGridlinePaint(Color.magenta);
plot1.setRangePannable(true);
plot1.setRangeCrosshairVisible(true);
plot1.setRangeCrosshairValue(4000, true);
plot1.setRangeCrosshairLockedOnData(true);
plot1.setRangeCrosshairVisible(true);
this.chart = new JFreeChart("", JFreeChart.DEFAULT_TITLE_FONT, plot1, false);
chartPanel = new ChartPanel(this.chart);
chartPanel.setPreferredSize(new java.awt.Dimension(1000, 500));
chartPanel.setMouseZoomable(true, false);
chartPanel.addChartMouseListener(this);
setContentPane(chartPanel);
priceLabel.setBackground(Color.cyan);
chartPanel.add(priceLabel);
priceLabel.setVisible(true);
priceLabel.setText("");
}
private static OHLCDataset createPriceDataset(String filename) {
// the following data is taken from http://finance.yahoo.com/
// for demo purposes...
OHLCSeries s1 = new OHLCSeries(filename);
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String inputLine;
in.readLine();
while ((inputLine = in.readLine()) != null) {
StringTokenizer st = new StringTokenizer(inputLine, ",");
Date date = df.parse(st.nextToken());
double open = Double.parseDouble(st.nextToken());
double high = Double.parseDouble(st.nextToken());
double low = Double.parseDouble(st.nextToken());
double close = Double.parseDouble(st.nextToken());
double volume = Double.parseDouble(st.nextToken());
s1.add(new Day(date), open, high, low, close);
//t1.add(new Day(date), close);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
OHLCSeriesCollection dataset = new OHLCSeriesCollection();
dataset.addSeries(s1);
return dataset;
}
/**
* Creates a sample dataset.
*
* #return The dataset.
*/
/**
* Receives chart mouse click events.
*
* #param event the event.
*/
public void chartMouseClicked(ChartMouseEvent event) {
int mouseX = event.getTrigger().getX();
int mouseY = event.getTrigger().getY();
System.out.println("x = " + mouseX + ", y = " + mouseY);
Point2D p = chartPanel.translateScreenToJava2D(
new Point(mouseX, mouseY));
XYPlot plot = (XYPlot) chart.getPlot();
Rectangle2D plotArea = this.chartPanel.getChartRenderingInfo().getPlotInfo().getDataArea();
ValueAxis domainAxis = plot.getDomainAxis();
RectangleEdge domainAxisEdge = plot.getDomainAxisEdge();
ValueAxis rangeAxis = plot.getRangeAxis();
RectangleEdge rangeAxisEdge = plot.getRangeAxisEdge();
double chartX = domainAxis.java2DToValue(p.getX(), plotArea,
domainAxisEdge);
double chartY = rangeAxis.java2DToValue(p.getY(), plotArea,
rangeAxisEdge);
this.chartPanel.setHorizontalAxisTrace(true);
this.chartPanel.setVerticalAxisTrace(true);
System.out.println("Chart: x = " + chartX + ", y = " + (int)chartY);
priceLabel.setText(""+(int)chartY);
}
/**
* Receives chart mouse moved events.
*
* #param event the event.
*/
public void chartMouseMoved(ChartMouseEvent event) {
// ignore
}
/**
* Starting point for the demonstration application.
*
* #param args ignored.
*/
public static void main(String[] args) {
MouseListenerDemo4 demo = new MouseListenerDemo4(
"Mouse Listener Demo 4");
demo.pack();
RefineryUtilities.centerFrameOnScreen(demo);
demo.setVisible(true);
}
}

Categories