Results 1 to 7 of 7
  1. #1
    bigj is offline Member
    Join Date
    Dec 2009
    Posts
    68
    Rep Power
    0

    Default confusing output of a selected cell in a JTable

    Java Code:
    public class InventoryDatabase extends JFrame {
    
        private JTable inventoryTable;
    
        private JTableHeader header;
        
        private JPanel inventoryPanel;
        
        private JScrollPane scroll;
        
        private JMenuBar menuBar;
    
        private JMenu file;
        private JMenu option;
    
        private JMenuItem openSingleItemEntry;
        private JMenuItem exitWindow;
    
        private JMenuItem helpWindow;
        private JMenuItem aboutWindow;
    
        private Font labelFont;
        private Font buttonFont;
        private Font menuItemFont;
        private Font menuFont;
    
        private Image icon;
    
        private ImageIcon tableBackground;
        private ImageIcon upperPanelBackground;
        
        private boolean isTableCellsEditable;
        
        public InventoryDatabase() {
            
            initializeInventory();
            ((DefaultCellEditor)inventoryTable.getDefaultEditor(new Object().getClass())).setClickCountToStart(1);
        }
    
        private void initializeInventory() {
    
            isTableCellsEditable = false;
            
            icon = new ImageIcon("c:/pics/mercuryLogo.jpg").getImage().getScaledInstance(300, 300, 0);
            tableBackground = new ImageIcon("c:/pics/inventorytablebck.jpg");
            upperPanelBackground = new ImageIcon("c:/pics/upperPanelBck.jpg");
            
            menuBar = new JMenuBar();
            
            file = new JMenu("File");
            option = new JMenu("Option");
            
            openSingleItemEntry = new JMenuItem("Open Single Item Entry Window");
            exitWindow = new JMenuItem("Exit");
            helpWindow = new JMenuItem("Help");
            aboutWindow = new JMenuItem("About");
    
            labelFont = new Font("Monospaced", Font.BOLD, 15);
            buttonFont = new Font("Monospaced", Font.BOLD, 11);
            menuItemFont = new Font("Monospaced", Font.BOLD, 13);
            menuFont = new Font("Monospaced", Font.BOLD, 14);        
    
            inventoryPanel = new JPanel() {
    
                @Override
                protected void paintComponent(Graphics g) {
    
                    // Scale image to size of component
                    Dimension d = getSize();
    
                    g.drawImage(upperPanelBackground.getImage(), 0, 0, d.width, d.height, null);
    
                    super.paintComponent(g);
                }
            };
            inventoryPanel.setOpaque(false);
    
            // set this panel's layout for manual positioning of components
            inventoryPanel.setLayout(null);
            
            // header titles for the table columns
            final String[] columnNames = {"Item Code", "Item Quantity", "Item Desciption", "Item Cost",
                                          "Cost Extension", "Retail", "Retail Extension", "Expiration Code"};
            
            final Object[][] data =  new Object[100][columnNames.length];
    
            // set the properties and actions of this menu item
            openSingleItemEntry.setFont(menuItemFont);
            openSingleItemEntry.setMnemonic(KeyEvent.VK_O);
            openSingleItemEntry.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent aE) {
    
                  //  setVisible(false);
                //    InventorySingleEntryWindow.showSingleEntryInventoryWindow();
                }
            });
    
            // set the properties and actions of this menu item
            exitWindow.setFont(menuItemFont);
            exitWindow.setMnemonic(KeyEvent.VK_X);
            exitWindow.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent aE) {
    
                    dispose();
                }
            });
    
            // set the properties and actions of this menu item
            helpWindow.setFont(menuItemFont);
            helpWindow.setMnemonic(KeyEvent.VK_H);
            helpWindow.addActionListener(new ActionListener() {
    
                public void actionPerformed(ActionEvent aE) {
    
                //    new HelpWindow();
                }
            });
            // add the corresponding menu items in this menu and set its properties
            file.add(openSingleItemEntry);
            file.add(exitWindow);
            file.setFont(menuFont);
            file.setMnemonic(KeyEvent.VK_F);
    
            // set the properties and actions of this menu item
            aboutWindow.setFont(menuItemFont);
            aboutWindow.setMnemonic(KeyEvent.VK_A);
            
            // add the corresponding menu items in this menu and set its properties
            option.add(helpWindow);
            option.add(aboutWindow);
            option.setFont(menuFont);
            option.setMnemonic(KeyEvent.VK_O);
    
            // add the menus in the menu bar
            menuBar.add(file);
            menuBar.add(option);
            
            inventoryTable = new JTable(data, columnNames);
            inventoryTable.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
    
                public void valueChanged(ListSelectionEvent e) {
    
                    int rowIndex = inventoryTable.getSelectedRow();
    
                    inventoryTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    
                    System.out.println(rowIndex);
           
                }
            });
            inventoryTable.setOpaque(false);
            inventoryTable.setGridColor(Color.BLACK);
            inventoryTable.setFont(new Font("Arial", Font.BOLD, 11));
            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);
            inventoryTable.getColumnModel().getColumn(3).setPreferredWidth(140);
            inventoryTable.getColumnModel().getColumn(4).setPreferredWidth(140);
            inventoryTable.getColumnModel().getColumn(5).setPreferredWidth(140);
            inventoryTable.getColumnModel().getColumn(6).setPreferredWidth(150);
            inventoryTable.getColumnModel().getColumn(7).setPreferredWidth(160);
            
            // create the scroll as the inventoryTable's scroll
            scroll = new JScrollPane(inventoryTable);
    
            scroll.setBounds(0, 300, 1395, 444);
    
            JSplitPane sP = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    
            inventoryPanel.add(scroll);
            
    
            getContentPane().add(inventoryPanel);
    
            // set the properties of this JFrame window
            setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
            setDefaultLookAndFeelDecorated(true);
            setTitle("  Inventory Window");
            setJMenuBar(menuBar);
            setIconImage(icon);
            setSize(1400, 800);
            setLocationRelativeTo(null);
            setResizable(false);
            setVisible(true);
        }
        
        public static void main(String[] args) {
    
            SwingUtilities.invokeLater(new Runnable() {
                
                public void run() {
    
                    new InventoryDatabase();           
                }
            });
        }
    }
    I'm trying to make a part of this program that will display the selected row in a selected column, I have started first with displaying the selected row but im getting a negative value

    Every time I click a cell the output is this
    Java Code:
    // first click
    -1
    -1
    0
    
    // second click
    -1
    -1
    1
    
    // third click
    -1
    -1
    2
    
    // fourth click
    -1
    -1
    3
    how am i suppose to resolve this.. I'm confused with the methods that i should implement to make the correct output.

    What I want to display is this,

    Java Code:
    Row Is : <Selected row>
    Column Is: <Selected Column>
    I am not yet implementing how to display the column , I have to deal first with displaying the selected row properly, please I need Help

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Suggestion number one: simplify your code a lot. Try to solve this issue in a small program that has a very simple JTable and very simple GUI. This way you can isolate the issue and more readily figure out what the problems may be. Then if it doesn't work, you can post a program that represents a more reasonable amount of code to ask someone else to review.

    Much luck.

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    OK, I'm not at work today and had extra time, and so I did the simplification work for you. Below is your program with all the extra crap, the stuff preventing you and us from seeing the true problem, removed:
    Java Code:
    import javax.swing.*;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.event.ListSelectionListener;
    
    @SuppressWarnings("serial")
    public class InventoryDatabase extends JFrame {
    
      private JTable inventoryTable;
      private JPanel inventoryPanel;
      private JScrollPane scroll;
    
      public InventoryDatabase() {
        initializeInventory();
      }
    
      private void initializeInventory() {
    
        inventoryPanel = new JPanel();
        inventoryPanel.setOpaque(false);
    
        final String[] columnNames = {"Item Code", "Item Quantity",
          "Item Desciption"};
    
        final Object[][] data = new Object[20][columnNames.length];
    
        inventoryTable = new JTable(data, columnNames);
        inventoryTable.getColumnModel().getSelectionModel().addListSelectionListener(new ListSelectionListener() {
              public void valueChanged(ListSelectionEvent e) {
                int rowIndex = inventoryTable.getSelectedRow();
                inventoryTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                System.out.println("row index: " + rowIndex);
              }
            });
        scroll = new JScrollPane(inventoryTable);
        inventoryPanel.add(scroll);
        getContentPane().add(inventoryPanel);
    
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Inventory Window");
        pack();
        setLocationRelativeTo(null);
        setVisible(true);
      }
    
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            new InventoryDatabase();
          }
        });
      }
    }
    Notice anything unusual about the simplified code? Two things jump out at me:

    1) You're adding your list selection listener to the column models selection model and then trying to get row information from it. It is my understanding that the column model's selection model should trigger changes in column selections, not row selections, and so this set up looks a bit funny.

    2) You're changing the inventory table's selection mode from within your listener. I have no idea what side effects this can cause, but have a feeling that it will bring nothing good.

    Suggestions:
    1) add your listener to a different delection model, perhaps the table's selection model.

    2) Set the inventory table's selection mode once and outside of your listeners (unless you have a compelling reason to do otherwise).

    3) Try to simplify your problems as much as possible to help you solve them, and failing that, to help us solve them.

    an example of a different listener:
    Java Code:
        //!! added
        inventoryTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        inventoryTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
          
          public void valueChanged(ListSelectionEvent e) {
            if (!e.getValueIsAdjusting()) {
              int rowIndex = inventoryTable.getSelectedRow();
              int colIndex = inventoryTable.getSelectedColumn();
              System.out.println("Selection [row, column]: [" + rowIndex + ", " + colIndex + "]");
            }
          }
        });

  4. #4
    bigj is offline Member
    Join Date
    Dec 2009
    Posts
    68
    Rep Power
    0

    Default

    thank you for spending a little of your time correcting my mistakes and debugging the error. I'll try to do the best I can regarding with posting codes next time again..

    anyway sir.. it gives me the correct output, the rows and cols, but another problem came in. The first click of a cell displays a correct output, but clicking different row in the same column doesnt generate the output

    Example:

    Clicking the first row in the first column displays the output
    Java Code:
    Selection [row, column]: [0, 0]
    But clicking the second row or next rows on the same column doesnt display the output

    I tried to search at google, but I ended up the same results.
    Last edited by bigj; 01-30-2010 at 02:08 PM.

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by bigj View Post
    thank you for spending a little of your time correcting my mistakes and debugging the error. I'll try to do the best I can regarding with posting codes next time again..

    anyway sir.. it gives me the correct output, the rows and cols, but another problem came in. The first click of a cell displays a correct output, but clicking different row in the same column doesnt generate the output

    Example:

    Clicking the first row in the first column displays the output
    Java Code:
    Selection [row, column]: [0, 0]
    But clicking the second row or next rows on the same column doesnt display the output

    I tried to search at google, but I ended up the same results.
    Perhaps you meant clicking on a different column.

    Please have a look at the JTable API to see how to watch for column selections and row selections. For the former, you could use the column model's list selection model as you do in your code above, for the latter you would use the table's list selection model as I do. In fact you could use both together in one program.

    I suggest that you create a simple program similar to the one I've posted above and just play with this idea, trying different variations. It's this experiment and creating that makes programming exciting and fun.

    Much luck!

  6. #6
    bigj is offline Member
    Join Date
    Dec 2009
    Posts
    68
    Rep Power
    0

    Default

    thank you sir. :)

  7. #7
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default

    Quote Originally Posted by bigj View Post
    thank you sir. :)
    You are most welcome. :)

Similar Threads

  1. JTable Cell Merg
    By anilkumar_vist in forum AWT / Swing
    Replies: 8
    Last Post: 04-25-2011, 09:32 AM
  2. JTable Gridline in selected row
    By arubin in forum AWT / Swing
    Replies: 11
    Last Post: 11-24-2009, 07:05 PM
  3. Jtable and cell coordinates
    By rattaman in forum AWT / Swing
    Replies: 2
    Last Post: 11-17-2009, 05:48 PM
  4. add a check box to only one cell in a JTable
    By aruna1 in forum New To Java
    Replies: 4
    Last Post: 04-03-2009, 06:28 PM
  5. JTable problem with getting ROW selected
    By nadia in forum Advanced Java
    Replies: 2
    Last Post: 01-13-2009, 05:57 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •