Displaying data on table into jfreechart - java

I am building an application to check the similiairity between two java codes or more. Now, I have a data that I am store into a table. The code to build this table like this
public final class ASTParseUnit {
String IDLexer;
public ASTParseUnit(final IParserSelector parserSelector) {
this.parserSelector = parserSelector;
}
public String getIDLexer() {
return IDLexer;
}
public void setIDLexer(String iDLexer) {
IDLexer = iDLexer;
}
public ASTManager parse(final JCCDFile[] files) {
final ASTManager container = new ASTManager(
TipeNode.PROJECT.getTipe(), null);
JCCDFile temp;
temp = files[0];
String name = temp.getName();
String idLexerSeleksi = "";
StringBuilder nameOfFileMainFile = new StringBuilder();
StringBuilder countLevenstheins = new StringBuilder();
StringBuilder countJaccards = new StringBuilder();
StringBuilder countCosines = new StringBuilder();
for (final JCCDFile file : files) {
container.tandaiNodeRoot();
parseTree(file, container);
if (name.equals(file.getName())) {
idLexerSeleksi = getIDLexer();
}
LevenshteinDistance lv = new LevenshteinDistance();
SimilarityRunner sr = new SimilarityRunner(); // my class to count similiarity
if (idLexerSeleksi != getIDLexer()) {
nameOfFileMainFile.append(file.getName());
System.out.println(temp.getName() + " ==> " + file.getName());
countLevenstheins.append(lv.printDistance(idLexerSeleksi, getIDLexer()));
countJaccards.append(sr.hitungJaccard(idLexerSeleksi, getIDLexer()));
countCosines.append(sr.hitungCosine(idLexerSeleksi, getIDLexer()));
}
}
String enemy = nameOfMainFile.toString();
String resultOfLevenstheins = countLevenstheins.toString();
String resultOfJaccards = countJaccards.toString();
String resultOfCosines = countCosines.toString();
DefaultTableModel model = (DefaultTableModel) Main_Menu.jTable3.getModel();
List<Report3> theListData = new ArrayList<Report3>();
Report3 persentaseTabel = new Report3();
persentaseTabel.setMainFile(name);
persentaseTabel.setComparingFile(enemy);
persentaseTabel.setLevenstheins(resultOfLevenstheins);
persentaseTabel.setJaccard(resultOfJaccards);
persentaseTabel.setCosine(resultOfCosines);
theListData.add(persentaseTabel);
for (Report3 report3 : theListData) {
model.addRow(new Object[]{
report3.getMainFile(),
report3.getComparingFile(),
report3.getLevenstheins(),
report3.getJaccard(),
report3.getCosine(),});
}
return container;
}
Now, How can I representation that table into a jfreeChart ?
This is my jfreechart code...
public class LayeredBarChartDemo11 extends ApplicationFrame {
public LayeredBarChartDemo11(String s) {
super(s);
CategoryDataset dataset = createDataset();
JFreeChart chart = createChart(dataset);
ChartPanel chartPanel = new ChartPanel(chart);
chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));
setContentPane(chartPanel);
chartPanel.setMouseWheelEnabled(true);
//Main_menu is my form
Main_Menu.presentase.removeAll();
Main_Menu.presentase.setLayout(new java.awt.BorderLayout());
Main_Menu.presentase.add(chartPanel);
}
private static CategoryDataset createDataset() {
String s = "Levensthein";
String s1 = "Jaccard";
String s2 = "Cosine";
String s3 = "a.java";
String s4 = "b.java";
String s5 = "c.java";
DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
defaultcategorydataset.addValue(100D, s, s3);
defaultcategorydataset.addValue(20, s1, s3);
defaultcategorydataset.addValue(40D, s, s4);
defaultcategorydataset.addValue(170, s, s5);
defaultcategorydataset.addValue(69, s1, s4);
defaultcategorydataset.addValue(51, s1, s5);
defaultcategorydataset.addValue(32, s2, s3);
defaultcategorydataset.addValue(87, s2, s4);
defaultcategorydataset.addValue(68, s2, s5);
defaultcategorydataset.addValue(89, s2, s4);
defaultcategorydataset.addValue(8, s2, s5);
return defaultcategorydataset;
}
private static JFreeChart createChart(CategoryDataset categorydataset) {
JFreeChart jfreechart = ChartFactory.createBarChart("Persentase Kemiripan", "File Pembanding", "File Utama", categorydataset, PlotOrientation.HORIZONTAL, true, true, false);
CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot();
categoryplot.setDomainGridlinesVisible(true);
categoryplot.setRangePannable(true);
categoryplot.setRangeZeroBaselineVisible(true);
categoryplot.configureRangeAxes();
NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
LayeredBarRenderer layeredbarrenderer = new LayeredBarRenderer();
layeredbarrenderer.setDrawBarOutline(false);
categoryplot.setRenderer(layeredbarrenderer);
categoryplot.setRowRenderingOrder(SortOrder.DESCENDING);
GradientPaint gradientpaint = new GradientPaint(0.0F, 0.0F, Color.blue, 0.0F, 0.0F, new Color(0, 0, 64));
GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F, Color.green, 0.0F, 0.0F, new Color(0, 64, 0));
GradientPaint gradientpaint2 = new GradientPaint(0.0F, 0.0F, Color.red, 0.0F, 0.0F, new Color(64, 0, 0));
layeredbarrenderer.setSeriesPaint(0, gradientpaint);
layeredbarrenderer.setSeriesPaint(1, gradientpaint1);
layeredbarrenderer.setSeriesPaint(2, gradientpaint2);
return jfreechart;
}
public static JPanel createDemoPanel() {
JFreeChart jfreechart = createChart(createDataset());
ChartPanel chartpanel = new ChartPanel(jfreechart);
chartpanel.setMouseWheelEnabled(true);
return chartpanel;
}
This is my screenshot of my application https://www.dropbox.com/s/opmao5l9sy0df8v/New%20Picture%20%2810%29.png

Assuming that you want the chart to reflect the (possibly changing) table entries, add a TableModelListener to your TableModel. Based on the TableModelEvent received, update the CategoryDataset accordingly; the listening chart will update itself in response.
If the table model does not change after the query and comparison functions are evaluated, use JDBCCategoryDataset, mentioned here, to query the database; then construct the corresponding table model.

Related

How to change from line chart to bar chart

I have this line chart and want to make it a bar chart, but I'm new to Java and am not knowing if it possible since the x-axis is TimeSeries. This is the code I have that visualizes the line chart:
public class Time {
private static Time INSTANCE;
public static boolean isInitialized = false;
private Marker marker;
private Long markerStart;
private Long markerEnd;
private XYPlot plot;
long last_lowerBound;
long last_upperBound;
#Inject
public Time() {
}
Composite comp;
TimeSeriesCollection dataset;
ChartPanel panel;
JFreeChart chart;
protected Point endPoint;
#PostConstruct
public void postConstruct(Composite parent) {
comp = new Composite(parent, SWT.NONE | SWT.EMBEDDED);
Frame frame = SWT_AWT.new_Frame(comp);
JApplet rootContainer = new JApplet();
TimeSeries series = new TimeSeries("Timeline");
dataset = new TimeSeriesCollection();
String plotTitle = "";
String xaxis = "Time";
String yaxis = "Docs";
PlotOrientation orientation = PlotOrientation.VERTICAL;
boolean show = false;
boolean toolTips = true;
boolean urls = false;
chart = ChartFactory.createTimeSeriesChart(plotTitle, xaxis, yaxis, dataset, show, toolTips, urls );
// get a reference to the plot for further customisation...
plot = chart.getXYPlot();
plot.setBackgroundPaint(Color.white);
plot.setDomainGridlinePaint(Color.gray);
plot.setRangeGridlinePaint(Color.gray);
plot.setOutlinePaint(Color.white);
plot.getRangeAxis().setLabel("");
plot.getDomainAxis().setLabel("");
ValueAxis y_axis = plot.getRangeAxis(); // Y
ValueAxis x_axis = plot.getDomainAxis(); // X
Font font = new Font("Veranda", Font.PLAIN, 12);
y_axis.setTickLabelFont(font);
x_axis.setTickLabelFont(font);
x_axis.setTickLabelPaint(Color.black);
y_axis.setTickLabelPaint(Color.black);
plot.getDomainAxis().setAxisLineVisible(false);
final XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
// renderer.setSeriesLinesVisible(0, false);
renderer.setSeriesShapesVisible(0, false);
plot.setRenderer(renderer);
Should I only update this line: chart = ChartFactory.createTimeSeriesChart(plotTitle, xaxis, yaxis, dataset, show, toolTips, urls ); or I should change it completely?
I tried changing this part like this but it doesn't show anything:
dataset = new TimeSeriesCollection();
String plotTitle = "";
String xaxis = "Time";
String yaxis = "Docs";
PlotOrientation orientation = PlotOrientation.VERTICAL;
boolean show = false;
boolean toolTips = true;
boolean urls = false;
chart = ChartFactory.createBarChart(plotTitle, xaxis, yaxis, (CategoryDataset) dataset, orientation, show, toolTips, urls);
chart.setBackgroundPaint(null);
chart.setBackgroundImageAlpha(0.0f);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setRangeGridlinesVisible(false);
plot.setDomainGridlinesVisible(false);
plot.setOutlineVisible(false);
plot.setRangeZeroBaselineVisible(false);
plot.setDomainGridlinesVisible(false);
plot.setBackgroundPaint(COLOR_INVISIBLE);
plot.setBackgroundImageAlpha(0.0f);
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setSeriesPaint(0, AttributeGuiTools.getColorForValueType(Ontology.NOMINAL));
renderer.setBarPainter(new StandardBarPainter());
renderer.setDrawBarOutline(true);
renderer.setShadowVisible(false); } }
Any help would be highly appreciated!
Given a suitable XYDataset, such as IntervalXYDataset, you can replace ChartFactory.createTimeSeriesChart() with ChartFactory.createXYBarChart(), which provides for an optional DateAxis. The example below uses the same dataset to create both charts.
IntervalXYDataset dataset = createDataset();
f.add(createPanel(ChartFactory.createXYBarChart("Data", "Time", true, "Value", dataset)));
f.add(createPanel(ChartFactory.createTimeSeriesChart("Data", "Time", "Value", dataset)));
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.JFrame;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickMarkPosition;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.plot.XYPlot;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.time.Year;
import org.jfree.data.xy.IntervalXYDataset;
/**
* #see https://stackoverflow.com/a/54362133/230513
* #see https://stackoverflow.com/a/42612723/230513
*/
public class Test {
public static void main(String[] args) {
EventQueue.invokeLater(new Test()::display);
}
private void display() {
JFrame f = new JFrame("Data");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLayout(new GridLayout(0, 1));
IntervalXYDataset dataset = createDataset();
f.add(createPanel(ChartFactory.createXYBarChart("Data", "Time", true, "Value", dataset)));
f.add(createPanel(ChartFactory.createTimeSeriesChart("Data", "Time", "Value", dataset)));
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private ChartPanel createPanel(JFreeChart chart) {
final XYPlot plot = chart.getXYPlot();
final DateAxis domainAxis = (DateAxis) plot.getDomainAxis();
domainAxis.setTickUnit(new DateTickUnit(DateTickUnitType.YEAR, 1));
domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);
domainAxis.setDateFormatOverride(new SimpleDateFormat("yyyy"));
return new ChartPanel(chart) {
#Override
public Dimension getPreferredSize() {
return new Dimension(500, 250);
}
};
}
private IntervalXYDataset createDataset() {
TimeSeries series = new TimeSeries("Value");
Calendar c = Calendar.getInstance();
for (int i = 0; i < 7; i++) {
series.add(new Year(c.getTime()), i + 1);
c.add(Calendar.YEAR, 1);
}
return new TimeSeriesCollection(series);
}
}

How to use JFreeChart for custom renderer

first of: I am really having a problem with JFreechart and mainly I really believe that this is my fault because I start using the library without fully understanding how it fully function or use
second of: these are some helpful resource that helped me :
check it out 1
check it out 2
check it out 3
my current state : my problem is in making use of the drawPrimaryLine()
in my already build project so I am still having a problem in connecting the dots
in my way, not in a sequence way
example: if I enter (10,10) and (15,15) and (20,20) and (25,25) in this sequence, this is what I will end up with (the left side without connecting, the right side with connecting)
My problem is:
1 - when drawing a line is showing on the right side, I don't want the line to be generated or created until all of the points are add and the button done has been clicked *show in the most bottom right side
2 - I don't want the showing line to be in a sequence way I want the line to be shown base on some algorithm and not all dots will have or a line will pass through it, only a line will pass in some case.
so, in summary: not all dots will be connected only some based on an algorithm.
this is my code :
public class x_y_2 extends JFrame {
private static final String title = "Connecting The Dots";
private XYSeries added = new XYSeries("Added");
public List ls = new LinkedList<XYSeries>();
private XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
final XYSeriesCollection dataset = new XYSeriesCollection();
private XYPlot plot ;
public x_y_2(String s) {
super(s);
final ChartPanel chartPanel = createDemoPanel();
this.add(chartPanel, BorderLayout.CENTER);
JPanel control = new JPanel();
JLabel label = new JLabel("Enter 'x' value");
JTextField Field_x = new JTextField();
Field_x.setPreferredSize( new Dimension( 100, 24 ));
JLabel label2 = new JLabel("Enter 'y' value");
JTextField Field_y = new JTextField();
JLabel error = new JLabel("Importent*** in case no value is entered,value is set to '1' ");
error.setForeground(Color.RED);
Field_y.setPreferredSize( new Dimension( 100, 24 ));
control.add(label);
control.add(Field_x);
control.add(label2);
control.add(Field_y);
control.add(new JButton(new AbstractAction("Add") {
#Override
public void actionPerformed(ActionEvent e) {
if (Field_x.getText().isEmpty()) {
Field_x.setText("1"); ;
}
if (Field_y.getText().isEmpty()) {
Field_y.setText("1");
}
Double x = Double.parseDouble(Field_x.getText());
Double y = Double.parseDouble(Field_y.getText());
added.add(x,y);
ls.add(added);
Field_x.setText("");
Field_y.setText("");
}
}));
control.add(error);
control.add(new JButton(new AbstractAction("Done..") {
#Override
public void actionPerformed(ActionEvent e) {
label.setVisible(false);
label2.setVisible(false);
Field_x.setVisible(false);
Field_y.setVisible(false);
error.setVisible(false);
PrimaryLine pr = new PrimaryLine(3);
GraphingData graphingdata = new GraphingData(2,4,2,10);
// pr.drawPrimaryLine(state, g2, plot, dataset, pass, series, item, domainAxis, rangeAxis, dataArea);
System.out.println(ls.size());
for (int i = 0 ; i < ls.size() ; i++) {
XYSeries xy = (XYSeries)ls.get(i);
System.out.println(xy.getX(i) +" "+xy.getY(i));
}
}
}));
this.add(control, BorderLayout.SOUTH);
}
private XYDataset createSampleData() {
dataset.addSeries(added);
return dataset;
}
private ChartPanel createDemoPanel() {
JFreeChart jfreechart = ChartFactory.createXYLineChart(
title, "X", "Y", createSampleData(),PlotOrientation.VERTICAL, true, true, false);
plot =jfreechart.getXYPlot();
renderer.setSeriesLinesVisible(0, true);
renderer.setSeriesShapesVisible(0, true);
plot.setRenderer(renderer);
return new ChartPanel(jfreechart);
}}
second class :
public class GraphingData extends JPanel {
double x_st , y_st , x_ed, y_ed = 0;
public Graphics2D g2 ;
public GraphingData(double x_st,double y_st,double x_ed,double y_ed) {
this.x_st = x_st ;
this.y_st = y_st;
this.x_ed = x_ed;
this.y_ed = y_ed;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
g2.draw(new Line2D.Double(x_st,y_st,x_ed, y_ed));
}
}
Third Class :
public class PrimaryLine extends XYLineAndShapeRenderer {
private final int anchor;
public PrimaryLine(int acnchor) {
this.anchor = acnchor;
}
#Override
protected void drawPrimaryLine(XYItemRendererState state, Graphics2D g2,
XYPlot plot, XYDataset dataset, int pass, int series, int item,
ValueAxis domainAxis, ValueAxis rangeAxis, Rectangle2D dataArea) {
if (item == anchor) {
return;
}
}
public void chart() {
PrimaryLine r = new PrimaryLine(8);
XYPlot plot = new XYPlot(createSampleData(),new NumberAxis("X"), new
NumberAxis("Y"), r);
JFreeChart chart = new JFreeChart(plot);
}
private XYDataset createSampleData() {
XYSeriesCollection xySeriesCollection = new XYSeriesCollection();
XYSeries added = new XYSeries("added");
added.add(4,2);
added.add(2,1);
xySeriesCollection.addSeries(added);
return xySeriesCollection;
}
}
Any kinda of help I would be greatfull for .

Setting foreground colour specific index of JComboBox

Changing foreground colour of a specified index of items in a JComboBox.
Eg,
if (number <= 1) { set the first item of the JComboBox to Red. }
Any way to do this without using CellRenderer? Never ever used CellRenderer before, no experience at all..
Already looked at these sites:
Changing a color chooser button's background color in Java,
Multiple Colors for Each Item in JComboBox, Colored jcombobox with colored items and focus
3rd one seems to be the most useful but no idea on how to implement..
Thank you.
Codes For Frame:
public class CreateBedForm extends JFrame {
private JPanel contentPane;
private JTextField textFieldPatientID;
private JTextField textFieldPatientName;
private JComboBox comboBoxAllocateBed;
private JComboBox comboBoxDpt;
private String bedStatusF = "Available";
private String selectedDepartment = "";
private int bedsAvailCardio;
private int bedsAvailOncology;
private int bedsAvailOrtho;
private int bedsAvailPediatric;
String[] departments = {"--Select Department--", "Cardiothoracic", "Oncology", "Orthopaedic", "Pediatric"};
Color comboBoxColour = new Color(0, 204, 0);
Color[] colorsForMain = {Color.BLACK, comboBoxColour, comboBoxColour, comboBoxColour, comboBoxColour};
Color[] colorsForCardiothoracic = {Color.BLACK, Color.RED, comboBoxColour, comboBoxColour, comboBoxColour};
Color[] colorsForOncology = {Color.BLACK, comboBoxColour, Color.RED, comboBoxColour, comboBoxColour};
Color[] colorsForOrthopaedic = {Color.BLACK, comboBoxColour, comboBoxColour, Color.RED, comboBoxColour};
Color[] colorsForPediatric = {Color.BLACK, comboBoxColour, comboBoxColour, comboBoxColour, Color.RED};
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
CreateBedForm frame = new CreateBedForm("", "", "");
frame.setVisible(true);
frame.setLocationRelativeTo(null);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public CreateBedForm(String val1, String val2, String admissionID) {
setTitle("Assign Bed");
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
setBounds(100, 100, 450, 400);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblPatientId = new JLabel("Patient ID:");
lblPatientId.setBounds(42, 52, 71, 16);
contentPane.add(lblPatientId);
JLabel lblPatientName = new JLabel("Patient Name:");
lblPatientName.setBounds(42, 97, 96, 16);
contentPane.add(lblPatientName);
textFieldPatientID = new JTextField();
textFieldPatientID.setEditable(false);
textFieldPatientID.setBounds(138, 49, 116, 22);
contentPane.add(textFieldPatientID);
textFieldPatientID.setColumns(10);
textFieldPatientName = new JTextField();
textFieldPatientName.setEditable(false);
textFieldPatientName.setBounds(138, 94, 116, 22);
contentPane.add(textFieldPatientName);
textFieldPatientName.setColumns(10);
JLabel lblAllocatedBed = new JLabel("Allocated Bed:");
lblAllocatedBed.setBounds(42, 183, 96, 16);
contentPane.add(lblAllocatedBed);
comboBoxAllocateBed = new JComboBox();
comboBoxAllocateBed.setBounds(138, 180, 71, 22);
contentPane.add(comboBoxAllocateBed);
JLabel lblNewLabel = new JLabel("Department:");
lblNewLabel.setBounds(42, 142, 96, 16);
contentPane.add(lblNewLabel);
JButton btnAssignBed = new JButton("Assign Bed");
btnAssignBed.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Adding
String patientID = textFieldPatientID.getText();
String patientName = textFieldPatientName.getText();
String selectedDepartment = comboBoxDpt.getSelectedItem().toString();
String selectedBed = comboBoxAllocateBed.getSelectedItem().toString();
ChangeBed cb = new ChangeBed(selectedBed, selectedDepartment, patientID, patientName);
ChangeBedControl cbc = new ChangeBedControl();
cbc.processAssignBeds(cb, selectedBed);
//Updating
bedStatusF = "Unavailable";
ChangeBed cb2 = new ChangeBed(selectedBed, selectedDepartment, patientID, patientName);
ChangeBedControl cbc2 = new ChangeBedControl();
cbc2.processAssignBeds2(cb2, selectedBed, bedStatusF);
dispose();
File desktop = new File(System.getProperty("user.home"), "/Desktop");
Document document = new Document(PageSize.A4.rotate());
com.itextpdf.text.Font font1 = FontFactory.getFont("Verdana", 25, Font.BOLD);
com.itextpdf.text.Font font2 = FontFactory.getFont("Verdana", 15, Font.BOLD);
Paragraph p = new Paragraph(("Patient Admission Details"), font1);
Paragraph p1 = new Paragraph(("Admission ID"), font2);
Paragraph p2 = new Paragraph(("Patient ID"), font2);
Paragraph p3 = new Paragraph(("Patient Name"), font2);
Paragraph p4 = new Paragraph(("Date and Time Admitted"), font2);
Paragraph p5 = new Paragraph(("Reason"), font2);
Paragraph p6 = new Paragraph(("Date and Time Discharged"), font2);
Paragraph pp = new Paragraph(("Bed Allocation Details"), font1);
Paragraph p01 = new Paragraph(("Bed ID"), font2);
Paragraph p02 = new Paragraph(("Department"), font2);
try {
PageSize.A4.rotate();
PdfWriter.getInstance(document, new FileOutputStream(desktop + "/" + textFieldPatientName.getText() + " Admission.pdf"));
document.open();
document.add(p);
PdfPTable table = new PdfPTable(6);
table.setWidthPercentage(102);
PdfPCell cell1 = new PdfPCell();
cell1.addElement(p1);
PdfPCell cell2 = new PdfPCell();
cell2.addElement(p2);
PdfPCell cell3 = new PdfPCell();
cell3.addElement(p3);
PdfPCell cell4 = new PdfPCell();
cell4.addElement(p4);
PdfPCell cell5 = new PdfPCell();
cell5.addElement(p5);
PdfPCell cell6 = new PdfPCell();
cell6.addElement(p6);
AdmissionInfoControl aic1 = new AdmissionInfoControl();
ArrayList<AdmissionInfo> admissionList = new ArrayList<AdmissionInfo>();
admissionList = aic1.processGetAdmissionInfoView(admissionID);
PdfPCell ell1;
PdfPCell ell2;
PdfPCell ell3;
PdfPCell ell4;
PdfPCell ell5;
PdfPCell ell6;
for (int i = 0; i < admissionList.size(); i++) {
ell1 = new PdfPCell(new Paragraph(admissionList.get(i).getAdmissionID()));
ell2 = new PdfPCell(new Paragraph(admissionList.get(i).getPatientID()));
ell3 = new PdfPCell(new Paragraph(admissionList.get(i).getPatientName()));
ell4 = new PdfPCell(new Paragraph(admissionList.get(i).getDateAdmitted()));
ell5 = new PdfPCell(new Paragraph(admissionList.get(i).getReason()));
ell6 = new PdfPCell(new Paragraph(admissionList.get(i).getDateDischarged()));
table.setSpacingBefore(30f);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
table.addCell(cell4);
table.addCell(cell5);
table.addCell(cell6);
table.addCell(ell1);
table.addCell(ell2);
table.addCell(ell3);
table.addCell(ell4);
table.addCell(ell5);
table.addCell(ell6);
}
document.add(table);
document.add(pp);
PdfPTable table2 = new PdfPTable(2);
table2.setHorizontalAlignment(Element.ALIGN_LEFT);
table2.setWidthPercentage(50);
PdfPCell cell01 = new PdfPCell();
cell01.addElement(p01);
PdfPCell cell02 = new PdfPCell();
cell02.addElement(p02);
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
bedList = cbc.processGetBedsEdit(textFieldPatientID.getText());
PdfPCell ell01;
PdfPCell ell02;
for (int i = 0; i < bedList.size(); i++) {
ell01 = new PdfPCell(new Paragraph(bedList.get(i).getBedID()));
ell02 = new PdfPCell(new Paragraph(bedList.get(i).getDepartment()));
table2.setSpacingBefore(30f);
table2.addCell(cell01);
table2.addCell(cell02);
table2.addCell(ell01);
table2.addCell(ell02);
}
document.add(table2);
document.close();
JOptionPane.showMessageDialog(null, "Admission PDF has been successfully created.");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
}
});
btnAssignBed.setBounds(288, 303, 116, 25);
contentPane.add(btnAssignBed);
comboBoxDpt = new JComboBox();
comboBoxDpt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String departmentSelection = comboBoxDpt.getSelectedItem().toString();
ChangeBedControl cbcS = new ChangeBedControl();
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
bedList = cbcS.processGetAvailBedsEdit(bedStatusF, departmentSelection);
comboBoxAllocateBed.removeAllItems();
for (int i = 0; i < bedList.size(); i++) {
comboBoxAllocateBed.addItem(bedList.get(i).getBedID());
}
}
});
//comboBoxDpt.setModel(new DefaultComboBoxModel(new String[] {"--Select Department--", "Cardiothoracic", "Oncology", "Orthopaedic", "Pediatric"}));
comboBoxDpt = new JComboBox();
ComboBoxRenderer renderer = new ComboBoxRenderer(comboBoxDpt);
renderer.setColorsForMain(colorsForMain);
renderer.setDepartments(departments);
comboBoxDpt.setRenderer(renderer);
comboBoxDpt.setBounds(138, 139, 153, 22);
contentPane.add(comboBoxDpt);
ChangeBedControl cbc = new ChangeBedControl();
ArrayList<AdmissionInfo> admissionList = new ArrayList<AdmissionInfo>();
admissionList = cbc.processGetChangeBedCreate(val1, val2);
for (int i = 0; i < admissionList.size(); i++) {
textFieldPatientID.setText(admissionList.get(i).getPatientID());
textFieldPatientName.setText(admissionList.get(i).getPatientName());
}
//=============Distinct Feature=============
ArrayList<ChangeBed> bedList = new ArrayList<ChangeBed>();
int selectedIndex = comboBoxDpt.getSelectedIndex() ;
String departmentComboBox;
ChangeBedControl cbc2 = new ChangeBedControl();
bedList = cbc2.processCountBedsAvailableDpt1();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailCardio = bedList.get(i).getRowCountAvail();
}
if (bedsAvailCardio <= 3) {
}
ChangeBedControl cbc4 = new ChangeBedControl();
bedList = cbc4.processCountBedsAvailableDpt2();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailOncology = bedList.get(i).getRowCountAvail();
}
if (bedsAvailOncology <= 3) {
}
ChangeBedControl cbc6 = new ChangeBedControl();
bedList = cbc6.processCountBedsAvailableDpt3();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailOrtho = bedList.get(i).getRowCountAvail();
}
if (bedsAvailOrtho <= 3) {
}
ChangeBedControl cbc8 = new ChangeBedControl();
bedList = cbc8.processCountBedsAvailableDpt4();
for (int i = 0; i < bedList.size(); i++) {
bedsAvailPediatric = bedList.get(i).getRowCountAvail();
}
if (bedsAvailPediatric <= 3) {
}
}
}
Codes for ComboBoxRenderer Class:
public class ComboBoxRenderer implements ListCellRenderer{
private Color comboBoxColour;
private Color[] colorsForMain;
private Color[] colorsForCardiothoracic;
private Color[] colorsForOncology;
private Color[] colorsForOrthopaedic;
private Color[] colorsForPediatric;
private String[] departments;
public ComboBoxRenderer() {};
public ComboBoxRenderer(JComboBox comboBoxDpt) {
}
public String[] getDepartments() {
return departments;
}
public void setDepartments(String[] departments) {
this.departments = departments;
}
public Color getComboBoxColour() {
return comboBoxColour;
}
public void setComboBoxColour(Color comboBoxColour) {
this.comboBoxColour = comboBoxColour;
}
public Color[] getColorsForMain() {
return colorsForMain;
}
public void setColorsForMain(Color[] colorsForMain) {
this.colorsForMain = colorsForMain;
}
public Color[] getColorsForCardiothoracic() {
return colorsForCardiothoracic;
}
public void setColorsForCardiothoracic(Color[] colorsForCardiothoracic) {
this.colorsForCardiothoracic = colorsForCardiothoracic;
}
public Color[] getColorsForOncology() {
return colorsForOncology;
}
public void setColorsForOncology(Color[] colorsForOncology) {
this.colorsForOncology = colorsForOncology;
}
public Color[] getColorsForOrthopaedic() {
return colorsForOrthopaedic;
}
public void setColorsForOrthopaedic(Color[] colorsForOrthopaedic) {
this.colorsForOrthopaedic = colorsForOrthopaedic;
}
public Color[] getColorsForPediatric() {
return colorsForPediatric;
}
public void setColorsForPediatric(Color[] colorsForPediatric) {
this.colorsForPediatric = colorsForPediatric;
}
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
return list;
}
}
If you look at the second link you provided you can see the following line of code:
static Color[] colors = {Color.BLUE, Color.GRAY, Color.RED};
Each index of the colors array matches the index of the String objects in the JComboBox.
In your case, because you want the first index to be red, you would make the first index of the color array to be red:
static Color[] colors = {Color.BLUE, Color.RED, Color.BLUE}; //Index # 1 is red.

How to Overcome the JFreeChart Issue?

I'm using the Jfree chart in my struts application. Y-Axis is Over Shipment Pieces and X-Axis is Supplier Code and secondary axis is used for the Over Shipment %. What the problem i faced here is , If the Over Shipment % values all comes to Zero it hide the X-Axis Supplier Value also. How can i overcome to avoid this. I have attached here screen shot for your consideration. Thanks to all to read this question.
I pasted my code here for your clear understanding,
/**
*
* #param response
* #throws IOException
*/
public void writeOccurrenceBasedParetoChart(HttpServletResponse response) throws IOException
{
String METHOD_NAME = "writeOccurrenceBasedParetoChart";
log.entering(CLASS_NAME, METHOD_NAME);
CategoryDataset dataset1 = createDataSetForPercentBasedChart1();
CategoryDataset dataset2 = createDataSetForPercentBasedChart2();
String rangeAxisLabel = "";
String numOfSupplrs = "";
//Behind Schedule "4"
if(searchRatingElement.equalsIgnoreCase("4"))
{
System.out.println("*******************searchRatingElement"+searchRatingElement);
rangeAxisLabel = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpcs");
}
else
{
rangeAxisLabel = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpcs");
}
JFreeChart chart = ChartFactory.createBarChart(
"", // chart title
"", // domain axis label
rangeAxisLabel, // range axis label
dataset1, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips?
false // URLs?
);
// NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
// set the background color for the chart...
chart.setBackgroundPaint(Color.white);
CategoryPlot plot = (CategoryPlot) chart.getPlot();
plot.setBackgroundPaint(Color.lightGray);
plot.setDataset(1, dataset2);
plot.mapDatasetToRangeAxis(1, 1);
CategoryItemRenderer renderer1 = plot.getRenderer();
renderer1.setSeriesItemLabelGenerator(0,new CategoryItemLabelGenerator() {
public String generateRowLabel(final CategoryDataset arg0, final int arg1) {
// TODO Auto-generated method stub
return null;
}
public String generateLabel(final CategoryDataset dataset1,final int series,final int category) {
String result = null;
//CHAPTER 12. ITEM LABELS 91
final Number value = dataset1.getValue(series, category);
if (value != null) {
final double v = value.doubleValue();
if (v > 0) {
result = value.toString(); // could apply formatting here
}
}
return result;
}
public String generateColumnLabel(final CategoryDataset arg0, final int arg1) {
// TODO Auto-generated method stub
return null;
}
});
renderer1.setSeriesItemLabelsVisible(0,true);
BarRenderer renderer = (BarRenderer) plot.getRenderer();
renderer.setDrawBarOutline(false);
renderer.setSeriesOutlinePaint(0,Color.BLACK);
renderer.setDrawBarOutline(true);
renderer.setMaximumBarWidth(0.02);
renderer.setSeriesPaint(0,new Color(170, 0, 85));
CategoryAxis domainAxis = plot.getDomainAxis();
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(.6));
domainAxis.setLabelFont(new Font("Helvetica", Font.BOLD, 14));
domainAxis.setTickLabelFont(new Font("Helvetica", Font.BOLD, 14));
//Behind Schedule "4"
if(searchRatingElement.equalsIgnoreCase("4"))
{
System.out.println("||||||||||||||||||||||||||||||||searchRatingElement"+searchRatingElement);
numOfSupplrs = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.bhndschpctforchart");
}
else
{
numOfSupplrs = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpctforchart");
}
ValueAxis axis2 = new NumberAxis(numOfSupplrs);
axis2.setLabelFont(new Font("Helvetica", Font.BOLD, 14));
axis2.setTickLabelFont(new Font("Helvetica", Font.PLAIN, 14));
//if(!this.isValueDataZeros)
//axis2.setRange(0,13);
plot.setRangeAxis(1, axis2);
NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
// if(!this.isNumberDataZeros)
//rangeAxis.setRange(0,90);
//rangeAxis.setTickUnit(new NumberTickUnit(1));
rangeAxis.setLabelFont(new Font("Helvetica", Font.BOLD, 14));
rangeAxis.setTickLabelFont(new Font("Helvetica", Font.PLAIN, 14));
LineAndShapeRenderer renderer2 = new LineAndShapeRenderer();
renderer2.setSeriesPaint(0, Color.BLUE);
/*Start */
renderer2.setSeriesItemLabelGenerator(0,new CategoryItemLabelGenerator() {
public String generateRowLabel(final CategoryDataset arg0, final int arg1) {
// TODO Auto-generated method stub
return null;
}
public String generateLabel(final CategoryDataset dataset1,final int series,final int category) {
String result = null;
//CHAPTER 12. ITEM LABELS 91
final Number value = dataset1.getValue(series, category);
if (value != null) {
final double v = value.doubleValue();
if (v > 0) {
result = value.toString(); // could apply formatting here
}
}
return result;
}
public String generateColumnLabel(final CategoryDataset arg0, final int arg1) {
// TODO Auto-generated method stub
return null;
}
});
renderer2.setSeriesItemLabelsVisible(0,true);
/* End */
plot.setRenderer(1, renderer2);
plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);
ChartUtilities.writeChartAsPNG(response.getOutputStream(), chart,
1150, 450);
}
/**
*
*/
public DefaultCategoryDataset createDataSetForPercentBasedChart1()
{
String METHOD_NAME = "createDataSetForPercentBasedChart1";
log.entering(CLASS_NAME, METHOD_NAME);
DefaultCategoryDataset dataSetForOccurrenceBasedChart = new DefaultCategoryDataset();
boolean flagForPercentPareto = false;
String occurrenceCountLabelName = null;
try
{
if(paretoReportBasedDataQO != null && paretoReportBasedDataQO.size()>0)
{
//Behind Schedule "4"
if(searchRatingElement.equalsIgnoreCase("4"))
{
occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.bhndschpctforchart");
}
else
{
occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpcs");
}
if(!flagForPercentPareto)
{
for(int i =0;i<paretoReportBasedDataQO.size();i++)
{
dataSetForOccurrenceBasedChart.addValue(paretoReportBasedDataQO.get(i).getOverShipmentPiecesCount(), occurrenceCountLabelName, paretoReportBasedDataQO.get(i).getSupplierName());
}
}
}
}
catch(Exception exceptionOccurrenceBasedChart)
{
flagForPercentPareto = true;
System.out.println("Exception In createDataSetForPercentBasedChart1 : "+exceptionOccurrenceBasedChart.getMessage());
}
log.exiting(CLASS_NAME, METHOD_NAME);
return dataSetForOccurrenceBasedChart;
}
/**
*
*/
public DefaultCategoryDataset createDataSetForPercentBasedChart2()
{
String METHOD_NAME = "createDataSetForPercentBasedChart2";
log.entering(CLASS_NAME, METHOD_NAME);
DefaultCategoryDataset dataSetForOccurrenceBasedChart = new DefaultCategoryDataset();
boolean flagForPercentPareto = false;
String occurrenceCountLabelName = null;
try
{
if(paretoReportBasedDataQO != null && paretoReportBasedDataQO.size()>0)
{
if(searchRatingElement.equalsIgnoreCase("4"))
{
occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.bhndschpctforchart");
}
else
{
occurrenceCountLabelName = I18nMessageUtil.getMessage(CommonUtil.getLocale(), "label.reports.wdid.ovrshptpctforchart");
}
if(!flagForPercentPareto)
{
for(int i =0;i<paretoReportBasedDataQO.size();i++)
{
dataSetForOccurrenceBasedChart.addValue(paretoReportBasedDataQO.get(i).getOverShipmentPercentageCount(), occurrenceCountLabelName, paretoReportBasedDataQO.get(i).getSupplierName());
}
}
}
}
catch(Exception exceptionOccurrenceBasedChart)
{
flagForPercentPareto = true;
System.out.println("Exception In createDataSetForPercentBasedChart2 : "+exceptionOccurrenceBasedChart.getMessage());
}
log.exiting(CLASS_NAME, METHOD_NAME);
return dataSetForOccurrenceBasedChart;
}
What if you put the label in another position?
For example:
renderer.setBasePositiveItemLabelPosition(
new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER));

JFreeChart throws exception on getSeriesVisible

I am trying to run the following code and it throws exception on getSeriesVisible:
chart.addChangeListener(new ChartChangeListener() {
int indexChanged = -1;
#Override
public void chartChanged(ChartChangeEvent event) {
XYPlot ff = chart.getXYPlot();
XYItemRenderer y = ff.getRenderer();
boolean b = y.getSeriesVisible(0);
// chart.getXYPlot().getRenderer().setSeriesVisible(0, b);
}
});
Message: Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
ANy ideas?
UPDATE: I am adding a couple of series and generating chart as follows:
XYSeriesCollection data = new XYSeriesCollection();
XYSeries series = new XYSeries("Series 1", true);
series.add(1, 2);
series.add(3, 5);
series.add(8, 10);
series.add(11, 3);
series.add(8, 10);
data.addSeries(series);
series = new XYSeries("Series 2");
series.add(5, -2);
series.add(7, 6);
series.add(8, 12);
series.add(11, -2);
series.add(15, 10);
data.addSeries(series);
final JFreeChart chart = ChartFactory.createXYLineChart("Chart", "X", "Y", data, PlotOrientation.VERTICAL, true, true, false);
It must be somewhere else in your code. I see the expected result from this example using the modified addButton() listener below.
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n = dataset.getSeriesCount();
dataset.addSeries("Series" + n, createSeries(n));
XYPlot plot = chart.getXYPlot();
XYItemRenderer renderer = plot.getRenderer();
System.out.println(renderer.isSeriesVisible(n));
}
});

Categories