Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: JTable simple Solutions

  1. #1
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    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
    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
    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
    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
    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
    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
    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
    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
    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
    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
    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; February 22nd, 2010 at 03:20 AM.


  2. #2
    Java kindergarten chronoz13's Avatar
    Join Date
    Mar 2009
    Location
    Philippines
    Posts
    659
    Thanks
    177
    Thanked 30 Times in 28 Posts

    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; February 22nd, 2010 at 03:21 AM.

  3. The Following User Says Thank You to chronoz13 For This Useful Post:

    JavaPF (February 24th, 2010)

  4. #3
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: JTable simple Solutions

    Good work chronoz13. Thank you for your contributions.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  5. #4
    Junior Member
    Join Date
    Oct 2012
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: JTable simple Solutions

    It's very good, thanks!
    How to made something like this?
    TableHeader.jpg
    sorry for my bad english )

Similar Threads

  1. JTable in JScrollPane
    By alwayslearner in forum File I/O & Other I/O Streams
    Replies: 0
    Last Post: January 29th, 2010, 11:42 AM
  2. not so simple, simple swing question box
    By wolfgar in forum AWT / Java Swing
    Replies: 2
    Last Post: November 20th, 2009, 03:47 AM
  3. Printing a JTable
    By hundu in forum AWT / Java Swing
    Replies: 0
    Last Post: June 29th, 2009, 08:15 AM
  4. How to printing a Jtable
    By hundu in forum AWT / Java Swing
    Replies: 0
    Last Post: June 29th, 2009, 06:57 AM
  5. Printing JTable that retrieve data from the Database
    By hundu in forum AWT / Java Swing
    Replies: 3
    Last Post: June 28th, 2009, 01:50 PM