Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.*;
- import java.text.DecimalFormat;
- import java.text.DecimalFormatSymbols;
- import javax.swing.*;
- import javax.swing.table.DefaultTableCellRenderer;
- public class SimpleTableExample extends JFrame {
- private final JPanel topPanel;
- private final JTable table;
- private final JScrollPane scrollPane;
- public SimpleTableExample() {
- setTitle( "Simple Table Application" );
- setSize( 300, 200 );
- setBackground( Color.gray );
- setDefaultCloseOperation(JDialog.EXIT_ON_CLOSE);
- topPanel = new JPanel();
- topPanel.setLayout( new BorderLayout() );
- getContentPane().add( topPanel );
- table = new JTable();
- table.setModel(new javax.swing.table.DefaultTableModel(
- new Object [][] {{"IT01", "Shoes", new Double(3233233.87)}, {"IT02", "Hammer", new Double(321233.87)}},
- new String [] { "ID", "ITEM", "PRICE" }
- ) {
- Class[] types = new Class [] {
- java.lang.String.class, java.lang.String.class, java.lang.Double.class
- };
- public Class getColumnClass(int columnIndex) {
- return types [columnIndex];
- }
- });
- table.getColumnModel().getColumn(2).setCellRenderer(new DecimalFormatRenderer() );
- scrollPane = new JScrollPane(table);
- topPanel.add(scrollPane, BorderLayout.CENTER);
- }
- public static void main( String args[] ) {
- SimpleTableExample mainFrame = new SimpleTableExample();
- mainFrame.setVisible( true );
- }
- static class DecimalFormatRenderer extends DefaultTableCellRenderer {
- private static final DecimalFormatSymbols dfs = new DecimalFormatSymbols() ;
- private static final DecimalFormat dfCurrency = new DecimalFormat("#,###.##");
- public DecimalFormatRenderer() {
- super();
- dfs.setDecimalSeparator(',');
- dfs.setGroupingSeparator('.');
- dfCurrency.setDecimalFormatSymbols(dfs);
- }
- public Component getTableCellRendererComponent(
- JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
- // First format the cell value as required
- value = dfCurrency.format((Number)value);
- // And pass it on to parent class
- return super.getTableCellRendererComponent(
- table, value, isSelected, hasFocus, row, column );
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement