Results 1 to 7 of 7
Like Tree1Likes
  • 1 Post By doWhile

Thread: Adding model to JTable - NullPointerException thrown

  1. #1
    Zyril is offline Senior Member
    Join Date
    Oct 2011
    Location
    Sweden
    Posts
    124
    Rep Power
    0

    Default [SOLVED] Adding model to JTable - NullPointerException thrown

    SOLUTION:
    I just solved the problem, it's a really silly one. The table never gets initialized.
    Following code solves it completely.
    Java Code:
            table = new JTable(model);
    Original post below for interested people!

    Hello all!

    I'm having some trouble with a GUI I'm coding right now. Not the best way to have fun, but it has to be done.
    I'm adding a DefaultTableModel to a JTable object, but I keep getting a NullPointerException thrown. I've tried debugging, but I can't really figure out what the Unknown Source indicates.

    The troublesome code is in the very end of the file.

    EDIT:
    Alright, I've shortened down the code so it's more easy to run! I'm sorry for pasting all of it and just waiting for answers, I was in a hurry and wanted to get it posted. Next time I'll know it's better to do it correctly from the start!

    1) Why does your class extend JFrame? (misuse of inheritance: favor composition.)
    2) Why is menuBar static? (it shouldn't be)
    3) Why all the setPreferredSize(...) calls? (use layout managers correctly and they are not needed. Moreover, setting the preferred size to something that looks right on your computer can mess up royally when the code is run on another system.)
    4) Removed inane comments before posting on a forum. Your comments make the code more, not less, difficult to follow.
    1. I created a visual class in Eclipse named AddressBookGUI. It works as my mainframe, therefor it extends JFrame. Why is that less desirable than creating a class, and then a JFrame within it?

    2. True, I don't know why it is. Might be the result of a copy/paste, though that means there is another file in another project with the same mistake.

    3. I'm using FlowLayout where the buttons are used, where most of the setPreferredSize are. I want them to be of the same size and I don't know how a layoutmanager can do that for me. I've read about them and I am using different layoutmanagers for the panels.

    4. Comments removed.

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.border.EmptyBorder;
    import javax.swing.table.DefaultTableModel;
     
    public class AddressBookGUI extends JFrame {
    
        private JPanel contentPane;
        private JPanel panelTable;
        private JPanel panelLeft;
         
        private JScrollPane tableContainer;
        private JTable table;
        private DefaultTableModel model;
         
     
        private JMenuBar menuBar;
        private JMenu fileMenu;
        private JMenuItem openMenu;
        private JMenuItem exitMenu;
         
        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                            if ("Nimbus".equals(info.getName())) {
                                UIManager.setLookAndFeel(info.getClassName());
                                break;
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        AddressBookGUI frame = new AddressBookGUI();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
     
        /**
         * Create the frame.
         */
        @SuppressWarnings("serial")
        public AddressBookGUI() {
            setTitle("Address Book");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 600, 530);
            contentPane = new JPanel();
            contentPane.setBackground(Color.WHITE);
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new BorderLayout(0, 0));
            setContentPane(contentPane);
            
    
            panelLeft = new JPanel();   
            panelLeft.setBackground(Color.WHITE);
            contentPane.add(panelLeft, BorderLayout.WEST);
            panelLeft.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            panelLeft.setPreferredSize(new Dimension(150,0));
            panelLeft.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
             
    
            panelTable = new JPanel();
            contentPane.add(panelTable, BorderLayout.EAST);
            tableContainer = new JScrollPane(table);
            panelTable.add(tableContainer);
            panelTable.setBorder(BorderFactory.createLineBorder(Color.BLACK));
            panelTable.setPreferredSize(new Dimension(420,0));
     
    
            model = new DefaultTableModel(){
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            };
    //      model = new DefaultTableModel();
            model.setColumnIdentifiers(new String[] {"Förnamn", "Efternamn", "Telefonnummer"});
            table.setModel(model);
        }
    }
    Am I messing things up with my different JPanels, perhaps missing a step somewhere that makes it impossible for the table to find the model?

    I also tried to declare the model differently:

    Java Code:
            DefaultTableModel model = new DefaultTableModel(){
            	public boolean isCellEditable(int row, int column) {
                    return false;
            	}
            };
    //		model = new DefaultTableModel();
            model.setColumnIdentifiers(new String[] {"Förnamn", "Efternamn", "Telefonnummer"});
            table.setModel(model);

    This is the stacktrace:
    Java Code:
    java.lang.NullPointerException
    	at AddressBookGUI.<init>(AddressBookGUI.java:87)
    	at AddressBookGUI$1.run(AddressBookGUI.java:40)
    	at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.awt.EventQueue$1.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)
    Last edited by Zyril; 09-18-2012 at 07:44 PM.

  2. #2
    JavaAdviser is offline Member
    Join Date
    Sep 2012
    Posts
    26
    Rep Power
    0

    Default Re: Adding model to JTable - NullPointerException thrown

    Could you maybe please post the stacktrace as well?
    Last edited by JavaAdviser; 09-18-2012 at 05:17 PM.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,189
    Rep Power
    19

    Default Re: Adding model to JTable - NullPointerException thrown

    To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem. Not code that has dependencies that aren't available to members who might like to try to help.

    Other notes:
    1) Why does your class extend JFrame? (misuse of inheritance: favor composition.)
    2) Why is menuBar static? (it shouldn't be)
    3) Why all the setPreferredSize(...) calls? (use layout managers correctly and they are not needed. Moreover, setting the preferred size to something that looks right on your computer can mess up royally when the code is run on another system.)
    4) Removed inane comments before posting on a forum. Your comments make the code more, not less, difficult to follow.

    Adn JavaAdvisor is right, without compilable code and/or a stack trace, we would be just guessing at possible causes. Probably wouldn't help to do that.

    db
    Last edited by DarrylBurke; 09-18-2012 at 05:31 PM.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  4. #4
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    6

    Default Re: Adding model to JTable - NullPointerException thrown

    Posting the stack trace will help. I would start by reading that, figuring out which line in your code the exception is thrown, then add some println's to determine which object is null. You posted a bit of code to wade through (an SSCCE does a world of good in you getting help), but the first variable I would look at is 'table' - where is it instantiated?

  5. #5
    Zyril is offline Senior Member
    Join Date
    Oct 2011
    Location
    Sweden
    Posts
    124
    Rep Power
    0

    Default Re: Adding model to JTable - NullPointerException thrown

    Updated the original thread starting post!
    Sorry for the rushed post earlier, I should have prepared it better to be expect answers!

    I also included the stacktrace in the end. I put breakpoints on line 87 and 40, and the exception is thrown on line 87. Unknown source? What is the source it is looking for, is it the object called model or something else?

    Cheers,
    Z!

  6. #6
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    6

    Default Re: Adding model to JTable - NullPointerException thrown

    What is null on line 87? Hint: read post #4.
    Zyril likes this.

  7. #7
    Zyril is offline Senior Member
    Join Date
    Oct 2011
    Location
    Sweden
    Posts
    124
    Rep Power
    0

    Default Re: Adding model to JTable - NullPointerException thrown

    Oh, yes I never saw that you posted that. My mistake again. Oh, I have to be more grateful for the help and read everything more carefully!

Similar Threads

  1. Replies: 7
    Last Post: 12-03-2011, 04:25 AM
  2. Returning a ResultSet to custom JTable Model
    By Kenjitsuka in forum New To Java
    Replies: 9
    Last Post: 10-16-2010, 09:17 PM
  3. JTable view/model sync problem
    By edcincy in forum AWT / Swing
    Replies: 0
    Last Post: 09-12-2008, 06:25 PM
  4. Replies: 0
    Last Post: 08-29-2008, 12:49 PM
  5. Replies: 0
    Last Post: 08-29-2008, 12:16 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
  •