Go Back   Java Programming Forums > Learning Java > Java Code Snippets and Tutorials


Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 07-02-2010, 04:56 AM
chronoz13's Avatar
Java kindergarten
 

Join Date: Mar 2009
Location: Squatters Mansion
Posts: 405
Thanks: 113
Thanked 21 Times in 21 Posts
chronoz13 is on a distinguished road

I'm feeling Stressed
Default JTable simple Solutions

in this thread you will see a different solutions on the problems that you might encounter when you are dealing with JTable , I would like to share this because google cannot give a very pure solutions in this problems, (and im currently encountering that, but I hope our fellow proffesional forum mates will post any comments on this codes

JTable: Adding Rows and Columns with Auto-Scoll
Java Code
public class JTableAddingRowsAndColumnsWithAutoScroll extends JFrame {

    public static void main(String[] args) {

        JFrame frame = new JFrame();
        final JTable table;
        JScrollPane scroll;
        JPanel inventoryPanel = new JPanel();
        JButton addRow = new JButton("Add row");
        JButton addCol = new JButton("Add column");
        
        final DefaultTableModel model;
        
        final String[] columnNames = {"Item Code", "Item Quantity", "Item Desciption", "Item Cost",
                                      "Cost Extension", "Retail", "Retail Extension", "Expiration Code", "asdasd"};


        final Object[][] data = {{"1000008", "TOBI MIX NUTS 45g", new Integer(32), new Double(18.52), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000013",  "TOBI MELON SEEDs 100g", new Integer(45), new Double(30.00), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000002", "TOBI MIX NUTS 100g", new Integer(15), new Double(39.59), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)} ,
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000015", "TOBI SQUASH SEEDS 100g", new Integer(323), new Double(31.35), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)},
                                {"1000018", "CASINO FEM E ALC70%SOL 250mL", new Integer(64), new Double(26.36), new Double(100.50),
                                new Double(21.75), new Double(150.50), new Long(100142)}};

        model = new DefaultTableModel(data, columnNames);

        table = new JTable(model);

        scroll = new JScrollPane(table);
        scroll.setBounds(0, 150, 1395, 220);

        addRow.setBounds(10, 30, 150, 20);
        addRow.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                model.addRow(new Object[] {null,null,null,null,null,null,null,null});

                // this will automatically set the view of the scroll in the location of the value
                table.scrollRectToVisible(table.getCellRect(table.getRowCount() - 1, table.getColumnCount(), true));
            }
        });

        addCol.setBounds(180, 30, 150, 20);
        addCol.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                model.addColumn("New Column");
                table.scrollRectToVisible(table.getCellRect(table.getColumnCount(), table.getRowCount(), true));
            }
        });
        inventoryPanel.setLayout(null);

        inventoryPanel.add(addRow);
        inventoryPanel.add(addCol);
        inventoryPanel.add(scroll);

        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(inventoryPanel);
        frame.setSize(1400, 398);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}
JTable: Automatic Cell Computation , with mouse and key events
Java Code
public class JTableAutomaticCellComputation extends JFrame {

    private JTable table;
    private JPanel lowerPanel;
    private JScrollPane scroll;

    public JTableAutomaticCellComputation() {

        initializeInventory();
    }

    private void initializeInventory() {

        lowerPanel = new JPanel();
        
        lowerPanel.setLayout(new BorderLayout(1,2));

        final String[] columnNames = {"Number1", "Number2", "Sum"};
        final Object[][] data = new Object[5][3];

        TableModel model = new DefaultTableModel(data, columnNames);

        table = new JTable(model);

        // allow row and column selection
        table.setColumnSelectionAllowed(true);
        table.setRowSelectionAllowed(true);

        // add listener to this table
        table.addMouseListener(new MyMouseListener());
        table.addKeyListener(new MyKeyListener());

        scroll = new JScrollPane(table);
        scroll.setBounds(0, 0, 900, 400);

        lowerPanel.add(scroll);

        getContentPane().add(lowerPanel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Inventory Window");
        setSize(1400, 400);
        setLocationRelativeTo(null);
        setVisible(true);

    }
    
    private class MyKeyListener extends KeyAdapter {

        public void keyReleased(KeyEvent e) {

            if (table.getSelectedColumn() == 2 && (e.getKeyCode() == KeyEvent.VK_TAB
                || e.getKeyCode() == KeyEvent.VK_ENTER)) {

                if (table.getValueAt(table.getSelectedRow(), 0) == null || table.getValueAt(table.getSelectedRow(), 1) == null) {

                    System.out.println("Null Cell Value");
                }
                else {

                    Integer a = Integer.parseInt(table.getValueAt(table.getSelectedRow(), 0).toString());
                    Integer b = Integer.parseInt(table.getValueAt(table.getSelectedRow(), 1).toString());
                  
                    table.setValueAt(a + b, table.getSelectedRow(), 2);
                }
            }
        }
    }

    private class MyMouseListener extends MouseAdapter {

        public void mousePressed(MouseEvent e) {

            if (table.getSelectedColumn() == 2) {

                if (table.getValueAt(table.getSelectedRow(), 0) == null || table.getValueAt(table.getSelectedRow(), 1) == null) {

                    System.out.println("Null Cell Value");
                }
                else {

                    Integer a = Integer.parseInt(table.getValueAt(table.getSelectedRow(), 0).toString());
                    Integer b = Integer.parseInt(table.getValueAt(table.getSelectedRow(), 1).toString());

                    table.setValueAt(a + b, table.getSelectedRow(), 2);
                }
            }
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
         
                new JTableAutomaticCellComputation();
            }
        });
    }
}
JTable: This program displays the selected Column/Row(The Cell) in a console output
Java Code
public class JTableKeyListenerForCellSelection extends JFrame {

    private JTable table;
    private JPanel lowerPanel;
    private JScrollPane scroll;

    public JTableKeyListenerForCellSelection() {

        initializeInventory();
    }

    private void initializeInventory() {

        lowerPanel = new JPanel();
        lowerPanel.setLayout(new BorderLayout());

        final String[] columnNames = {"First", "Second", "Third", "Fourth"};
        final Object[][] data = new Object[100][columnNames.length];

        table = new JTable(data, columnNames);

        table.setRowSelectionAllowed(true);
        table.setColumnSelectionAllowed(true);
        table.addKeyListener(new MyKeyListener());
        
        scroll = new JScrollPane(table);
        scroll.setBounds(0, 0, 1395, 400);

        lowerPanel.add(scroll);

        getContentPane().add(lowerPanel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Inventory Window");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    // class for implementing the key listener
    private class MyKeyListener extends KeyAdapter {

        public void keyReleased(KeyEvent e) {

            if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN
                || e.getKeyCode() == KeyEvent.VK_LEFT || e.getKeyCode() == KeyEvent.VK_RIGHT) {

                int rowIdx = table.getSelectedRow();
                int colIdx = table.getSelectedColumn();

                System.out.println("Row: " + rowIdx + "  " + "Column: " + colIdx);
            }
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new JTableKeyListenerForCellSelection();
            }
        });
    }
}
JTable: Setting the column width
Java Code
public class JTableManualSettingOfColumnWidth {

    public static void main(String[] args) {

        final JFrame frame = new JFrame();
        JTable inventoryTable;
        JScrollPane tableScroll;
        String[]columnNames = {"Short Column Width", "Semi-Long Column Width", "Long Column Widht"};

        Object[][] data = new Object[100][columnNames.length];

        inventoryTable = new JTable(data, columnNames);
        inventoryTable.setOpaque(false);
        inventoryTable.setGridColor(Color.BLACK);
        inventoryTable.setPreferredScrollableViewportSize(new Dimension(500, 70));
        inventoryTable.setAutoCreateRowSorter(true);
        inventoryTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        inventoryTable.getColumnModel().getColumn(0).setPreferredWidth(150);
        inventoryTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        inventoryTable.getColumnModel().getColumn(2).setPreferredWidth(360);

        tableScroll = new JScrollPane(inventoryTable);
        
        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(tableScroll);
        frame.setSize(660, 398);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}
JTable: A program that demonstrates a listening event when a user click the column Header
Java Code
public class JTableMouseListenerForHeadersAndCells extends JFrame {

    private JTable table;
    private JPanel lowerPanel;
    private JScrollPane scroll;
    private JTableHeader header;

    public JTableMouseListenerForHeadersAndCells() {

        initializeInventory();
    }

    private void initializeInventory() {

        lowerPanel = new JPanel();
        lowerPanel.setLayout(new BorderLayout());

        final String[] columnNames = {"First", "Second", "Third", "Fourth"};
        final Object[][] data = new Object[100][columnNames.length];

        table = new JTable(data, columnNames);

        header = table.getTableHeader();
        header.addMouseListener(new MyMouseAdapter());
        table.addMouseListener(new MyMouseAdapter());
        
        scroll = new JScrollPane(table);

        lowerPanel.add(scroll);

        getContentPane().add(lowerPanel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setTitle("Inventory Window");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

    // class for implementing the mouse listener
    private class MyMouseAdapter extends MouseAdapter {

        public void mousePressed(MouseEvent e) {
            
            if (table.equals(e.getSource())) {

                int colIdx = table.columnAtPoint(e.getPoint());
                int rowIdx = table.rowAtPoint(e.getPoint());
                
                System.out.println("Row: " + rowIdx + " " + "Colulmn: " + colIdx);
            }
            else if (header.equals(e.getSource())) {
                
                int selectedColumnIdx = header.columnAtPoint(e.getPoint());
                String colName = table.getColumnName(header.columnAtPoint(e.getPoint()));

                System.out.println("Column Name: " + colName);
                System.out.println("Selected Column: " + selectedColumnIdx);
            }
        }
    }
    
    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new JTableMouseListenerForHeadersAndCells();
            }
        });
    }
}


JTable: RowSorter
Java Code
public class JTableRowSorter extends JFrame {

    public static void main(String[] args) {

        final JFrame frame = new JFrame();
        final ImageIcon tableBackground = new ImageIcon("c:/pics/inventorytablebck.jpg");
        
        JTable inventoryTable;
        JScrollPane scroll;
        JPanel inventoryPanel = new JPanel();;
        TableModel model;
        
        final String[] columnNames = {"Item Code", "Item Quantity", "Item Desciption", "Item Cost",
                                      "Cost Extension", "Retail", "Retail Extension", "Expiration Code"};


        final Object[][] data = {{"1000008", new Integer(32), "TOBI MIX NUTS 45g", new Double(18.52), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)},
                                 {"1000013", new Integer(45), "TOBI MELON SEEDs 100g", new Double(30.00), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)},
                                 {"1000002", new Integer(15), "TOBI MIX NUTS 100g", new Double(39.59), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)} ,
                                 {"1000015", new Integer(323), "TOBI SQUASH SEEDS 100g", new Double(31.35), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)},
                                 {"1000018", new Integer(64), "CASINO FEM E ALC70%SOL 250mL", new Double(26.36), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)},
                                 {"1000005", new Integer(123), "CASINO FEM E ALC70%SOL 500mL", new Double(45.41), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)},
                                 {"1000021", new Integer(154), "EIGHT O CLOCK MGO 100%43.5g", new Double(8.54), new Double(100.50),
                                 new Double(21.75), new Double(150.50), new Long(100142)}};

        model = new DefaultTableModel(data, columnNames) {

            public Class getColumnClass(int column) {

                Class returnValue;

                if ((column >= 0) && (column < getColumnCount())) {

                    returnValue = getValueAt(0, column).getClass();
                }
                else {

                    returnValue = Object.class;
                }

                return returnValue;
            }
        };

        RowSorter<TableModel> sorter = new TableRowSorter<TableModel>(model);
        
        inventoryTable = new JTable(model) {

            public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {

                Component c = super.prepareRenderer(renderer, row, column);

                // We want renderer component to be
                // transparent so background image is visible
                if(c instanceof JComponent) {

                    ((JComponent)c).setOpaque(false);
                }

                return c;
            }

            public void paint( Graphics g ) {

                // tile the background image
                Dimension d = getSize();

                for( int x = 0; x < d.width; x += tableBackground.getIconWidth()) {

                    for( int y = 0; y < d.height; y += tableBackground.getIconHeight()) {

                        g.drawImage( tableBackground.getImage(), x, y, null, null );
                    }

                    // Now let the paint do its usual work
                    super.paint(g);
                }
            }
        };
        inventoryTable.setOpaque(false);
        inventoryTable.setRowSorter(sorter);


        scroll = new JScrollPane(inventoryTable);
        scroll.setBounds(0, 300, 1395, 444);

        inventoryPanel.setLayout(null);
        inventoryPanel.add(scroll);

        frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(inventoryPanel);
        frame.setSize(660, 398);
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);
        frame.setVisible(true);
    }
}


Take Note Of This Code, this is one of the complex or difficult things that you might encounter when you are dealing with JTable , searching and highlighting the selected cell(the searched cell/row)

JTable: Searching and Highlighting
Java Code
public class JTableSearchAndHighlight extends JFrame {

    private JTextField searchField;
    private JTable table;
    private JPanel panel;
    private JScrollPane scroll;

    public JTableSearchAndHighlight() {

        initializeInventory();
    }

    private void initializeInventory() {

        panel = new JPanel();

        searchField = new JTextField();

        panel.setLayout(null);

        final String[] columnNames = {"Name", "Surname", "Age"};

        final Object[][] data = {{"Jhon", "Java", "23"}, {"Stupid", "Stupido", "500"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Max", "Dumbass", "10"}, {"Melanie", "Martin", "500"},
                                {"Jollibe", "Mcdonalds", "15"}};

        table = new JTable(data, columnNames);
        table.setColumnSelectionAllowed(true);
        table.setRowSelectionAllowed(true);

        scroll = new JScrollPane(table);
        scroll.setBounds(0, 200, 900, 150);

        searchField.setBounds(10, 100, 150, 20);
        searchField.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {

                String value = searchField.getText();

                for (int row = 0; row <= table.getRowCount() - 1; row++) {

                    for (int col = 0; col <= table.getColumnCount() - 1; col++) {

                        if (value.equals(table.getValueAt(row, col))) {

                            // this will automatically set the view of the scroll in the location of the value
                            table.scrollRectToVisible(table.getCellRect(row, 0, true));
                        
                            // this will automatically set the focus of the searched/selected row/value
                            table.setRowSelectionInterval(row, row);

                            for (int i = 0; i <= table.getColumnCount() - 1; i++) {

                                table.getColumnModel().getColumn(i).setCellRenderer(new HighlightRenderer());
                            }
                        }
                    }
                }
            }
        });

        panel.add(searchField);
        panel.add(scroll);

        getContentPane().add(panel);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("Inventory Window");
        setSize(900, 400);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    private class HighlightRenderer extends DefaultTableCellRenderer {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

            // everything as usual
            super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

            // added behavior
            if(row == table.getSelectedRow()) {

                // this will customize that kind of border that will be use to highlight a row
                setBorder(BorderFactory.createMatteBorder(2, 1, 2, 1, Color.BLACK));
            }

            return this;
        }
    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new JTableSearchAndHighlight();
            }
        });
    }
}
update 1
JTable: Row Headers 1
Java Code
public class JTableRowHeaders1 extends JFrame {

    private JTable table;
    private JPanel panel;
    private JScrollPane scroll;
    private JList rowHeaders;

    public JTableRowHeaders1() {

        initializeInventory();
    }

    private void initializeInventory() {

        panel = new JPanel();

        panel.setLayout(new GridLayout(1,0));

        final String[] columnNames = {"Name", "Surname", "Age"};

        final Object[][] data = {{"Jhon", "Java", "23"}, {"Stupid", "Stupido", "500"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
                                {"Max", "Dumbass", "10"}, {"Melanie", "Martin", "500"},
                                {"Jollibe", "Mcdonalds", "15"}};

        table = new JTable(data, columnNames);


        Integer[] rowData = new Integer[data.length];

        for (int x = 0; x <= rowData.length - 1; x++) {

            rowData[x] = x + 1;
        }

        rowHeaders = new JList (rowData);
        rowHeaders.setFixedCellWidth(50);
        rowHeaders.setCellRenderer(new RowHeaderRenderer(table));
        
        scroll = new JScrollPane(table);
        scroll.setBounds(0, 100, 900, 500);
        scroll.setRowHeaderView(rowHeaders);

        panel.add(scroll);

        getContentPane().add(panel);

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(900, 700);
        setLocationRelativeTo(null);
        setVisible(true);
    }

   // class use for rendering the properties of the row headers
    private class RowHeaderRenderer extends JLabel implements ListCellRenderer {

        RowHeaderRenderer(JTable table) {

            setOpaque(true);
            setBorder(UIManager.getBorder("TableHeader.cellBorder"));
            setHorizontalAlignment(CENTER);
            setForeground(new Color(100, 100, 100));
            setFont(new Font("Monospaced", Font.BOLD, 11));
    	}

        public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {

            setText((value == null) ? "" : value.toString());
            return this;
        }
    }
    
    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            public void run() {

                new JTableRowHeaders1();
            }
        });
    }
}
update 2
JTable: Row Headers 2
Java Code
public class JTableRowHeaders2 extends JFrame {

     private JTable mainTable;
     private JScrollPane scroll ;
     private JViewport jv;
     private JTable rowHeaderTableColumn;
     private JPanel panel;

     private TableModel tableModel;
     private DefaultTableModel mainTableModel;

     private Integer[] rowHeaderData;

     public JTableRowHeaders2() {

         initComponents();
     }

     private void initComponents() {

         panel = new JPanel();
         tableModel = new AbstractTableModel() {

             String[] header = {"Rows"};

             public int getColumnCount() {

                 return 1;
             }

             public int getRowCount() {

                 return mainTable.getRowCount();
             }

             public String getColumnName(int col) {

                 // this will set the row headers column name
                 return header[0];
             }

             public Object getValueAt(int row, int col) {

                 // this will set the row headers row data
                 // instead of this;
                 // "return rowHeaderData[col] + row;"
                 // this one will generate its own count for each row' cell count
                 return 1 + row;
             }
         };

         TableColumnModel rowHeaderModel = new DefaultTableColumnModel() {

             boolean first = true;

             public void addColumn(TableColumn tableColumn) {

                 if (first) {

                     tableColumn.setMaxWidth(tableColumn.getPreferredWidth());

                     super.addColumn(tableColumn);
                     tableColumn.setMaxWidth(100);
                     first = false;
                 }
             }
         };

         String[] columns = {"Item Code", "Item Desciption", "Item Quantity", "Item Cost",
                                 "Cost Extension", "Retail", "Retail Extension", "Expiration Code"};

         Object[][] rows = new Object[200][columns.length];

         mainTableModel = new DefaultTableModel(rows, columns);

         mainTable = new JTable(mainTableModel);

         rowHeaderTableColumn = new JTable(tableModel, rowHeaderModel);

         rowHeaderTableColumn.createDefaultColumnsFromModel();
         rowHeaderTableColumn.setBackground(Color.lightGray);
         rowHeaderTableColumn.setColumnSelectionAllowed(false);
         rowHeaderTableColumn.setCellSelectionEnabled(false);

         jv = new JViewport();
         jv.setView(rowHeaderTableColumn);
         jv.setPreferredSize(rowHeaderTableColumn.getMaximumSize());

         mainTable.setSelectionModel(rowHeaderTableColumn.getSelectionModel());
         mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

         panel.setLayout(new GridLayout());

         rowHeaderData = new Integer[mainTable.getRowCount()];

         for (int count = 0; count <= mainTable.getRowCount() - 1; count++) {

             rowHeaderData[count] = count + 1;
         }

         scroll = new JScrollPane(mainTable);
         scroll.setRowHeader(jv);
         scroll.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, rowHeaderTableColumn.getTableHeader());
         panel.add(scroll);

         getContentPane().add(panel);

         setDefaultCloseOperation(EXIT_ON_CLOSE);
         setSize(500, 250);
         setLocationRelativeTo(null);
         setVisible(true);
     }

     public static void main(String args[]) {

         new JTableRowHeaders2();
     }
}
update 3;
JTable: synchronized row header and row when selecting and dragging
this is an example how to synchronize the row header with the row when a dragging event occurs
in a JScrollPane
Java Code
public class JTableRowHeadersAndRowsSynchronized extends JFrame {

     private JTable mainTable;
     private JScrollPane scroll ;
     private JViewport jv;
     private JTable rowHeaderTableColumn;
     private JPanel panel;

     private TableModel tableModel;
     private DefaultTableModel mainTableModel;

     private Integer[] rowHeaderData;

     public JTableRowHeadersAndRowsSynchronized() {

         initComponents();
     }

     private void initComponents() {

         panel = new JPanel();
         tableModel = new AbstractTableModel() {

             String[] header = {"Rows"};

             public int getColumnCount() {

                 return 1;
             }

             public int getRowCount() {

                 return mainTable.getRowCount();
             }

             public String getColumnName(int col) {

                 // this will set the row headers column name
                 return header[0];
             }

             public Object getValueAt(int row, int col) {

                 // this will set the row headers row data
                 // instead of this;
                 // "return rowHeaderData[col] + row;"
                 // this one will generate its own count for each row' cell count
                 return 1 + row;
             }
         };

         TableColumnModel rowHeaderModel = new DefaultTableColumnModel() {

             boolean first = true;

             public void addColumn(TableColumn tableColumn) {

                 if (first) {

                     tableColumn.setMaxWidth(tableColumn.getPreferredWidth());

                     super.addColumn(tableColumn);
                     tableColumn.setMaxWidth(100);
                     first = false;
                 }
             }
         };

         String[] columns = {"Item Code", "Item Desciption", "Item Quantity", "Item Cost",
                                 "Cost Extension", "Retail", "Retail Extension", "Expiration Code"};

         Object[][] rows = new Object[200][columns.length];

         mainTableModel = new DefaultTableModel(rows, columns);

         mainTable = new JTable(mainTableModel);

         rowHeaderTableColumn = new JTable(tableModel, rowHeaderModel);

         rowHeaderTableColumn.createDefaultColumnsFromModel();
         rowHeaderTableColumn.setBackground(Color.lightGray);
         rowHeaderTableColumn.setColumnSelectionAllowed(false);
         rowHeaderTableColumn.setCellSelectionEnabled(false);

         jv = new JViewport();
         jv.setView(rowHeaderTableColumn);
         jv.setPreferredSize(rowHeaderTableColumn.getMaximumSize());
         jv.addChangeListener(new RowHeaderAndRowTableSynchronizerChangeListener());
         
         mainTable.setSelectionModel(rowHeaderTableColumn.getSelectionModel());
         mainTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

         panel.setLayout(new GridLayout());

         rowHeaderData = new Integer[mainTable.getRowCount()];

         for (int count = 0; count <= mainTable.getRowCount() - 1; count++) {

             rowHeaderData[count] = count + 1;
         }

         scroll = new JScrollPane(mainTable);
         scroll.setRowHeader(jv);
         scroll.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, rowHeaderTableColumn.getTableHeader());
         panel.add(scroll);

         getContentPane().add(panel);

         setDefaultCloseOperation(EXIT_ON_CLOSE);
         setSize(500, 250);
         setLocationRelativeTo(null);
         setVisible(true);
     }

     // this listener will make the mouseDragged selection event in the rowHeader
     // synchronized with the inventoryTable's rows
     private class RowHeaderAndRowTableSynchronizerChangeListener implements ChangeListener {

         public void stateChanged(ChangeEvent e) {

             //  Keep the scrolling of the row table in sync with main table
             JViewport viewport = (JViewport) e.getSource();
             JScrollPane scrollPane = (JScrollPane)viewport.getParent();

             scrollPane.getVerticalScrollBar().setValue(viewport.getViewPosition().y);
         }
     }

     public static void main(String args[]) {

         new JTableRowHeadersAndRowsSynchronized();
     }
}
Please if theres any wrong with my codes, let me know, anyone is free to post a comment, so the pro's could help us from any mistakes, thank you




Last edited by chronoz13; 22-02-2010 at 07:20 AM.
Reply With Quote Share this thread on Facebook
Sponsored Links
Java Training from DevelopIntelligence
  #2 (permalink)  
Old 22-02-2010, 07:16 AM
chronoz13's Avatar
Java kindergarten
 

Join Date: Mar 2009
Location: Squatters Mansion
Posts: 405
Thanks: 113
Thanked 21 Times in 21 Posts
chronoz13 is on a distinguished road

I'm feeling Stressed
Default Re: JTable simple Solutions

I just want to inform viewers and forums mates, I added another three samples here. update #
--Edited Thread--

Last edited by chronoz13; 22-02-2010 at 07:21 AM.
Reply With Quote
The Following User Says Thank You to chronoz13 For This Useful Post:
JavaPF (24-02-2010)
  #3 (permalink)  
Old 24-02-2010, 01:14 PM
JavaPF's Avatar
mmm.. coffee
 
8 Highscores

Join Date: May 2008
Location: United Kingdom
Posts: 1,543
Thanks: 98
Thanked 92 Times in 85 Posts
JavaPF is someone you want to know!JavaPF is someone you want to know!JavaPF is someone you want to know!

I'm feeling Relaxed
Default Re: JTable simple Solutions

Good work chronoz13. Thank you for your contributions.
__________________
Don't forget to add syntax highlighted code tags around your code: [highlight=Java] code here [/highlight]

Forum Tip: Add to peoples reputation () by clicking the button on their useful posts.
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On



Similar Threads
Thread Thread Starter Forum Replies Last Post
JTable in JScrollPane alwayslearner File I/O & Other I/O Streams 0 29-01-2010 03:42 PM
not so simple, simple swing question box wolfgar AWT / Java Swing 2 20-11-2009 07:47 AM
How to printing a Jtable hundu AWT / Java Swing 0 29-06-2009 01:15 PM
How to printing a Jtable hundu AWT / Java Swing 0 29-06-2009 11:57 AM
How to printing a Jtable hundu AWT / Java Swing 3 28-06-2009 06:50 PM


100 most searched terms
Search Cloud
2 dimensional arraylist java 2d arraylist java actionlistener actionlistener in java addactionlistener addactionlistener java convert double to integer java double format java double to integer in java double to integer java drag en drop programmeren java eclipse shortcut keys exception in thread "awt-eventqueue-0" java.lang.outofmemoryerror: java heap space exception in thread "main" java.lang.nullpointerexception exception in thread "main" java.lang.outofmemoryerror: java heap space format double in java format double java get mouse position java java 2d arraylist java actionlistener java double format java double formatting java double to int java double to integer java format double java forum java forums java get mouse position java list to map java mouse position java programming forum java programming forums java programming practice problems java send keystrokes to another application java two dimensional arraylist java.io.ioexception: premature eof java.lang.classformaterror: truncated class file java.lang.outofmemoryerror: java heap space java.util.arraylist jbutton action jbutton actionlistener jtextarea font jtextfield font size jxl.read.biff.biffexception: unable to recognize ole stream programming mutators and generics smack api two dimensional arraylist two dimensional arraylist java unable to sendviapost to url what is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

All times are GMT. The time now is 02:06 AM.
Powered by vBulletin® Copyright ©2000-2009, Jelsoft Enterprises Ltd.