NumberViewer.java Source code

Java tutorial

Introduction

Here is the source code for NumberViewer.java

Source

import java.text.NumberFormat;
import java.util.Locale;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;

public class NumberViewer extends JPanel {
    protected AbstractTableModel tableModel;

    protected double currentValue = 1234567.89d;

    protected final static Locale[] availableLocales;

    static {
        availableLocales = Locale.getAvailableLocales();
    }

    public final static int LOCALE_COLUMN = 0;

    public final static int NUMBER_COLUMN = 1;

    public final static int CURRENCY_COLUMN = 2;

    public final static int PERCENT_COLUMN = 3;

    public final static String[] columnHeaders = { "Locale", "Numeric", "Currency", "Percent" };

    public static void main(String[] args) {
        JFrame f = new JFrame("Number Viewer");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(new NumberViewer());
        f.pack();
        f.setVisible(true);
    }

    public NumberViewer() {
        tableModel = new LocaleTableModel();
        JTable table = new JTable(tableModel);
        add(new JScrollPane(table));
    }

    class LocaleTableModel extends AbstractTableModel {
        public int getRowCount() {
            return availableLocales.length;
        }

        public int getColumnCount() {
            return columnHeaders.length;
        }

        public Object getValueAt(int row, int column) {
            Locale locale = availableLocales[row];
            NumberFormat formatter = NumberFormat.getNumberInstance();
            switch (column) {
            case LOCALE_COLUMN:
                return locale.getDisplayName();
            case NUMBER_COLUMN:
                formatter = NumberFormat.getNumberInstance(locale);
                break;
            case CURRENCY_COLUMN:
                formatter = NumberFormat.getCurrencyInstance(locale);
                break;
            case PERCENT_COLUMN:
                formatter = NumberFormat.getPercentInstance(locale);
                break;
            }
            return formatter.format(currentValue);
        }

        public String getColumnName(int column) {
            return columnHeaders[column];
        }
    }
}