Example usage for java.text NumberFormat getNumberInstance

List of usage examples for java.text NumberFormat getNumberInstance

Introduction

In this page you can find the example usage for java.text NumberFormat getNumberInstance.

Prototype

public static final NumberFormat getNumberInstance() 

Source Link

Document

Returns a general-purpose number format for the current default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:cn.edu.thss.iise.bpmdemo.statistics.actions.ModelReusePanel.java

private JPanel createPanel() throws IOException {
    createDataSet();//from   w  w w.  ja  v a 2 s .c o  m

    // create the chart...
    final JFreeChart chart = ChartFactory.createPieChart("Reused Times", // chart
            // title
            data1, // dataset
            false, // include legend
            true, false);

    // set the background color for the chart...
    chart.setBackgroundPaint(new Color(222, 222, 255));

    final PiePlot plot = (PiePlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setCircular(true);
    plot.setLabelGenerator(new StandardPieItemLabelGenerator("{0} = {2}", NumberFormat.getNumberInstance(),
            NumberFormat.getPercentInstance()));
    plot.setNoDataMessage("No data available");

    // add the chart to a panel...
    final ChartPanel chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new java.awt.Dimension(500, 270));

    String[] columnNames = { "Name", "Reuse Times" };
    JTable table = new JTable(data2, columnNames);
    JPanel panel = new JPanel();
    panel.add(chartPanel);
    panel.add(table);
    final Rotator rotator = new Rotator(plot);
    rotator.start();
    return panel;
}

From source file:com.pureinfo.srm.reports.impl.PieChartBuilder.java

private void fillChartInfo(DefaultPieDataset _dataset) {
    int n = _dataset.getItemCount();
    m_ChartInfo = new ChartInfo();
    m_ChartInfo.setChartTitle(m_sTitle);
    NumberFormat format = NumberFormat.getNumberInstance();
    String[] labels = new String[n];
    for (int i = 0; i < n; i++) {
        labels[i] = "" + _dataset.getKey(i);
        labels[i] += " = ";
        labels[i] += format.format(_dataset.getValue(i));
        double totalValue = DatasetUtilities.calculatePieDatasetTotal(_dataset);
        if (totalValue != 0) {
            labels[i] += "  ";
            labels[i] += PERCENT_NUMBER_FORMAT.format(_dataset.getValue(i).doubleValue() / totalValue);
        }/*w  w w .  j a  v  a 2  s . c  o m*/
    }
    m_ChartInfo.setLabels(labels);
    m_ChartInfo.setShowBoder(true);
    m_ChartInfo.setChartSize(ChartInfo.SIZE_WIDE_AND_THIN);
    m_ChartInfo.setLengedPosition(ChartInfo.LENGEND_POSITION_BUTTOM);
}

From source file:com.twocents.report.charts.StandardPieItemLabelGenerator.java

/**
 * Creates an item label generator using default number formatters.
 *///from  w  w  w  .  jav a  2  s. c o m
public StandardPieItemLabelGenerator() {
    this(DEFAULT_SECTION_LABEL_FORMAT, NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance());
}

From source file:edu.monash.merc.struts2.action.TLSumChartAction.java

@SuppressWarnings("unchecked")
public String piechart() {
    DefaultPieDataset dataset = new DefaultPieDataset();
    dataset.setValue("Green", l4);
    dataset.setValue("Yellow", l3);
    dataset.setValue("Red", l2);
    dataset.setValue("Black", l1);

    chart = ChartFactory.createPieChart(dt, dataset, true, true, false);
    PiePlot plot = (PiePlot) chart.getPlot();

    plot.setBackgroundPaint(Color.WHITE);
    //no border/* w  w w  . java2  s .c o m*/
    plot.setOutlineStroke(null);
    //no label
    plot.setLabelGenerator(null);

    NumberFormat percentFormat = NumberFormat.getPercentInstance();
    percentFormat.setMaximumFractionDigits(2);
    plot.setLegendLabelGenerator(
            new StandardPieSectionLabelGenerator("{0}={2}", NumberFormat.getNumberInstance(), percentFormat));
    //set specific colors  green, yellow, red and black
    Color[] colors = { new Color(0, 140, 0), new Color(254, 172, 0), new Color(226, 0, 40),
            new Color(0, 0, 0) };
    setColor(plot, dataset, colors);

    chart.setBackgroundPaint(Color.WHITE);
    chart.getTitle().setFont(chart.getTitle().getFont().deriveFont(11.0f));
    return SUCCESS;
}

From source file:com.shahnami.fetch.Controller.FetchMovies.java

public List<Movie> getBollyMovies(String query) {
    try {/* w ww .ja  v  a  2  s .c o  m*/
        Document doc;
        Elements searchDetails;
        String link;
        String title;
        String image = null;
        Elements linkAndTitles;
        Document movieDetails;
        double rating = 0;
        String magnetLink;
        String torrentFile;
        NumberFormat formatter;
        String output;
        if (query.equalsIgnoreCase("")) {
            //
        } else {
            doc = Jsoup.connect("https://1337x.to/search/" + URLEncoder.encode(query, "UTF-8") + "+hindi/1/")
                    .userAgent("Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.7.2) Gecko/20040803").get();
            searchDetails = doc.getElementsByClass("coll-1");
            for (Element e : searchDetails) {
                linkAndTitles = e.getElementsByTag("strong");
                for (Element e1 : linkAndTitles) {
                    link = "https://1337x.to" + e1.getElementsByTag("a").first().attr("href");
                    title = e1.getElementsByTag("a").first().html();
                    if (!link.contains("/mirror")) {
                        Movie m = new Movie();
                        m.setTitle(title.replace("<b>", "").replace("</b>", "").trim()); //.substring(0, 47)+ "..."
                        m.setLanguage("Hindi");
                        m.setUrl(link);
                        Pattern pattern = Pattern.compile(".*([\\s(]+[0-9]{4}[\\s)]+).*");
                        Matcher matcher = pattern.matcher(title);
                        while (matcher.find()) {
                            m.setYear(Integer
                                    .parseInt(matcher.group(1).replace("(", "").replace(")", "").trim()));
                        }
                        movieDetails = Jsoup.connect(link).get();
                        try {
                            image = movieDetails.getElementsByClass("moive-box").first().getElementsByTag("img")
                                    .first().attr("src");
                            rating = Float.parseFloat(
                                    movieDetails.getElementsByClass("rateing").first().getElementsByTag("i")
                                            .attr("style").split(":")[1].replace("%;", "").trim());
                        } catch (Exception ex) {
                            //
                        }
                        magnetLink = movieDetails.getElementsByClass("magnet").first().attr("href");
                        torrentFile = movieDetails.getElementsByClass("torrent").first().attr("href");
                        formatter = NumberFormat.getNumberInstance();
                        formatter.setMinimumFractionDigits(2);
                        formatter.setMaximumFractionDigits(2);
                        output = formatter.format(rating / 10);
                        rating = Double.parseDouble(output);
                        if (rating < 1) {
                            rating = 0;
                        }
                        m.setRating(rating);
                        m.setSmall_cover_image(image);
                        List<Torrent> torrents = new ArrayList<>();
                        Torrent t = new Torrent();
                        t.setUrl(magnetLink);
                        Torrent t2 = new Torrent();
                        t2.setUrl(torrentFile);
                        torrents.add(t);
                        torrents.add(t2);
                        m.setTorrents(torrents);
                        m.getTorrents().get(0).setSeeds(
                                Integer.valueOf(movieDetails.getElementsByClass("green").first().text()));
                        m.getTorrents().get(0).setPeers(
                                Integer.valueOf(movieDetails.getElementsByClass("red").first().text()));
                        m.setIsBollywood(true);
                        m.setSize(movieDetails.getElementsByClass("list").first().getElementsByTag("li").get(3)
                                .text().substring(10).trim());
                        _movies.add(m);
                    }
                }
                //String link = linkAndTitle.getElementsByAttribute("href").first().text();
                //System.out.println(link);
                //String title = linkAndTitle.getElementsByTag("b").text();
                //System.out.println(title);
            }
        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(FetchMovies.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(FetchMovies.class.getName()).log(Level.SEVERE, null, ex);
    }
    return _movies;
}

From source file:eu.choreos.vv.chart.XYChart.java

private static JFreeChart createChart(XYDataset dataset, String chartTitle, String xLabel, String yLabel) {

    // create the chart...
    JFreeChart chart = ChartFactory.createXYLineChart(chartTitle, // chart title
            xLabel, // domain axis label
            yLabel, // range axis label
            dataset, // initial series
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips?
            false // URLs?
    );/*w ww . j a va 2 s  .com*/

    // set chart background
    chart.setBackgroundPaint(Color.white);

    // set a few custom plot features
    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(new Color(0xffffe0));
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.lightGray);
    plot.setRangeGridlinePaint(Color.lightGray);

    // set the plot's axes to display integers
    TickUnitSource ticks = NumberAxis.createIntegerTickUnits();
    NumberAxis domain = (NumberAxis) plot.getDomainAxis();
    domain.setStandardTickUnits(ticks);
    domain.resizeRange(1.1);
    domain.setLowerBound(0.5);

    NumberAxis range = (NumberAxis) plot.getRangeAxis();
    range.setStandardTickUnits(ticks);
    range.setUpperBound(range.getUpperBound() * 1.1);

    // render shapes and lines
    XYLineAndShapeRenderer renderer = new XYLineAndShapeRenderer(true, true);
    plot.setRenderer(renderer);
    renderer.setBaseShapesVisible(true);
    renderer.setBaseShapesFilled(true);

    // set the renderer's stroke
    Stroke stroke = new BasicStroke(3f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_BEVEL);
    renderer.setBaseOutlineStroke(stroke);

    // label the points
    NumberFormat format = NumberFormat.getNumberInstance();
    format.setMaximumFractionDigits(2);
    XYItemLabelGenerator generator = new StandardXYItemLabelGenerator(
            StandardXYItemLabelGenerator.DEFAULT_ITEM_LABEL_FORMAT, format, format);
    renderer.setBaseItemLabelGenerator(generator);
    renderer.setBaseItemLabelsVisible(true);

    return chart;
}

From source file:org.apache.derbyDemo.scores.proc.Functions.java

/**
 * <p>//www. j av  a  2s.c om
 * Format a double as a percentage, suitable for printing.
 * </p>
 */
public static String formatPercent(double score) throws SQLException {
    int rounded = (int) score;
    NumberFormat nf = NumberFormat.getNumberInstance();

    return nf.format(rounded);
}

From source file:net.kjmaster.cookiemom.booth.add.AddBoothDialogFragment.java

private void showDateTimeDialog() {
    // Create the dialog
    final Dialog mDateTimeDialog = new Dialog(getActivity());
    // Inflate the root layout
    final RelativeLayout mDateTimeDialogView = (RelativeLayout) getActivity().getLayoutInflater()
            .inflate(R.layout.ui_date_time_dialog, null);
    // Grab widget instance
    final DateTimePicker mDateTimePicker = (DateTimePicker) mDateTimeDialogView
            .findViewById(R.id.DateTimePicker);
    // Check is system is set to use 24h time (this doesn't seem to work as expected though)
    final String timeS = android.provider.Settings.System.getString(getActivity().getContentResolver(),
            android.provider.Settings.System.TIME_12_24);
    final boolean is24h = !(timeS == null || timeS.equals("12"));

    // Update demo TextViews when the "OK" button is clicked
    mDateTimeDialogView.findViewById(R.id.SetDateTime).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            mDateTimePicker.clearFocus();
            // TODO Auto-generated method stub

            String eventDate = SimpleDateFormat.getDateInstance(DateFormat.LONG)
                    .format(new Date(mDateTimePicker.getDateTimeMillis()));
            ((TextView) getActivity().findViewById(R.id.Date)).setText(eventDate);
            if (mDateTimePicker.is24HourView()) {
                ((TextView) getActivity().findViewById(R.id.Time)).setText(
                        mDateTimePicker.get(Calendar.HOUR_OF_DAY) + ":" + mDateTimePicker.get(Calendar.MINUTE));
            } else {
                NumberFormat fmt = NumberFormat.getNumberInstance();
                fmt.setMinimumIntegerDigits(2);

                ((TextView) getActivity().findViewById(R.id.Time))
                        .setText(fmt.format(mDateTimePicker.get(Calendar.HOUR)) + ":"
                                + fmt.format(mDateTimePicker.get(Calendar.MINUTE)) + " "
                                + (mDateTimePicker.get(Calendar.AM_PM) == Calendar.AM ? "AM" : "PM"));

            }//from   ww w . j  a  v  a  2 s. c  o m

            hiddenDateTime.setText(String.valueOf(mDateTimePicker.getDateTimeMillis()));
            mDateTimeDialog.dismiss();
        }
    });

    // Cancel the dialog when the "Cancel" button is clicked
    mDateTimeDialogView.findViewById(R.id.CancelDialog).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            mDateTimeDialog.cancel();
        }
    });

    // Reset Date and Time pickers when the "Reset" button is clicked
    mDateTimeDialogView.findViewById(R.id.ResetDateTime).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            mDateTimePicker.reset();
        }
    });

    // Setup TimePicker
    mDateTimePicker.setIs24HourView(is24h);
    // No title on the dialog window
    mDateTimeDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    // Set the dialog content view
    mDateTimeDialog.setContentView(mDateTimeDialogView);
    // Display the dialog
    mDateTimeDialog.show();
}

From source file:com.twocents.report.charts.StandardPieItemLabelGenerator.java

/**
 * Creates an item label generator.//from   w  ww .java 2s . com
 * 
 * @param labelFormat  the label format.
 */
public StandardPieItemLabelGenerator(String labelFormat) {
    this(labelFormat, NumberFormat.getNumberInstance(), NumberFormat.getPercentInstance());
}

From source file:com.clustercontrol.http.factory.RunMonitorHttp.java

/**
 * HTTP ?/*www  . j a va 2s .c o m*/
 * 
 * @param facilityId ID
 * @return ???????true
 */
@Override
public boolean collect(String facilityId) {

    if (m_now != null) {
        m_nodeDate = m_now.getTime();
    }
    m_value = 0;
    m_message = "";
    m_messageOrg = "";

    ;

    String url = m_requestUrl;
    // ???URL??
    if (nodeInfo != null && nodeInfo.containsKey(facilityId)) {
        Map<String, String> nodeParameter = RepositoryUtil.createNodeParameter(nodeInfo.get(facilityId));
        StringBinder strbinder = new StringBinder(nodeParameter);
        url = strbinder.bindParam(m_requestUrl);
        if (m_log.isTraceEnabled())
            m_log.trace("http request. (nodeInfo = " + nodeInfo + ", facilityId = " + facilityId + ", url = "
                    + url + ")");
    }

    boolean result = false;
    try (GetHttpResponse m_request = GetHttpResponse.custom().setConnectTimeout(m_httpTimeout)
            .setRequestTimeout(m_httpTimeout)
            .setNeedAuthSSLCert(!HinemosPropertyUtil.getHinemosPropertyBool("monitor.http.ssl.trustall", true))
            .build()) {
        result = m_request.execute(url);
        if (result) {
            m_value = m_request.getResponseTime();

            m_message = MessageConstant.RESPONSE_TIME_MILLI_SEC.getMessage() + " : "
                    + NumberFormat.getNumberInstance().format(m_value);

            StringBuffer response = new StringBuffer();
            response.append(MessageConstant.REQUEST_URL.getMessage() + " : " + url);
            response.append(
                    "\n" + MessageConstant.STATUS_CODE.getMessage() + " : " + m_request.getStatusCode());
            if (m_request.getHeaderString() != null && !"".equals(m_request.getHeaderString().trim())) {
                response.append("\n" + MessageConstant.HEADER.getMessage() + " :\n"
                        + m_request.getHeaderString().trim());
            }
            if (m_request.getResponseBody() != null && !"".equals(m_request.getResponseBody().trim())) {
                response.append("\n" + MessageConstant.RESPONSE_BODY.getMessage() + " :\n"
                        + m_request.getResponseBody().trim());
            }
            m_messageOrg = response.toString();
        } else {
            m_message = MessageConstant.MESSAGE_COULD_NOT_GET_VALUE_HTTP.getMessage();

            StringBuffer response = new StringBuffer();
            response.append(m_request.getErrorMessage());
            response.append("\n");
            response.append("\n" + MessageConstant.REQUEST_URL.getMessage() + " : " + url);
            response.append(
                    "\n" + MessageConstant.STATUS_CODE.getMessage() + " : " + m_request.getStatusCode());
            if (m_request.getHeaderString() != null && !"".equals(m_request.getHeaderString().trim())) {
                response.append("\n" + MessageConstant.HEADER.getMessage() + " :\n"
                        + m_request.getHeaderString().trim());
            }
            m_messageOrg = response.toString();
        }
    } catch (IOException e) {
        m_log.warn("fail to close HttpClient : " + e.getMessage(), e);
    }
    return result;
}