Example usage for java.awt Font PLAIN

List of usage examples for java.awt Font PLAIN

Introduction

In this page you can find the example usage for java.awt Font PLAIN.

Prototype

int PLAIN

To view the source code for java.awt Font PLAIN.

Click Source Link

Document

The plain style constant.

Usage

From source file:asl.util.PlotMaker2.java

public void writePlot(String fileName) {
    //System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle, fileName);

    File outputFile = new File(fileName);

    // Check that we will be able to output the file without problems and if not --> return
    if (!checkFileOut(outputFile)) {
        System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it "
                + " --> skip plot\n", fileName);
        return;/*from   w w w .  jav  a  2s .co m*/
    }

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x = domain

    if (fileName.contains("nlnm") || fileName.contains("coher") || fileName.contains("stn")) { // NLNM or StationDeviation 
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y = range

        if (fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM or StationDeviation 
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -95));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer();
        XYPlot xyplot = new XYPlot((XYDataset) seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());
            renderer.setSeriesLinesVisible(iTrace, true);
            renderer.setSeriesShapesVisible(iTrace, false);

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop so that
        //                      the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner = (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g., "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")) {
                // x1 > x2 > x3, e.g.:
                //  o-------o   00-LHZ
                //  x3     x2       x1

                double scale = .01; // Controls distance between trace label and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400);
    } catch (IOException e) {
        System.err.println("Problem occurred creating chart.");

    }

}

From source file:be.ac.ua.comp.scarletnebula.gui.ServerCellRenderer.java

private JLabel getTagComponent(final Server server, final Color foreground) {
    final JLabel tags = new JLabel();

    final Font tagFont = new Font(tags.getFont().getName(), Font.PLAIN, 11);
    tags.setFont(tagFont);/* www  .  j av a2 s.  co m*/
    tags.setText(Utils.implode(new ArrayList<String>(server.getTags()), ", "));
    tags.setForeground(foreground);
    return tags;
}

From source file:MenuDemo.java

protected void updateMonitor() {
    int index = -1;
    for (int k = 0; k < menus.length; k++) {
        if (menus[k].isSelected()) {
            index = k;/*from   www  .j a  v  a  2  s  . c om*/
            break;
        }
    }
    if (index == -1)
        return;

    if (index == 2) // Courier
    {
        boldMenuItem.setSelected(false);
        boldMenuItem.setEnabled(false);
        italicMenuItem.setSelected(false);
        italicMenuItem.setEnabled(false);
    } else {
        boldMenuItem.setEnabled(true);
        italicMenuItem.setEnabled(true);
    }

    int style = Font.PLAIN;
    if (boldMenuItem.isSelected())
        style |= Font.BOLD;
    if (italicMenuItem.isSelected())
        style |= Font.ITALIC;
}

From source file:charts.PieChart3D.java

/**
 * Creates a chart.//from   w w w .j av a 2 s  .co m
 *
 * @param dataset
 *            the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset, PieChartModel model) {

    JFreeChart chart = ChartFactory.createPieChart(model.getTitle(), // chart
            // title
            dataset, // data
            false, // no legend
            true, // tooltips
            false // no URL generation
    );

    // set a custom background for the chart
    chart.setBackgroundPaint(
            new GradientPaint(new Point(0, 0), new Color(20, 20, 20), new Point(400, 200), Color.DARK_GRAY));

    // customise the title position and font
    TextTitle t = chart.getTitle();
    t.setHorizontalAlignment(HorizontalAlignment.LEFT);
    t.setPaint(new Color(240, 240, 240));
    t.setFont(new Font("Arial", Font.BOLD, 26));

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(null);
    plot.setInteriorGap(0.04);
    plot.setOutlineVisible(false);

    // use gradients and white borders for the section colours
    plot.setSectionPaint("FCA", createGradientPaint(new Color(200, 200, 255), Color.BLUE));
    plot.setSectionPaint("FCH", createGradientPaint(new Color(255, 200, 200), Color.RED));
    plot.setSectionPaint("FCS", createGradientPaint(new Color(200, 255, 200), Color.GREEN));
    plot.setSectionPaint("FCG", createGradientPaint(new Color(200, 255, 200), Color.YELLOW));
    plot.setSectionPaint("FCJ", createGradientPaint(new Color(200, 255, 200), Color.BLACK));
    plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0} {1} ({2}) "));
    plot.setBaseSectionOutlinePaint(Color.WHITE);
    plot.setSectionOutlinesVisible(true);
    plot.setBaseSectionOutlineStroke(new BasicStroke(2.0f));

    // customise the section label appearance
    plot.setLabelFont(new Font("Courier New", Font.BOLD, 20));
    plot.setLabelLinkPaint(Color.WHITE);
    plot.setLabelLinkStroke(new BasicStroke(2.0f));
    plot.setLabelOutlineStroke(null);
    plot.setLabelPaint(Color.WHITE);
    plot.setLabelBackgroundPaint(null);

    // add a subtitle giving the data source
    TextTitle source = new TextTitle(model.getSubTitle(), new Font("Courier New", Font.PLAIN, 12));
    source.setPaint(Color.WHITE);
    source.setPosition(RectangleEdge.BOTTOM);
    source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.addSubtitle(source);
    return chart;

}

From source file:RMOS.PieChart.java

/**
 * Creates a chart./*from   ww w .j a va2  s . com*/
 *
 * @param dataset  the dataset.
 *
 * @return A chart.
 */
private static JFreeChart createChart(PieDataset dataset) {

    JFreeChart chart = ChartFactory.createPieChart("Eco Systems Statistics", // chart title
            dataset, // data
            false, // no legend
            true, // tooltips
            false // no URL generation
    );

    // set a custom background for the chart
    chart.setBackgroundPaint(
            new GradientPaint(new Point(0, 0), new Color(20, 20, 20), new Point(400, 200), Color.DARK_GRAY));

    // customise the title position and font
    TextTitle t = chart.getTitle();
    t.setHorizontalAlignment(HorizontalAlignment.LEFT);
    t.setPaint(new Color(240, 240, 240));
    t.setFont(new Font("Arial", Font.BOLD, 26));

    PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(null);
    plot.setInteriorGap(0.04);
    plot.setOutlineVisible(false);

    plot.setSectionPaint(f1.getStationInGroup().get(1), Color.blue);
    plot.setSectionPaint(f1.getStationInGroup().get(1), Color.GREEN);

    // use gradients and white borders for the section colours
    /*plot.setSectionPaint("Others", createGradientPaint(new Color(200, 200, 255), Color.BLUE));
    plot.setSectionPaint("Samsung", createGradientPaint(new Color(255, 200, 200), Color.RED));
    plot.setSectionPaint("Apple", createGradientPaint(new Color(200, 255, 200), Color.GREEN));
    plot.setSectionPaint("Nokia", createGradientPaint(new Color(200, 255, 200), Color.YELLOW));*/
    plot.setBaseSectionOutlinePaint(Color.WHITE);
    plot.setSectionOutlinesVisible(true);
    plot.setBaseSectionOutlineStroke(new BasicStroke(2.0f));

    // customise the section label appearance
    plot.setLabelFont(new Font("Courier New", Font.BOLD, 20));
    plot.setLabelLinkPaint(Color.WHITE);
    plot.setLabelLinkStroke(new BasicStroke(2.0f));
    plot.setLabelOutlineStroke(null);
    plot.setLabelPaint(Color.WHITE);
    plot.setLabelBackgroundPaint(null);

    // add a subtitle giving the data source
    TextTitle source = new TextTitle("Source: Eco Recycle Station", new Font("Courier New", Font.PLAIN, 12));
    source.setPaint(Color.WHITE);
    source.setPosition(RectangleEdge.BOTTOM);
    source.setHorizontalAlignment(HorizontalAlignment.RIGHT);
    chart.addSubtitle(source);
    return chart;

}

From source file:HardcopyWriter.java

/**
 * The constructor for this class has a bunch of arguments: The frame argument
 * is required for all printing in Java. The jobname appears left justified at
 * the top of each printed page. The font size is specified in points, as
 * on-screen font sizes are. The margins are specified in inches (or fractions
 * of inches)./*from   ww w . j  a va 2 s  . c o  m*/
 */
public HardcopyWriter(Frame frame, String jobname, int fontsize, double leftmargin, double rightmargin,
        double topmargin, double bottommargin) throws HardcopyWriter.PrintCanceledException {
    // Get the PrintJob object with which we'll do all the printing.
    // The call is synchronized on the static printprops object, which
    // means that only one print dialog can be popped up at a time.
    // If the user clicks Cancel in the print dialog, throw an exception.
    Toolkit toolkit = frame.getToolkit(); // get Toolkit from Frame
    synchronized (printprops) {
        job = toolkit.getPrintJob(frame, jobname, printprops);
    }
    if (job == null)
        throw new PrintCanceledException("User cancelled print request");

    pagesize = job.getPageDimension(); // query the page size
    pagedpi = job.getPageResolution(); // query the page resolution

    // Bug Workaround:
    // On windows, getPageDimension() and getPageResolution don't work, so
    // we've got to fake them.
    if (System.getProperty("os.name").regionMatches(true, 0, "windows", 0, 7)) {
        // Use screen dpi, which is what the PrintJob tries to emulate
        pagedpi = toolkit.getScreenResolution();
        // Assume a 8.5" x 11" page size. A4 paper users must change this.
        pagesize = new Dimension((int) (8.5 * pagedpi), 11 * pagedpi);
        // We also have to adjust the fontsize. It is specified in points,
        // (1 point = 1/72 of an inch) but Windows measures it in pixels.
        fontsize = fontsize * pagedpi / 72;
    }

    // Compute coordinates of the upper-left corner of the page.
    // I.e. the coordinates of (leftmargin, topmargin). Also compute
    // the width and height inside of the margins.
    x0 = (int) (leftmargin * pagedpi);
    y0 = (int) (topmargin * pagedpi);
    width = pagesize.width - (int) ((leftmargin + rightmargin) * pagedpi);
    height = pagesize.height - (int) ((topmargin + bottommargin) * pagedpi);

    // Get body font and font size
    font = new Font("Monospaced", Font.PLAIN, fontsize);
    metrics = frame.getFontMetrics(font);
    lineheight = metrics.getHeight();
    lineascent = metrics.getAscent();
    charwidth = metrics.charWidth('0'); // Assumes a monospaced font!

    // Now compute columns and lines will fit inside the margins
    chars_per_line = width / charwidth;
    lines_per_page = height / lineheight;

    // Get header font information
    // And compute baseline of page header: 1/8" above the top margin
    headerfont = new Font("SansSerif", Font.ITALIC, fontsize);
    headermetrics = frame.getFontMetrics(headerfont);
    headery = y0 - (int) (0.125 * pagedpi) - headermetrics.getHeight() + headermetrics.getAscent();

    // Compute the date/time string to display in the page header
    DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT);
    df.setTimeZone(TimeZone.getDefault());
    time = df.format(new Date());

    this.jobname = jobname; // save name
    this.fontsize = fontsize; // save font size
}

From source file:asl.plotmaker.PlotMaker2.java

public void writePlot(String fileName) {
    // System.out.format("== plotTitle=[%s] fileName=[%s]\n", plotTitle,
    // fileName);

    File outputFile = new File(fileName);

    // Check that we will be able to output the file without problems and if
    // not --> return
    if (!checkFileOut(outputFile)) {
        // System.out.format("== plotMaker: request to output plot=[%s] but we are unable to create it "
        // + " --> skip plot\n", fileName );
        logger.warn("== Request to output plot=[{}] but we are unable to create it " + " --> skip plot\n",
                fileName);//w  ww .  j  a v  a 2 s  .  co  m
        return;
    }

    NumberAxis horizontalAxis = new NumberAxis("x-axis default"); // x =
    // domain

    if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("coher")
            || fileName.contains("stn")) { // NLNM or StationDeviation
        horizontalAxis = new LogarithmicAxis("Period (sec)");
        horizontalAxis.setRange(new Range(1, 11000));
        horizontalAxis.setTickUnit(new NumberTickUnit(5.0));
    } else { // EventCompareSynthetics/StrongMotion
        horizontalAxis = new NumberAxis("Time (s)");
        double x[] = panels.get(0).getTraces().get(0).getxData();
        horizontalAxis.setRange(new Range(x[0], x[x.length - 1]));
    }

    CombinedDomainXYPlot combinedPlot = new CombinedDomainXYPlot(horizontalAxis);
    combinedPlot.setGap(15.);

    // Loop over (3) panels for this plot:

    for (Panel panel : panels) {

        NumberAxis verticalAxis = new NumberAxis("y-axis default"); // y =
        // range

        if (fileName.contains("alnm") || fileName.contains("nlnm") || fileName.contains("stn")) { // NLNM
            // or
            // StationDeviation
            verticalAxis = new NumberAxis("PSD 10log10(m**2/s**4)/Hz dB");
            verticalAxis.setRange(new Range(-190, -80));
            verticalAxis.setTickUnit(new NumberTickUnit(5.0));
        } else if (fileName.contains("coher")) { // Coherence
            verticalAxis = new NumberAxis("Coherence, Gamma");
            verticalAxis.setRange(new Range(0, 1.2));
            verticalAxis.setTickUnit(new NumberTickUnit(0.1));
        } else { // EventCompareSynthetics/StrongMotion
            verticalAxis = new NumberAxis("Displacement (m)");
        }

        Font fontPlain = new Font("Verdana", Font.PLAIN, 14);
        Font fontBold = new Font("Verdana", Font.BOLD, 18);
        verticalAxis.setLabelFont(fontBold);
        verticalAxis.setTickLabelFont(fontPlain);
        horizontalAxis.setLabelFont(fontBold);
        horizontalAxis.setTickLabelFont(fontPlain);

        XYSeriesCollection seriesCollection = new XYSeriesCollection();
        XYDotRenderer renderer = new XYDotRenderer();
        XYPlot xyplot = new XYPlot(seriesCollection, horizontalAxis, verticalAxis, renderer);
        xyplot.setDomainGridlinesVisible(true);
        xyplot.setRangeGridlinesVisible(true);
        xyplot.setRangeGridlinePaint(Color.black);
        xyplot.setDomainGridlinePaint(Color.black);

        // Plot each trace on this panel:
        int iTrace = 0;
        for (Trace trace : panel.getTraces()) {

            XYSeries series = new XYSeries(trace.getName());

            double xdata[] = trace.getxData();
            double ydata[] = trace.getyData();
            for (int k = 0; k < xdata.length; k++) {
                series.add(xdata[k], ydata[k]);
            }

            renderer.setSeriesPaint(iTrace, trace.getColor());
            renderer.setSeriesStroke(iTrace, trace.getStroke());

            seriesCollection.addSeries(series);

            iTrace++;
        }

        // Add Annotations for each trace - This is done in a separate loop
        // so that
        // the upper/lower limits for this panel will be known
        double xmin = horizontalAxis.getRange().getLowerBound();
        double xmax = horizontalAxis.getRange().getUpperBound();
        double ymin = verticalAxis.getRange().getLowerBound();
        double ymax = verticalAxis.getRange().getUpperBound();
        double delX = Math.abs(xmax - xmin);
        double delY = Math.abs(ymax - ymin);

        // Annotation (x,y) in normalized units - where upper-right corner =
        // (1,1)
        double xAnn = 0.97; // Right center coords of the trace name (e.g.,
        // "00-LHZ")
        double yAnn = 0.95;

        double yOff = 0.05; // Vertical distance between different trace
        // legends

        iTrace = 0;
        for (Trace trace : panel.getTraces()) {
            if (!trace.getName().contains("NLNM") && !trace.getName().contains("NHNM")
                    && !trace.getName().contains("ALNM")) {
                // x1 > x2 > x3, e.g.:
                // o-------o 00-LHZ
                // x3 x2 x1

                double scale = .01; // Controls distance between trace label
                // and line segment
                double xL = .04; // Length of trace line segment in legend

                double xAnn2 = xAnn - scale * trace.getName().length();
                double xAnn3 = xAnn - scale * trace.getName().length() - xL;

                double x1 = xAnn * delX + xmin; // Right hand x-coord of
                // text in range units
                double x2 = xAnn2 * delX + xmin; // x-coord of line segment
                // end in range units
                double x3 = xAnn3 * delX + xmin; // x-coord of line segment
                // end in range units

                double y = (yAnn - (iTrace * yOff)) * delY + ymin;

                if (horizontalAxis instanceof LogarithmicAxis) {
                    double logMin = Math.log10(xmin);
                    double logMax = Math.log10(xmax);
                    delX = logMax - logMin;
                    x1 = Math.pow(10, xAnn * delX + logMin);
                    x2 = Math.pow(10, xAnn2 * delX + logMin);
                    x3 = Math.pow(10, xAnn3 * delX + logMin);
                }
                xyplot.addAnnotation(new XYLineAnnotation(x3, y, x2, y, trace.getStroke(), trace.getColor()));
                XYTextAnnotation xyText = new XYTextAnnotation(trace.getName(), x1, y);
                xyText.setFont(new Font("Verdana", Font.BOLD, 18));
                xyText.setTextAnchor(TextAnchor.CENTER_RIGHT);
                xyplot.addAnnotation(xyText);
            }
            iTrace++;
        }

        combinedPlot.add(xyplot, 1);

    } // panel

    final JFreeChart chart = new JFreeChart(combinedPlot);
    chart.setTitle(new TextTitle(plotTitle, new Font("Verdana", Font.BOLD, 18)));
    chart.removeLegend();

    try {
        ChartUtilities.saveChartAsPNG(outputFile, chart, 1400, 1400);
    } catch (IOException e) {
        // System.err.println("Problem occurred creating chart.");
        logger.error("IOException:", e);
    }

}

From source file:PointTest.java

private BranchGroup createPoints(final int nPointSize, final int nNumPoints, boolean bAliased) {
    BranchGroup bg = new BranchGroup();

    String szText = new String();
    szText += (nNumPoints + "X, Size:" + nPointSize + ", aliased: " + bAliased);

    Font3D f3d = new Font3D(new Font("SansSerif", Font.PLAIN, 1), new FontExtrusion());
    Text3D label3D = new Text3D(f3d, szText, new Point3f(-5, 0, 0));
    Shape3D sh = new Shape3D(label3D);

    bg.addChild(sh);/*w  ww.  j a  v a  2 s .  com*/

    PointArray pointArray = new PointArray(nNumPoints * nNumPoints,
            GeometryArray.COORDINATES | GeometryArray.COLOR_3);

    // create the PointArray that we will be rendering
    int nPoint = 0;
    final double factor = 1.0 / nNumPoints;

    for (int n = 0; n < nNumPoints; n++) {
        for (int i = 0; i < nNumPoints; i++) {
            Point3f point = new Point3f(n - nNumPoints / 2, i - nNumPoints / 2, 0.0f);
            pointArray.setCoordinate(nPoint, point);
            pointArray.setColor(nPoint++, new Color3f(0.5f, (float) (n * factor), (float) (i * factor)));
        }
    }

    // create the material for the points
    Appearance pointApp = new Appearance();

    // enlarge the points
    pointApp.setPointAttributes(new PointAttributes(nPointSize, bAliased));

    Shape3D pointShape = new Shape3D(pointArray, pointApp);

    bg.addChild(pointShape);
    return bg;
}

From source file:model.DrawTopologyDiagram.java

@Override
public void init() {

    //create a graph
    Graph<VertexTopology, Number> ig = Graphs.<VertexTopology, Number>synchronizedDirectedGraph(
            new DirectedSparseMultigraph<VertexTopology, Number>());

    ObservableGraph<VertexTopology, Number> og = new ObservableGraph<VertexTopology, Number>(ig);
    og.addGraphEventListener(new GraphEventListener<VertexTopology, Number>() {

        public void handleGraphEvent(GraphEvent<VertexTopology, Number> evt) {
            System.err.println("got " + evt);

        }/*w w w .  ja  v  a2s . c  o m*/
    });
    this.g = og;
    //layouts
    //create a graphdraw
    //        layout = new FRLayout2<String,Number>(g);
    //        layout = new SpringLayout<String,Number>(g);
    //        ((FRLayout)layout).setMaxIterations(200);
    layout = new KKLayout<VertexTopology, Number>(g);

    vv = new VisualizationViewer<VertexTopology, Number>(layout, new Dimension(600, 600));

    createGraph();

    Container content = getContentPane();
    JPanel totalCasesPanel = new JPanel();

    final JPanel scaleGrids = new JPanel(new GridLayout(0, 2));
    scaleGrids.add(new JLabel("   Test Cases      "));
    scaleGrids.add(new JLabel("       "));
    totalCasesPanel.add(scaleGrids);

    JPanel filteredCasesPanel = new JPanel();

    final JPanel filteredGrids = new JPanel(new GridLayout(0, 2));
    filteredGrids.add(new JLabel("   Filtered Cases      "));
    filteredGrids.add(new JLabel("       "));
    filteredCasesPanel.add(filteredGrids);

    JRootPane rp = this.getRootPane();
    rp.putClientProperty("defeatSystemEventQueueCheck", Boolean.TRUE);

    content.setLayout(new BorderLayout());
    content.setBackground(java.awt.Color.lightGray);
    content.setFont(new Font("Serif", Font.PLAIN, 12));

    vv.getModel().getRelaxer().setSleepTime(500);
    vv.setGraphMouse(new DefaultModalGraphMouse<VertexTopology, Number>());

    vv.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.CNTR);

    vv.setForeground(Color.white);

    FontMetrics fm = vv.getFontMetrics(vv.getFont());
    int width = fm.stringWidth(g.toString());

    Transformer<VertexTopology, Shape> vertexSize = new Transformer<VertexTopology, Shape>() {
        public Shape transform(VertexTopology i) {

            Ellipse2D circle = new Ellipse2D.Double(-20, -20, 40, 40);
            // in this case, the vertex is twice as large                
            return circle;
        }

    };

    vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
        @Override
        public String transform(Object v) {

            return ((VertexTopology) v).getScreenName();
        }
    });

    vv.getRenderContext().setVertexShapeTransformer(vertexSize);

    //Get picked states
    final PickedState<VertexTopology> pickedState = vv.getPickedVertexState();
    pickedState.addItemListener(new ItemListener() {
        ArrayList<TestCase> outputTestCase = new ArrayList<TestCase>();
        final Map<String, JButton> createdBtns = new HashMap<String, JButton>();

        Map<String, Integer> deviceSelected = new HashMap<String, Integer>(); // not useful

        ArrayList<String> endPointList = new ArrayList<String>();

        @Override
        public void itemStateChanged(ItemEvent e) {
            // TODO Auto-generated method stub
            Object subject = e.getItem();
            if (e.getStateChange() != 1) {
                scaleGrids.removeAll();
                filteredGrids.removeAll();
                endPointList.remove(getScreenName(subject));

                outputTestCase.clear();

                filteredGrids.repaint();
                filteredGrids.add(new JLabel("   Filtered Cases      "));
                filteredGrids.add(new JLabel("       "));

                scaleGrids.repaint();
                scaleGrids.add(new JLabel("   Test Cases      "));
                scaleGrids.add(new JLabel("       "));

                deviceSelected.clear();

            }
            if (e.getStateChange() == 1) {

                for (TestCase testCase : outputTestCase) {
                    scaleGrids.removeAll();
                    scaleGrids.add(new JLabel("   Test Cases      "));
                    scaleGrids.add(new JLabel("       "));

                    filteredGrids.removeAll();
                    filteredGrids.add(new JLabel("   Filtered Cases      "));
                    filteredGrids.add(new JLabel("       "));

                }

                if (subject instanceof VertexTopology) {
                    final VertexTopology edgePicked = (VertexTopology) subject;
                    if (pickedState.isPicked(edgePicked)) {

                        for (TestCase testCase : edgePicked.getTestCaseList()) {
                            if (!outputTestCase.contains(testCase))
                                outputTestCase.add(testCase);
                            System.out.println("The size for reference is " + testCase.inputReferenceMap.size()
                                    + testCase.getName());
                            System.out.println("The size for target is " + testCase.inputTargetMap.size()
                                    + testCase.getName());
                        }

                        if (deviceSelected.get(edgePicked.getScreenName()) != null)
                            deviceSelected.put(edgePicked.getScreenName(),
                                    deviceSelected.get(edgePicked.getScreenName()) + 1);
                        else
                            deviceSelected.put(edgePicked.getScreenName(), 1);

                        endPointList.add(edgePicked.getScreenName());

                    }
                }
            }

            for (TestCase testCase : outputTestCase) {
                JButton btnCase = new JButton(testCase.getName());
                scaleGrids.add(btnCase);

                if (testCase.getInputDeviceList().size() <= endPointList.size())
                    if (testCaseSelected(testCase, endPointList)) {
                        JButton btnCaseFiltered = new JButton(testCase.getName());
                        filteredGrids.add(btnCaseFiltered);
                    }
                ;

            }

            scaleGrids.revalidate();
            scaleGrids.setVisible(true);
        }

    });

    final DefaultModalGraphMouse graphMouse = new DefaultModalGraphMouse();
    vv.setGraphMouse(graphMouse);
    graphMouse.setMode(ModalGraphMouse.Mode.PICKING);

    content.setPreferredSize(new Dimension(1400, 900));
    content.add(vv);
    switchLayout = new JButton("Switch to SpringLayout");
    //        switchLayout.addActionListener(new ActionListener() {
    //
    //            @SuppressWarnings("unchecked")
    //            public void actionPerformed(ActionEvent ae) {
    //               Dimension d = new Dimension(600,600);
    //                if (switchLayout.getText().indexOf("Spring") > 0) {
    //                    switchLayout.setText("Switch to FRLayout");
    //                    layout = new SpringLayout<String,Number>(g,
    //                        new ConstantTransformer(EDGE_LENGTH));
    //                    layout.setSize(d);
    //                    vv.getModel().setGraphLayout(layout, d);
    //                } else {
    //                    switchLayout.setText("Switch to SpringLayout");
    //                    layout = new FRLayout<String,Number>(g, d);
    //                    vv.getModel().setGraphLayout(layout, d);
    //                }
    //            }
    //        });

    JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, totalCasesPanel, filteredCasesPanel);
    jSplitPane.setResizeWeight(.5d);

    content.add(switchLayout, BorderLayout.SOUTH);
    content.add(jSplitPane, BorderLayout.EAST);
}

From source file:net.sf.maltcms.chromaui.foldChangeViewer.tasks.FoldChangeViewLoaderWorker.java

@Override
public void run() {
    ProgressHandle handle = ProgressHandleFactory.createHandle("Creating fold change plot");
    try {// w w  w.j a  v  a 2s.co m
        handle.setDisplayName("Loading fold change elements");//+new File(this.files.getResourceLocation()).getName());
        handle.start(5);
        handle.progress("Reading settings", 1);
        RTUnit rtAxisUnit = RTUnit.valueOf(sp.getProperty("rtAxisUnit", "SECONDS"));
        handle.progress("Retrieving data", 2);
        XYShapeRenderer renderer = new XYShapeRenderer() {

            @Override
            protected Paint getPaint(XYDataset dataset, int series, int item) {
                double x = dataset.getXValue(series, item);
                double y = dataset.getYValue(series, item);
                if (Math.abs(x) < 1.0) {
                    Paint p = super.getPaint(dataset, series, item);
                    if (p instanceof Color) {
                        Color color = (Color) p;
                        float[] values = Color.RGBtoHSB(color.getRed(), color.getGreen(), color.getBlue(),
                                new float[3]);
                        Color hsb = new Color(
                                Color.HSBtoRGB(values[0], (float) Math.max(0.1, values[1] - 0.9), values[2]));
                        return new Color(hsb.getRed(), hsb.getGreen(), hsb.getBlue(), 64);
                    }
                }
                return super.getPaint(dataset, series, item);
            }

        };
        renderer.setAutoPopulateSeriesFillPaint(true);
        renderer.setAutoPopulateSeriesOutlinePaint(true);
        renderer.setBaseCreateEntities(true);
        handle.progress("Building plot", 3);
        XYPlot plot = new XYPlot(dataset, new NumberAxis("log2 fold change"), new NumberAxis("-log10 p-value"),
                renderer);
        BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 5.0f,
                new float[] { 5.0f }, 0.0f);
        ValueMarker marker = new ValueMarker(-Math.log10(0.05), Color.RED, dashed);
        marker.setLabel("p-value=0.05");
        marker.setLabelAnchor(RectangleAnchor.BOTTOM_LEFT);
        marker.setLabelOffset(new RectangleInsets(UnitType.ABSOLUTE, 0, 50, 10, 0));
        marker.setLabelOffsetType(LengthAdjustmentType.EXPAND);
        marker.setLabelPaint(Color.LIGHT_GRAY);
        plot.addRangeMarker(marker);

        Font font1 = new Font("SansSerif", Font.PLAIN, 12);
        SelectionAwareXYTooltipGenerator tooltipGenerator = cvtc.getLookup()
                .lookup(SelectionAwareXYTooltipGenerator.class);
        if (tooltipGenerator == null) {
            tooltipGenerator = new SelectionAwareXYTooltipGenerator(tooltipGenerator) {
                @Override
                public String createSelectionAwareTooltip(XYDataset xyd, int i, int i1) {
                    FoldChangeDataset dataset = (FoldChangeDataset) xyd;
                    FoldChangeElement fce = dataset.getNamedElementProvider().get(i).get(i1);
                    StringBuilder sb = new StringBuilder();
                    sb.append("<html>");
                    sb.append(fce.getPeakGroup().getMajorityDisplayName());
                    sb.append("<br>");
                    sb.append("log2 fold change=");
                    sb.append(fce.getFoldChange());
                    sb.append("<br>");
                    sb.append("p-value=");
                    sb.append(Math.pow(10, -fce.getPvalue()));
                    sb.append("</html>");
                    return sb.toString();
                }
            };
        }
        tooltipGenerator.setXYToolTipGenerator(new XYToolTipGenerator() {
            @Override
            public String generateToolTip(XYDataset xyd, int i, int i1) {
                Comparable comp = xyd.getSeriesKey(i);
                double x = xyd.getXValue(i, i1);
                double y = xyd.getYValue(i, i1);
                StringBuilder sb = new StringBuilder();
                sb.append("<html>");
                sb.append(comp);
                sb.append("<br>");
                sb.append("log2 fold change=");
                sb.append(x);
                sb.append("<br>");
                sb.append("p-value=");
                sb.append(sb.append(Math.pow(10, -y)));
                sb.append("</html>");
                return sb.toString();
            }
        });
        plot.getRenderer().setBaseToolTipGenerator(tooltipGenerator);
        handle.progress("Configuring plot", 4);
        configurePlot(plot, rtAxisUnit);
        final FoldChangeViewPanel cmhp = cvtc.getLookup().lookup(FoldChangeViewPanel.class);
        Range domainRange = null;
        Range valueRange = null;
        if (cmhp != null) {
            XYPlot xyplot = cmhp.getPlot();
            if (xyplot != null) {
                ValueAxis domain = xyplot.getDomainAxis();
                domainRange = domain.getRange();
                ValueAxis range = xyplot.getRangeAxis();
                valueRange = range.getRange();
            }
        }

        if (domainRange != null) {
            plot.getDomainAxis().setRange(domainRange);
        }
        if (valueRange != null) {
            Logger.getLogger(getClass().getName()).info("Setting previous value range!");
        }
        handle.progress("Adding plot to panel", 5);
        final XYPlot targetPlot = plot;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                final FoldChangeViewPanel cmhp = cvtc.getLookup().lookup(FoldChangeViewPanel.class);
                cmhp.setPlot(targetPlot);
                cvtc.requestActive();
            }
        });
    } finally {
        handle.finish();
    }
}