List of usage examples for java.awt Color magenta
Color magenta
To view the source code for java.awt Color magenta.
Click Source Link
From source file:projekt.CustomRenderer.java
public void raport_globalny() throws IOException, ClassNotFoundException, SQLException { String zapytanie = "select count(*) as Aktualne from zadania where Status_zadania='Aktualne'"; String zapytanie1 = "select count(*) as FORTEST from zadania where Status_zadania='FORTEST'"; String zapytanie2 = "select count(*) as Zakonczone from zadania where Status_zadania='Zakonczone'"; Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pz?characterEncoding=utf8", "root", ""); PreparedStatement statment;/* w w w . j a v a 2 s. co m*/ ResultSet result; double odp = 0, odp1 = 0, odp2 = 0; statment = con.prepareStatement(zapytanie); result = statment.executeQuery(); if (result.next()) { odp = result.getDouble("Aktualne"); } statment = con.prepareStatement(zapytanie1); result = statment.executeQuery(); if (result.next()) { odp1 = result.getDouble("FORTEST"); } statment = con.prepareStatement(zapytanie2); result = statment.executeQuery(); if (result.next()) { odp2 = result.getDouble("Zakonczone"); } loginController login = new loginController(); statment = con.prepareStatement( "SELECT CONCAT(imie, ' ', nazwisko) as osoba from uzytkownicy WHERE idUzytkownika = '" + login.uzytkownikID + "'"); result = statment.executeQuery(); String bbc = ""; if (result.next()) { bbc = result.getString(1); } DefaultCategoryDataset set2 = new DefaultCategoryDataset(); set2.setValue(odp, "", "Aktualne"); set2.setValue(odp1, "", "FORTEST"); set2.setValue(odp2, "", "Zakonczone"); JFreeChart chart = ChartFactory.createBarChart("Wszystkie zadania w bazie", "Zadania", "Ilosc", set2, PlotOrientation.VERTICAL, false, true, false); final CategoryItemRenderer renderer = new CustomRenderer(new Paint[] { Color.red, Color.blue, Color.green, Color.yellow, Color.orange, Color.cyan, Color.magenta, Color.blue }); final CategoryPlot plot = chart.getCategoryPlot(); plot.setNoDataMessage("NO DATA!"); renderer.setItemLabelsVisible(true); final ItemLabelPosition p = new ItemLabelPosition(ItemLabelAnchor.CENTER, TextAnchor.CENTER, TextAnchor.CENTER, 45.0); renderer.setPositiveItemLabelPosition(p); plot.setRenderer(renderer); ByteArrayOutputStream out = new ByteArrayOutputStream(); ChartUtilities.writeChartAsJPEG(out, chart, 450, 600); DateFormat dataformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); DateFormat dataformat1 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss"); Date data = new Date(); String fileName = "Raport globalny " + dataformat1.format(data) + ".pdf"; try { PDRectangle PAGE_SIZE = PDRectangle.A4; PDDocument doc = new PDDocument(); PDFont font = PDType0Font.load(doc, getClass().getResourceAsStream("/fonts/RobotoCondensed-Regular.ttf")); PDFont font1 = PDType0Font.load(doc, getClass().getResourceAsStream("/fonts/RobotoCondensed-Bold.ttf")); PDPage page = new PDPage(PAGE_SIZE); PDPage page1 = new PDPage(PAGE_SIZE); doc.addPage(page); PDPageContentStream content = new PDPageContentStream(doc, page); //naglowek strona 1 Naglowek(content, dataformat, data); //stopka strona1 Stopka(content, doc); content.beginText(); content.setFont(font1, 48); content.moveTextPositionByAmount(135, 550); content.showText("Raport globalny"); content.endText(); content.beginText(); content.setFont(font, 22); content.moveTextPositionByAmount(30, 250); content.showText("Wersja systemu : 1.0"); content.newLine(); content.moveTextPositionByAmount(0, 35); content.showText("Autor raportu : " + result.getString("osoba")); content.endText(); content.close(); PDPageContentStream content1 = new PDPageContentStream(doc, page1); PDPage page2 = new PDPage(PAGE_SIZE); doc.addPage(page2); PDPageContentStream content2 = new PDPageContentStream(doc, page2); Naglowek(content2, dataformat, data); //stopka strona2 Stopka(content2, doc); content2.beginText(); content2.setFont(font, 14); content2.moveTextPositionByAmount(30, 775); content2.showText("Wszystkie projekty z bazy danych:"); statment = con.prepareStatement("Select Nazwa, Opis, Poczatek, Koniec, ludzie from projekty"); result = statment.executeQuery(); content2.newLine(); int liczba = 615; content2.moveTextPositionByAmount(0, -15); while (result.next()) { content2.newLine(); content2.moveTextPositionByAmount(0, -22); liczba += 22; //content2.showText("Nazwa : "+result.getString("Nazwa")+" Opis: "+result.getString("Opis")+" Data rozpoczecia: "+result.getString("Poczatek")+" Data zakonczenia: "+result.getString("Koniec")); content2.showText("Nazwa : " + result.getString("Nazwa") + " Opis: " + result.getString("Opis")); content2.newLine(); content2.moveTextPositionByAmount(0, -17); liczba += 22; content2.showText("Data rozpoczecia: " + result.getString("Poczatek") + " Data zakonczenia: " + result.getString("Koniec")); } content2.endText(); // content2.setLineWidth(2); // content2.moveTo(10, liczba + 5); // content2.lineTo(10, liczba +5); // content2.closeAndStroke(); DateFormat dataformat2 = new SimpleDateFormat("yyyy-MM-dd"); statment = con.prepareStatement("Select count(*) as 'Aktualne' from projekty where Koniec > '" + dataformat2.format(data) + "'"); result = statment.executeQuery(); int aktualne = 0, zakonczone = 0; if (result.next()) { aktualne = result.getInt("Aktualne"); } System.out.println("aktualne:" + aktualne); statment = con.prepareStatement("Select count(*) as 'Zakonczone' from projekty where Koniec < '" + dataformat2.format(data) + "'"); result = statment.executeQuery(); if (result.next()) { zakonczone = result.getInt("Zakonczone"); } System.out.println("zakonczone:" + zakonczone); DefaultPieDataset pieDataset = new DefaultPieDataset(); pieDataset.setValue("Aktualne", aktualne); pieDataset.setValue("Zakonczone", zakonczone); JFreeChart chart1 = ChartFactory.createPieChart("Zestawienia projektw", // Title pieDataset, // Dataset true, // Show legend true, // Use tooltips false // Configure chart to generate URLs? ); PiePlot plot1 = (PiePlot) chart1.getPlot(); plot1.setSectionPaint("Aktualne", Color.green); plot1.setSectionPaint("Zakonczone", Color.red); plot1.setExplodePercent("Aktualne", 0.10); plot1.setSimpleLabels(true); PieSectionLabelGenerator gen = new StandardPieSectionLabelGenerator("{0}: {1} ({2})", new DecimalFormat("0"), new DecimalFormat("0%")); plot1.setLabelGenerator(gen); ByteArrayOutputStream out1 = new ByteArrayOutputStream(); ChartUtilities.writeChartAsJPEG(out1, chart1, 450, 600); PDImageXObject img1 = JPEGFactory.createFromStream(doc, new ByteArrayInputStream(out1.toByteArray())); content2.close(); PDPage page3 = new PDPage(PAGE_SIZE); doc.addPage(page3); PDPageContentStream content3 = new PDPageContentStream(doc, page3); Naglowek(content3, dataformat, data); //stopka strona2 Stopka(content3, doc); content3.drawImage(img1, 50, 50); content3.close(); PDPage page4 = new PDPage(PAGE_SIZE); doc.addPage(page4); PDPageContentStream content4 = new PDPageContentStream(doc, page4); Naglowek(content4, dataformat, data); //stopka strona2 Stopka(content4, doc); content4.beginText(); content4.setFont(font, 14); content4.moveTextPositionByAmount(30, 780); content4.showText("Wszystkie zadania w bazie:"); statment = con.prepareStatement( "SELECT `Nazwa`,`Opis`,`Status_zadania`,`projekt`, CONCAT(x.imie, \" \", x.nazwisko) as \"UZY\" FROM `zadania` , (SELECT imie, nazwisko, idUzytkownika from uzytkownicy) X WHERE zadania.idUzytkownika=x.idUzytkownika limit 12"); result = statment.executeQuery(); content4.newLine(); int nw = 850; content4.moveTextPositionByAmount(0, -15); nw -= 15; while (result.next()) { content4.newLine(); nw -= 22; content4.moveTextPositionByAmount(0, -22); //content2.showText("Nazwa : "+result.getString("Nazwa")+" Opis: "+result.getString("Opis")+" Data rozpoczecia: "+result.getString("Poczatek")+" Data zakonczenia: "+result.getString("Koniec")); content4.showText("Nazwa : " + result.getString("Nazwa")); content4.newLine(); nw -= 17; content4.moveTextPositionByAmount(0, -17); content4.showText(" Opis: " + result.getString("Opis") + " Status zadania: " + result.getString("Status_zadania")); content4.newLine(); nw -= 17; content4.moveTextPositionByAmount(0, -17); content4.showText(" Projekt: " + result.getString("projekt") + " Przydzielona osoba do zadania: " + result.getString("UZY")); } content4.endText(); content4.close(); statment = con.prepareStatement("SELECT count(*) as 'liczba' FROM `zadania`"); result = statment.executeQuery(); if (result.next()) { } statment = con.prepareStatement( "SELECT `Nazwa`,`Opis`,`Status_zadania`,`projekt`, CONCAT(x.imie, \" \", x.nazwisko) as \"UZY\" FROM `zadania` , (SELECT imie, nazwisko, idUzytkownika from uzytkownicy) X WHERE zadania.idUzytkownika=x.idUzytkownika limit 12," + result.getInt(1) + ""); result = statment.executeQuery(); PDPage page5 = new PDPage(PAGE_SIZE); doc.addPage(page5); PDPageContentStream content5 = new PDPageContentStream(doc, page5); Naglowek(content5, dataformat, data); //stopka strona2 Stopka(content5, doc); content5.beginText(); content5.setFont(font, 14); content5.moveTextPositionByAmount(30, 700); while (result.next()) { content5.newLine(); nw -= 22; content5.moveTextPositionByAmount(0, -22); //content2.showText("Nazwa : "+result.getString("Nazwa")+" Opis: "+result.getString("Opis")+" Data rozpoczecia: "+result.getString("Poczatek")+" Data zakonczenia: "+result.getString("Koniec")); content5.showText("Nazwa : " + result.getString("Nazwa")); content5.newLine(); nw -= 17; content5.moveTextPositionByAmount(0, -17); content5.showText(" Opis: " + result.getString("Opis") + " Status zadania: " + result.getString("Status_zadania")); content5.newLine(); nw -= 17; content5.moveTextPositionByAmount(0, -17); content5.showText(" Projekt: " + result.getString("projekt") + " Przydzielona osoba do zadania: " + result.getString("UZY")); } content5.endText(); content5.close(); doc.addPage(page1); //naglowek strona 2 Naglowek(content1, dataformat, data); //stopka strona2 Stopka(content1, doc); PDImageXObject img = JPEGFactory.createFromStream(doc, new ByteArrayInputStream(out.toByteArray())); content1.drawImage(img, 50, 50); content1.close(); doc.save(fileName); doc.close(); } catch (Exception e) { System.err.println(e.getMessage()); } }
From source file:org.pentaho.reporting.engine.classic.core.modules.output.pageable.graphics.internal.LogicalPageDrawable.java
protected void drawOutlineBox(final Graphics2D g2, final RenderBox box) { final int nodeType = box.getNodeType(); if (nodeType == LayoutNodeTypes.TYPE_BOX_PARAGRAPH) { g2.setPaint(Color.magenta); } else if (nodeType == LayoutNodeTypes.TYPE_BOX_LINEBOX) { g2.setPaint(Color.orange); } else if ((nodeType & LayoutNodeTypes.MASK_BOX_TABLE) == LayoutNodeTypes.MASK_BOX_TABLE) { g2.setPaint(Color.cyan);//from w w w . j a v a 2s. c o m } else { g2.setPaint(Color.lightGray); } final double x = StrictGeomUtility.toExternalValue(box.getX()); final double y = StrictGeomUtility.toExternalValue(box.getY()); final double w = StrictGeomUtility.toExternalValue(box.getWidth()); final double h = StrictGeomUtility.toExternalValue(box.getHeight()); boxArea.setFrame(x, y, w, h); g2.draw(boxArea); }
From source file:com.juanhg.pot.PotApplet.java
void updateOutputs() { double Wo = model.getWo(); double Wf = model.getWf(); double Qo = model.getQo(); double Qf = model.getQf(); double To = model.getTo(); double Tf = model.getTf(); double Uo = model.getUo(); double Uf = model.getUf(); double Po = model.getPo(); double Pf = model.getPf(); double Vo = model.getVo(); double Vf = model.getVf(); double aux;// w w w.jav a2 s. c o m if (Wo > Wf) { aux = Wo; Wo = Wf; Wf = aux; } if (Qo > Qf) { aux = Qo; Qo = Qf; Qf = aux; } if (To > Tf) { aux = To; To = Tf; Tf = aux; } if (Uo > Uf) { aux = Uo; Uo = Uf; Uf = aux; } if (Po > Pf) { aux = Po; Po = Pf; Pf = aux; } if (Vo > Vf) { aux = Vo; Vo = Vf; Vf = aux; } double Wn = normalize(model.getW(), Wo, Wf, 0, 10); double Qn = normalize(model.getQ(), Qo, Qf, 0, 10); double Tn = normalize(model.getT(), To, Tf, 0, 10); double Un = normalize(model.getU(), Uo, Uf, 0, 10); double Pn = normalize(model.getP(), Po, Pf, 0, 10); double Vn = normalize(model.getV(), Vo, Vf, 0, 10); Stroke stroke = new BasicStroke(1f); chartChart.deleteAnnotation(WAnnotation); WAnnotation = chartChart.drawBox(0.5, 0, 1.5, Wn, stroke, Color.BLACK, Color.RED); chartChart.deleteAnnotation(QAnnotation); QAnnotation = chartChart.drawBox(2.5, 0, 3.5, Qn, stroke, Color.BLACK, Color.ORANGE); chartChart.deleteAnnotation(TAnnotation); TAnnotation = chartChart.drawBox(4.5, 0, 5.5, Tn, stroke, Color.BLACK, Color.YELLOW); chartChart.deleteAnnotation(UAnnotation); UAnnotation = chartChart.drawBox(6.5, 0, 7.5, Un, stroke, Color.BLACK, Color.GREEN); chartChart.deleteAnnotation(PAnnotation); PAnnotation = chartChart.drawBox(8.5, 0, 9.5, Pn, stroke, Color.BLACK, Color.BLUE); chartChart.deleteAnnotation(VAnnotation); VAnnotation = chartChart.drawBox(10.5, 0, 11.5, Vn, stroke, Color.BLACK, Color.MAGENTA); }
From source file:cn.InstFS.wkr.NetworkMining.UIs.TimeSeriesChart1.java
public static Color getcolor(int i) { switch (i) {/*from ww w . j a va2 s. c o m*/ case 1: return Color.red; case 2: return Color.blue; case 3: return Color.cyan; case 4: return Color.gray; case 5: return Color.green; case 6: return Color.magenta; case 7: return Color.orange; case 8: return Color.yellow; case 9: return Color.white; case 0: return Color.pink; default: return Color.black; } }
From source file:mil.tatrc.physiology.utilities.csv.plots.ActionEventPlotter.java
public void createGraph(PlotJob job, List<List<Double>> timeData, List<List<Double>> data, List<LogEvent> events, List<SEAction> actions) { CSVPlotTool plotTool = new CSVPlotTool(); //to leverage existing functions String title = job.name + "_"; XYSeriesCollection dataSet = new XYSeriesCollection(); double maxY = 0; double minY = Double.MAX_VALUE; for (int i = 0; i < timeData.size(); i++) { if (timeData.get(i) == null || data.get(i) == null) { job.bgColor = Color.white; //This hits when we have Expected data but NOT computed data continue; }/* w w w. j ava2 s . c om*/ title = title + job.headers.get(i) + "_"; XYSeries dataSeries; if (job.isComparePlot) { if (timeData.size() > 1) dataSeries = plotTool.createXYSeries(i == 0 ? "Expected" : "Computed", timeData.get(i), data.get(i)); else //If we're comparing but only have one data list, expected is missing, so rename to computed { dataSeries = plotTool.createXYSeries("Computed", timeData.get(i), data.get(i)); } } else dataSeries = plotTool.createXYSeries(job.headers.get(i), timeData.get(i), data.get(i)); dataSet.addSeries(dataSeries); maxY = maxY < dataSeries.getMaxY() ? dataSeries.getMaxY() : maxY; minY = minY > dataSeries.getMinY() ? dataSeries.getMinY() : minY; } title = title + "vs_Time_Action_Event_Plot"; //Override the constructed title if desired (usually for compare plots) if (job.titleOverride != null && !job.titleOverride.isEmpty() && !job.titleOverride.equalsIgnoreCase("None")) title = job.titleOverride; double rangeLength = maxY - minY; if (Math.abs(rangeLength) < 1e-6) { rangeLength = .01; } class AEEntry implements Comparable<AEEntry> { public String name; public List<Double> times = new ArrayList<Double>(); public List<Double> YVals = new ArrayList<Double>(); public String type = ""; public int compareTo(AEEntry entry) { return times.get(0) < entry.times.get(0) ? -1 : times.get(0) > entry.times.get(0) ? 1 : 0; } } List<AEEntry> allActionsAndEvents = new ArrayList<AEEntry>(); if (!job.skipAllEvents) { //Make points for each event //Treat each event like two points on the same vertical line for (LogEvent event : events) { boolean skip = false; for (String eventToSkip : job.eventOmissions) { if (event.text.contains(eventToSkip)) skip = true; } if (skip) continue; AEEntry entry = new AEEntry(); entry.times.add(event.time.getValue()); if (job.logAxis) entry.YVals.add(maxY); else if (job.forceZeroYAxisBound && maxY < 0) entry.YVals.add(-.01); else entry.YVals.add(maxY + 0.15 * rangeLength); entry.times.add(event.time.getValue()); if (job.logAxis) entry.YVals.add(minY); else if (job.forceZeroYAxisBound && minY > 0) entry.YVals.add(-.01); else entry.YVals.add(minY - 0.15 * rangeLength); entry.name = event.text + "\r\nt=" + event.time.getValue(); entry.type = "EVENT:"; allActionsAndEvents.add(entry); } } if (!job.skipAllActions) { //Make similar entries for actions for (SEAction action : actions) { boolean skip = false; for (String actionToSkip : job.actionOmissions) { if (action.toString().contains(actionToSkip)) skip = true; } if (skip) continue; if (action.toString().contains("Advance Time")) continue; AEEntry entry = new AEEntry(); entry.times.add(action.getScenarioTime().getValue()); if (job.logAxis) entry.YVals.add(maxY); else if (job.forceZeroYAxisBound && maxY < 0) entry.YVals.add(-.01); else entry.YVals.add(maxY + 0.15 * rangeLength); entry.times.add(action.getScenarioTime().getValue()); if (job.logAxis) entry.YVals.add(minY); else if (job.forceZeroYAxisBound && minY > 0) entry.YVals.add(-.01); else entry.YVals.add(minY - 0.15 * rangeLength); entry.name = action.toString() + "\r\nt=" + action.getScenarioTime().getValue(); entry.type = "ACTION:"; allActionsAndEvents.add(entry); } } //Sort the list Collections.sort(allActionsAndEvents); //Add a series for each entry for (AEEntry entry : allActionsAndEvents) { dataSet.addSeries(plotTool.createXYSeries(entry.type + entry.name, entry.times, entry.YVals)); } //If we have experimental data, try to load it and create a dataset for it XYSeriesCollection expDataSet = new XYSeriesCollection(); if (job.experimentalData != null && !job.experimentalData.isEmpty()) { Map<String, List<Double>> expData = new HashMap<String, List<Double>>(); List<String> expHeaders = new ArrayList<String>(); try { CSVContents csv = new CSVContents(job.experimentalData); csv.abbreviateContents = 0; csv.readAll(expData); expHeaders = csv.getHeaders(); } catch (Exception e) { Log.error("Unable to read experimental data"); } if (!expData.isEmpty() && !expHeaders.isEmpty()) { List<Double> expTimeData = new ArrayList<Double>(); expTimeData = expData.get("Time(s)"); for (String h : expHeaders) //Will assume all headers from exp file will be on same Y axis vs time { if (h.equalsIgnoreCase("Time(s)")) continue; expDataSet.addSeries(plotTool.createXYSeries("Experimental " + h, expTimeData, expData.get(h))); } } } //set labels String XAxisLabel = "Time(s)"; String YAxisLabel = job.headers.get(0); JFreeChart chart = ChartFactory.createXYLineChart( job.titleOverride != null && job.titleOverride.equalsIgnoreCase("None") ? "" : title, // chart title XAxisLabel, // x axis label YAxisLabel, // y axis label dataSet, // data PlotOrientation.VERTICAL, // orientation true, // include legend true, // tooltips false // urls ); Log.info("Creating Graph " + title); XYPlot plot = (XYPlot) chart.getPlot(); if (!job.logAxis) { // Determine Y range double resMax0 = maxY; double resMin0 = minY; if (Double.isNaN(resMax0) || Double.isNaN(resMin0)) plot.getDomainAxis().setLabel("Range is NaN"); if (DoubleUtils.isZero(resMin0)) resMin0 = -0.000001; if (DoubleUtils.isZero(resMax0)) resMax0 = 0.000001; if (job.forceZeroYAxisBound && resMin0 >= 0) resMin0 = -.000001; if (job.forceZeroYAxisBound && resMax0 <= 0) resMax0 = .000001; rangeLength = resMax0 - resMin0; ValueAxis yAxis = plot.getRangeAxis(); if (rangeLength != 0) yAxis.setRange(resMin0 - 0.15 * rangeLength, resMax0 + 0.15 * rangeLength);//15% buffer so we can see top and bottom clearly //Add another Y axis to the right side for easier reading ValueAxis rightYAxis = new NumberAxis(); rightYAxis.setRange(yAxis.getRange()); rightYAxis.setLabel(""); //Override the bounds if desired try { if (job.Y1LowerBound != null) { yAxis.setLowerBound(job.Y1LowerBound); rightYAxis.setLowerBound(job.Y1LowerBound); } if (job.Y1UpperBound != null) { yAxis.setUpperBound(job.Y1UpperBound); rightYAxis.setUpperBound(job.Y1UpperBound); } } catch (Exception e) { Log.error( "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist."); } plot.setRangeAxis(0, yAxis); plot.setRangeAxis(1, rightYAxis); } else { double resMin = minY; double resMax = maxY; if (resMin <= 0.0) resMin = .00001; LogarithmicAxis yAxis = new LogarithmicAxis("Log(" + YAxisLabel + ")"); LogarithmicAxis rightYAxis = new LogarithmicAxis(""); yAxis.setLowerBound(resMin); rightYAxis.setLowerBound(resMin); yAxis.setUpperBound(resMax); rightYAxis.setUpperBound(resMax); //Override the bounds if desired try { if (job.Y1LowerBound != null) { yAxis.setLowerBound(job.Y1LowerBound); rightYAxis.setLowerBound(job.Y1LowerBound); } if (job.Y1UpperBound != null) { yAxis.setUpperBound(job.Y1UpperBound); rightYAxis.setUpperBound(job.Y1UpperBound); } } catch (Exception e) { Log.error( "Couldn't set Y bounds. You probably tried to set a bound on an axis that doesn't exist."); } plot.setRangeAxis(0, yAxis); plot.setRangeAxis(1, rightYAxis); } //Override X bounds if desired try { if (job.X1LowerBound != null) plot.getDomainAxis(0).setLowerBound(job.X1LowerBound); if (job.X1UpperBound != null) plot.getDomainAxis(0).setUpperBound(job.X1UpperBound); } catch (Exception e) { Log.error("Couldn't set X bounds. You probably tried to set a bound on an axis that doesn't exist."); } //Override labels if desired if (job.X1Label != null && !plot.getDomainAxis(0).getLabel().contains("NaN")) plot.getDomainAxis(0).setLabel(job.X1Label.equalsIgnoreCase("None") ? "" : job.X1Label); if (job.Y1Label != null) plot.getRangeAxis(0).setLabel(job.Y1Label.equalsIgnoreCase("None") ? "" : job.Y1Label); //If we have experimental data, set up the renderer for it and add to plot if (expDataSet.getSeriesCount() != 0) { XYItemRenderer renderer1 = new XYLineAndShapeRenderer(false, true); // Shapes only renderer1.setSeriesShape(0, ShapeUtilities.createDiamond(8)); plot.setDataset(1, expDataSet); plot.setRenderer(1, renderer1); plot.mapDatasetToDomainAxis(1, 0); plot.mapDatasetToRangeAxis(1, 0); } formatAEPlot(job, chart); plot.setDomainGridlinesVisible(job.showGridLines); plot.setRangeGridlinesVisible(job.showGridLines); //Changing line widths and colors XYItemRenderer r = plot.getRenderer(); BasicStroke wideLine = new BasicStroke(2.0f); Color[] AEcolors = { Color.red, Color.green, Color.black, Color.magenta, Color.orange }; Color[] dataColors = { Color.blue, Color.cyan, Color.gray, Color.black, Color.red }; for (int i = 0, cIndex = 0; i < dataSet.getSeriesCount(); i++, cIndex++) { r.setSeriesStroke(i, wideLine); XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); renderer.setBaseShapesVisible(false); if (cIndex > 4) cIndex = 0; if (i < job.headers.size()) //Our actual data { renderer.setSeriesFillPaint(i, dataColors[cIndex]); renderer.setSeriesPaint(i, dataColors[cIndex]); } else //actions and events in procession of other colors { renderer.setSeriesFillPaint(i, AEcolors[cIndex]); renderer.setSeriesPaint(i, AEcolors[cIndex]); } } //Special color and format changes for compare plots if (job.isComparePlot) { XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) plot.getRenderer(); for (int i = 0; i < dataSet.getSeriesCount(); i++) { if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Expected")) { renderer.setSeriesStroke(//makes a dashed line i, //argument below float[]{I,K} -> alternates between solid and opaque (solid for I, opaque for K) new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1.0f, new float[] { 15.0f, 30.0f }, 0.0f)); renderer.setDrawSeriesLineAsPath(true); renderer.setUseFillPaint(true); renderer.setBaseShapesVisible(false); renderer.setSeriesFillPaint(i, Color.black); renderer.setSeriesPaint(i, Color.black); } if (dataSet.getSeries(i).getKey().toString().equalsIgnoreCase("Computed")) { renderer.setSeriesFillPaint(i, Color.red); renderer.setSeriesPaint(i, Color.red); } if (dataSet.getSeries(i).getKey().toString().startsWith("ACTION")) { renderer.setSeriesFillPaint(i, Color.green); renderer.setSeriesPaint(i, Color.green); } if (dataSet.getSeries(i).getKey().toString().startsWith("EVENT")) { renderer.setSeriesFillPaint(i, Color.blue); renderer.setSeriesPaint(i, Color.blue); } } } //Split the auto-generated legend into two legends, one for data and one for actions and events LegendItemCollection originalLegendCollection = plot.getLegendItems(); final LegendItemCollection dataLegendCollection = new LegendItemCollection(); int i; for (i = 0; i < job.headers.size() && i < originalLegendCollection.getItemCount(); i++) { if (originalLegendCollection.get(i).getLabel().startsWith("ACTION") || originalLegendCollection.get(i).getLabel().startsWith("EVENT")) break; dataLegendCollection.add(originalLegendCollection.get(i)); } final LegendItemCollection remainingLegendCollection = new LegendItemCollection(); for (; i < originalLegendCollection.getItemCount(); i++) { remainingLegendCollection.add(originalLegendCollection.get(i)); } chart.removeLegend(); LegendItemSource source = new LegendItemSource() { LegendItemCollection lic = new LegendItemCollection(); { lic.addAll(dataLegendCollection); } public LegendItemCollection getLegendItems() { return lic; } }; LegendTitle dataLegend = new LegendTitle(source); dataLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0)); dataLegend.setBorder(2, 2, 2, 2); dataLegend.setBackgroundPaint(Color.white); dataLegend.setPosition(RectangleEdge.TOP); dataLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22)); chart.addLegend(dataLegend); source = new LegendItemSource() { LegendItemCollection lic = new LegendItemCollection(); { lic.addAll(remainingLegendCollection); } public LegendItemCollection getLegendItems() { return lic; } }; LegendTitle actionEventsLegend = new LegendTitle(source); actionEventsLegend.setMargin(new RectangleInsets(1.0, 1.0, 1.0, 1.0)); actionEventsLegend.setBorder(2, 2, 2, 2); actionEventsLegend.setBackgroundPaint(Color.white); actionEventsLegend.setPosition(RectangleEdge.BOTTOM); actionEventsLegend.setItemFont(new Font("SansSerif", Font.PLAIN, 22)); if (!job.hideAELegend && !job.removeAllLegends) chart.addLegend(actionEventsLegend); if (job.removeAllLegends) chart.removeLegend(); int verticalPixels = 800 + 170 * (allActionsAndEvents.size() / 5); //This is a little hacky, but if we want only the legend, just extend Plot() and remove the draw functionality so it makes a blank plot class legendPlot extends Plot { public void draw(Graphics2D arg0, Rectangle2D arg1, Point2D arg2, PlotState arg3, PlotRenderingInfo arg4) { } public String getPlotType() { return null; } } //Then add the legend to that and throw away the original plot if (job.legendOnly) { chart = new JFreeChart("", null, new legendPlot(), false); chart.addLegend(actionEventsLegend); } try { FileUtils.createDirectory(job.outputDir); String filename = job.outputFilename == null ? job.outputDir + "/" + plotTool.MakeFileName(title) + ".jpg" : job.outputDir + "/" + job.outputFilename; if (!filename.endsWith(".jpg")) filename = filename + ".jpg"; File JPGFile = new File(filename); if (job.imageHeight != null && job.imageWidth != null) ChartUtilities.saveChartAsJPEG(JPGFile, chart, job.imageWidth, job.imageHeight); else if (!job.hideAELegend && !job.removeAllLegends) ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, verticalPixels); else ChartUtilities.saveChartAsJPEG(JPGFile, chart, 1600, 800); } catch (IOException e) { Log.error(e.getMessage()); } }
From source file:edu.ucla.stat.SOCR.applications.demo.BinomialTradingApplication.java
void updateGraph() { //This method will later update/redraw/repaint the (Node, Edge)-Graph // For now, we just print out the results in JTextArea // Price of the Stock Price[k][l] is the price of the stock at level k (0<=k<=n) // and outcome l (0<=l<n+1) GraphModel model = new DefaultGraphModel(); jgraph = new JGraph(model); cells = new DefaultGraphCell[((n + 1) * (n + 2) / 2) * 3]; cellCount = 0;/* w ww .j av a2 s . co m*/ int XSpace = 130; int YSpace = 30; int YMiddle = 20 + n * YSpace; //150 for (int k = 0; k <= n; k++) { //System.out.println("============Start-of-level("+k+")=================="); for (int l = 0; l <= k; l++) { // Print to GraphPanel's JTextArea int j = -k + l * 2; if (choice.charAt(9) == 'P') { //For put option if (k == n) { // For the last column, k=n, (in the money), // we need to color GREEN or BLUE the node-background // to indicate if the Call Price (C) is > 0 (green) or // <= 0 (blue) if (j < 0) { if (Diff[k][l] > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20), Color.green); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20), Color.blue); } else if (j > 0) { if (Diff[k][l] > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20), Color.green); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20), Color.blue); } else { if (Diff[k][l] > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle, Color.green); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle, Color.blue); } } else { // For all columns before the last (in the money) column, k<n)! if (j < 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20)); else if (j > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20)); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " P[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle); } } else { //For call option if (k == n) { // For the last column, k=n, (in the money), // we need to color GREEN or BLUE the node-background // to indicate if the Call Price (C) is > 0 (green) or // <= 0 (blue) if (j < 0) { if (Diff[k][l] > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20), Color.green); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20), Color.blue); } else if (j > 0) { if (Diff[k][l] > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20), Color.green); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20), Color.blue); } else { if (Diff[k][l] > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle, Color.green); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle, Color.blue); } } else if (choice.charAt(0) == 'A' && Diff[k][l] == Math.abs(Price[k][l] - EP)) { // For all columns before the last (in the money) column, k<n)! and possibly exercised early if (j < 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20), Color.magenta); else if (j > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20), Color.magenta); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle, Color.magenta); } else { // For all columns before the last (in the money) column, k<n)! if (j < 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace - 20)); else if (j > 0) addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), (YMiddle + j * YSpace + 20)); else addNode("S[" + k + "," + l + "]=" + formatter.format(Price[k][l]) + " C[" + k + "," + l + "]=" + formatter.format(Diff[k][l]), (10 + k * XSpace), YMiddle); // Also Print to STD_OUT // System.out.println("j="+j); // System.out.println("Price["+k+"]["+l+"]="+Price[k][l]); // System.out.println("Diff["+k+"]["+l+"]="+Diff[k][l]); } } } //System.out.println("============End-of-level("+k+")==================\n"); } //System.out.println("cellCount="+cellCount); for (int k = 0; k < n; k++) { //System.out.println("============Start-of-level("+k+")=================="); for (int l = 0; l <= k; l++) { // System.out.println((k*(k+1)/2+l)+"->"+((k+1)*(k+2)/2+l) ); addEdge((k * (k + 1) / 2 + l), ((k + 1) * (k + 2) / 2 + l)); //System.out.println((k*(k+1)/2+l)+"->"+((k+1)*(k+2)/2+l+1) ); addEdge((k * (k + 1) / 2 + l), ((k + 1) * (k + 2) / 2 + l + 1)); } // System.out.println("============End-of-level("+k+")==================\n"); } // System.out.println("cellCount="+cellCount); DefaultGraphCell[] cellsCache = new DefaultGraphCell[cellCount]; for (int i = 0; i < cellCount; i++) cellsCache[i] = cells[i]; jgraph.getGraphLayoutCache().insert(cellsCache); Dimension d = jgraph.getPreferredSize(); //System.out.println(d.width +","+d.height); jgraph.setPreferredSize(new Dimension(d.width + 150, d.height)); jgraphPanel.removeAll(); JScrollPane jsp = new JScrollPane(jgraph); jgraphPanel.add(jsp); jgraphPanel.setPreferredSize(new Dimension(CHART_SIZE_X, CHART_SIZE_Y)); JViewport jv = jsp.getViewport(); jv.setViewPosition(new Point(0, YMiddle - 150)); jgraphPanel.validate(); }
From source file:com.voterData.graph.Graph.java
public static JFreeChart getRaceDistbn2008(Map<String, Double> dataMap) { DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset(); for (String key : dataMap.keySet()) { if (key.equals("A_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Asian", "REP"); } else if (key.equals("B_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "African American/Black", "REP"); } else if (key.equals("I_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "American Indian/Alaska Native", "REP"); } else if (key.equals("O_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Other", "REP"); } else if (key.equals("M_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Multiracial", "REP"); } else if (key.equals("U_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Undefined", "REP"); } else if (key.equals("W_Rep_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "White", "REP"); } else if (key.equals("A_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Asian", "DEM"); } else if (key.equals("B_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "African American/Black", "DEM"); } else if (key.equals("I_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "American Indian/Alaska Native", "DEM"); } else if (key.equals("O_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Other", "DEM"); } else if (key.equals("M_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Multiracial", "DEM"); } else if (key.equals("U_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Undefined", "DEM"); } else if (key.equals("W_Dem_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "White", "DEM"); } else if (key.equals("A_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Asian", "UNA"); } else if (key.equals("B_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "African American/Black", "UNA"); } else if (key.equals("I_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "American Indian/Alaska Native", "UNA"); } else if (key.equals("O_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Other", "UNA"); } else if (key.equals("M_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Multiracial", "UNA"); } else if (key.equals("U_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "Undefined", "UNA"); } else if (key.equals("W_Una_2008")) { defaultcategorydataset.addValue(dataMap.get(key), "White", "UNA"); }/* w w w . j a v a 2 s . c o m*/ } JFreeChart jfreechart = ChartFactory.createBarChart("Race Distribution - 2008", "Party", "% of votes", defaultcategorydataset, PlotOrientation.VERTICAL, true, true, false); jfreechart.setBackgroundPaint(Color.white); CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot(); categoryplot.setBackgroundPaint(Color.lightGray); categoryplot.setRangeGridlinePaint(Color.white); BarRenderer renderer = (BarRenderer) categoryplot.getRenderer(); renderer.setDrawBarOutline(false); renderer.setSeriesPaint(0, Color.ORANGE); renderer.setSeriesPaint(1, Color.MAGENTA); renderer.setSeriesPaint(2, Color.PINK); renderer.setSeriesPaint(3, Color.YELLOW); renderer.setSeriesPaint(4, Color.cyan); renderer.setSeriesPaint(5, Color.RED); renderer.setSeriesPaint(6, Color.green); renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator()); renderer.setSeriesItemLabelGenerator(0, new StandardCategoryItemLabelGenerator()); renderer.setItemLabelsVisible(true); categoryplot.setRenderer(renderer); return jfreechart; }
From source file:gdsc.smlm.ij.plugins.pcpalm.PCPALMFitting.java
/** * Perform the PC Analysis/* w ww.j a v a 2 s .co m*/ * <p> * Spatial domain results can just be combined to an average curve. * <p> * Frequency domain results can be fit using the g(r) model. */ private void analyse() { previous_gr = gr; previous_peakDensity = peakDensity; previous_spatialDomain = spatialDomain; String axisTitle; if (spatialDomain) { offset = 0; axisTitle = "molecules/um^2"; } else { // Ignore the r=0 value by starting with an offset if necessary offset = (gr[0][0] == 0) ? 1 : 0; axisTitle = "g(r)"; } String title = TITLE + " " + axisTitle; Plot plot = PCPALMAnalysis.plotCorrelation(gr, offset, title, axisTitle, spatialDomain, showErrorBars); if (spatialDomain) { saveCorrelationCurve(gr); log("Created correlation curve from the spatial domain (Plot title = " + title + ")"); return; } // ------------- // Model fitting for g(r) correlation curves // ------------- log("Fitting g(r) correlation curve from the frequency domain"); log("Average peak density = %s um^-2. Blinking estimate = %s", Utils.rounded(peakDensity, 4), Utils.rounded(blinkingRate, 4)); createResultsTable(); // Get the protein density in nm^2. peakDensity /= 1e6; // Use the blinking rate estimate to estimate the density // (factors in the over-counting of the same molecules) double proteinDensity = peakDensity / blinkingRate; ArrayList<double[]> curves = new ArrayList<double[]>(); // Fit the g(r) curve for r>0 to equation 2 Color color = Color.red; String resultColour = "Red"; double[] parameters = fitRandomModel(gr, estimatedPrecision, proteinDensity, resultColour); if (parameters != null) { log(" Plot %s: Over-counting estimate = %s", randomModel.getName(), Utils.rounded(peakDensity / parameters[1], 4)); log(" Plot %s == %s", randomModel.getName(), resultColour.toString()); plot.setColor(color); plot.addPoints(randomModel.getX(), randomModel.value(parameters), Plot.LINE); addNonFittedPoints(plot, gr, randomModel, parameters); Utils.display(title, plot); if (saveCorrelationCurve) curves.add(extractCurve(gr, randomModel, parameters)); } // Fit the clustered models if the random model fails or if chosen as an option if (!valid1 || fitClusteredModels) { // Fit the g(r) curve for r>0 to equation 3 color = Color.blue; resultColour = "Blue"; parameters = fitClusteredModel(gr, estimatedPrecision, proteinDensity, resultColour); if (parameters != null) { log(" Plot %s: Over-counting estimate = %s", clusteredModel.getName(), Utils.rounded(peakDensity / parameters[1], 4)); log(" Plot %s == %s, ", clusteredModel.getName(), resultColour.toString()); plot.setColor(color); plot.addPoints(clusteredModel.getX(), clusteredModel.value(parameters), Plot.LINE); addNonFittedPoints(plot, gr, clusteredModel, parameters); Utils.display(title, plot); if (saveCorrelationCurve) curves.add(extractCurve(gr, clusteredModel, parameters)); } // Fit to an emulsion model for a distribution confined to circles color = Color.magenta; resultColour = "Magenta"; parameters = fitEmulsionModel(gr, estimatedPrecision, proteinDensity, resultColour); if (parameters != null) { log(" Plot %s: Over-counting estimate = %s", emulsionModel.getName(), Utils.rounded(peakDensity / parameters[1], 4)); log(" Plot %s == %s", emulsionModel.getName(), resultColour.toString()); plot.setColor(color); plot.addPoints(emulsionModel.getX(), emulsionModel.value(parameters), Plot.LINE); addNonFittedPoints(plot, gr, emulsionModel, parameters); Utils.display(title, plot); if (saveCorrelationCurve) curves.add(extractCurve(gr, emulsionModel, parameters)); } } saveCorrelationCurve(gr, curves.toArray(new double[0][0])); }
From source file:tufts.vue.ds.DataAction.java
private static LWLink makeLink(final LWComponent src, final LWComponent dest, final Relation r) { if (DEBUG.Enabled) Log.debug("makeLink: " + r); final Color color; final LWLink link = makeLink(src, dest, null, r.getDescription(), null); if (link == null) { Log.error("link=null " + r); return null; }/*from www . ja va2s.c o m*/ if (r.isCrossSchema()) { link.mStrokeStyle.setTo(LWComponent.StrokeStyle.DASH3); link.setStrokeWidth(2); } // todo: count style priority over join style if (r.type == Relation.AUTOMATIC) { color = Color.lightGray; } else if (r.type == Relation.USER) { color = Color.black; } else if (r.type == Relation.COUNT) { //if (true) return null; color = Color.lightGray; if (r.count == 1) link.setStrokeWidth(0.3f); else link.setStrokeWidth((float) Math.log(r.count)); link.setTextColor(color); link.setLabel(String.format(" %d ", r.getCount())); } else if (r.type == Relation.JOIN) { color = Color.orange; } else color = Color.magenta; // unknown type! link.setStrokeColor(color); // if (r.type == Relation.JOIN) // else if (r.type == Relation.COUNT) return link; }
From source file:org.gumtree.vis.awt.JChartPanel.java
private void drawTextInputBox(Graphics2D g2) { if (textInputFlag && textInputPoint != null) { // g2.drawChars("Input Text Here".toCharArray(), 1, 60, (int) textInputPoint.getX(), (int) textInputPoint.getY()); Color oldColor = g2.getColor(); g2.setColor(Color.BLACK); String inputText = textInputContent == null ? "" : textInputContent; FontMetrics fm = g2.getFontMetrics(); // int sWidth; // if (textInputCursorIndex == 0 || inputText.length() == 0) { // sWidth = 0; // } else if (textInputCursorIndex < inputText.length()){ // sWidth = fm.stringWidth(inputText.substring(0, textInputCursorIndex)); // } else { // sWidth = fm.stringWidth(inputText); // } String[] lines = inputText.split("\n", 100); int cursorY = 0; int cursorX = 0; int charCount = 0; int maxWidth = 0; int maxHeight = 0; for (int i = 0; i < lines.length; i++) { g2.drawString(lines[i], (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3 + i * 15); // charCount += lines[i].length() + 1; if (textInputCursorIndex > charCount && textInputCursorIndex < charCount + lines[i].length() + 1) { cursorY = i;// w ww . j a v a2 s.c om cursorX = fm.stringWidth(lines[i].substring(0, textInputCursorIndex - charCount)); } else if (textInputCursorIndex == charCount + lines[i].length() + 1) { cursorY = i + 1; cursorX = 0; } charCount += lines[i].length() + 1; int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } maxHeight = 15 * lines.length; // g2.drawString(inputText, (int) textInputPoint.getX() + 3, (int) textInputPoint.getY() - 3); g2.setColor(Color.MAGENTA); // g2.drawString("|", (float) textInputPoint.getX() + 2 + sWidth, (float) textInputPoint.getY() - 3); g2.drawLine((int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + (cursorY - 1) * 15, (int) textInputPoint.getX() + 3 + cursorX, (int) textInputPoint.getY() + cursorY * 15); g2.setColor(Color.BLACK); g2.setColor(oldColor); // int boxWidth = fm.stringWidth(inputText) + 10; if (maxWidth < 100) { maxWidth = 100; } Rectangle2D inputBox = new Rectangle2D.Double(textInputPoint.getX(), textInputPoint.getY() - 15, maxWidth + 8, maxHeight); // ChartMaskingUtilities.drawMaskBoarder(g2, inputBox); Color fillColor = new Color(250, 250, 50, 30); g2.setPaint(fillColor); g2.fill(inputBox); g2.setColor(Color.ORANGE); g2.drawRect((int) textInputPoint.getX(), (int) textInputPoint.getY() - 15, maxWidth + 8, maxHeight); } if (textContentMap.size() > 0) { Color oldColor = g2.getColor(); g2.setColor(Color.BLACK); Rectangle2D imageArea = getScreenDataArea(); for (Entry<Rectangle2D, String> entry : textContentMap.entrySet()) { Rectangle2D rect = entry.getKey(); Point2D screenPoint = ChartMaskingUtilities .translateChartPoint(new Point2D.Double(rect.getX(), rect.getY()), imageArea, getChart()); String text = entry.getValue(); if (text == null) { continue; } String[] lines = text.split("\n"); g2.setColor(Color.BLACK); for (int i = 0; i < lines.length; i++) { g2.drawString(lines[i], (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3 + i * 15); } if (rect == selectedTextWrapper) { FontMetrics fm = g2.getFontMetrics(); int maxWidth = 0; int maxHeight = 0; for (int i = 0; i < lines.length; i++) { int lineWidth = fm.stringWidth(lines[i]); if (lineWidth > maxWidth) { maxWidth = lineWidth; } } maxHeight = 15 * lines.length; if (maxWidth < 100) { maxWidth = 100; } Rectangle2D inputBox = new Rectangle2D.Double(screenPoint.getX(), screenPoint.getY() - 15, maxWidth + 8, maxHeight); Color fillColor = new Color(250, 250, 50, 30); g2.setPaint(fillColor); g2.fill(inputBox); g2.setColor(Color.ORANGE); g2.drawRect((int) screenPoint.getX(), (int) screenPoint.getY() - 15, maxWidth + 8, maxHeight); } // g2.drawString(text == null ? "" : text, (int) screenPoint.getX() + 3, (int) screenPoint.getY() - 3); } g2.setColor(oldColor); } }