Skip to main content

Selection on JTable

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
No replies
CookieBrowser
Offline
Joined: 2012-12-01

I have a J Split Panel, with 2 J Tables, What i would like to do is when i click on an Item inside the JTable that
the Second J Table so automatic populate with the Person Information from a Different Table.

I am getting Errors on my Console when i Try and Click on an Item inside one of the Tables

<br />
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException<br />
	at DisplayQueryResults.isRecordSelected(DisplayQueryResults.java:300)<br />
	at DisplayQueryResults$3.valueChanged(DisplayQueryResults.java:230)<br />
	at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)<br />
	at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:164)<br />
	at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:211)<br />
	at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:405)<br />
	at javax.swing.DefaultListSelectionModel.changeSelection(DefaultListSelectionModel.java:415)<br />
	at javax.swing.DefaultListSelectionModel.setSelectionInterval(DefaultListSelectionModel.java:459)<br />
	at javax.swing.JTable.changeSelectionModel(JTable.java:2392)<br />
	at javax.swing.JTable.changeSelection(JTable.java:2461)<br />
	at javax.swing.plaf.basic.BasicTableUI$Handler.adjustSelection(BasicTableUI.java:1115)<br />
	at javax.swing.plaf.basic.BasicTableUI$Handler.mousePressed(BasicTableUI.java:1038)<br />
	at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mousePressed(BasicTableUI.java:798)<br />
	at java.awt.AWTEventMulticaster.mousePressed(AWTEventMulticaster.java:280)<br />
	at java.awt.Component.processMouseEvent(Component.java:6502)<br />
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)<br />
	at java.awt.Component.processEvent(Component.java:6270)<br />
	at java.awt.Container.processEvent(Container.java:2229)<br />
	at java.awt.Component.dispatchEventImpl(Component.java:4861)<br />
	at java.awt.Container.dispatchEventImpl(Container.java:2287)<br />
	at java.awt.Component.dispatchEvent(Component.java:4687)<br />
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)<br />
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4489)<br />
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)<br />
	at java.awt.Container.dispatchEventImpl(Container.java:2273)<br />
	at java.awt.Window.dispatchEventImpl(Window.java:2719)<br />
	at java.awt.Component.dispatchEvent(Component.java:4687)<br />
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)<br />
	at java.awt.EventQueue.access$200(EventQueue.java:103)<br />
	at java.awt.EventQueue$3.run(EventQueue.java:682)<br />
	at java.awt.EventQueue$3.run(EventQueue.java:680)<br />
	at java.security.AccessController.doPrivileged(Native Method)<br />
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)<br />
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)<br />
	at java.awt.EventQueue$4.run(EventQueue.java:696)<br />
	at java.awt.EventQueue$4.run(EventQueue.java:694)<br />
	at java.security.AccessController.doPrivileged(Native Method)<br />
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)<br />
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)<br />
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)<br />
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)<br />
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)<br />
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)<br />
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)<br />
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)<br />
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException<br />
	at DisplayQueryResults.isRecordSelected(DisplayQueryResults.java:300)<br />
	at DisplayQueryResults$3.valueChanged(DisplayQueryResults.java:230)<br />
	at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:184)<br />
	at javax.swing.DefaultListSelectionModel.fireValueChanged(DefaultListSelectionModel.java:154)<br />
	at javax.swing.DefaultListSelectionModel.setValueIsAdjusting(DefaultListSelectionModel.java:685)<br />
	at javax.swing.plaf.basic.BasicTableUI$Handler.setValueIsAdjusting(BasicTableUI.java:953)<br />
	at javax.swing.plaf.basic.BasicTableUI$Handler.mouseReleased(BasicTableUI.java:1166)<br />
	at javax.swing.plaf.basic.BasicTableUI$MouseInputHandler.mouseReleased(BasicTableUI.java:802)<br />
	at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:290)<br />
	at java.awt.Component.processMouseEvent(Component.java:6505)<br />
	at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)<br />
	at java.awt.Component.processEvent(Component.java:6270)<br />
	at java.awt.Container.processEvent(Container.java:2229)<br />
	at java.awt.Component.dispatchEventImpl(Component.java:4861)<br />
	at java.awt.Container.dispatchEventImpl(Container.java:2287)<br />
	at java.awt.Component.dispatchEvent(Component.java:4687)<br />
	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)<br />
	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)<br />
	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)<br />
	at java.awt.Container.dispatchEventImpl(Container.java:2273)<br />
	at java.awt.Window.dispatchEventImpl(Window.java:2719)<br />
	at java.awt.Component.dispatchEvent(Component.java:4687)<br />
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:723)<br />
	at java.awt.EventQueue.access$200(EventQueue.java:103)<br />
	at java.awt.EventQueue$3.run(EventQueue.java:682)<br />
	at java.awt.EventQueue$3.run(EventQueue.java:680)<br />
	at java.security.AccessController.doPrivileged(Native Method)<br />
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)<br />
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)<br />
	at java.awt.EventQueue$4.run(EventQueue.java:696)<br />
	at java.awt.EventQueue$4.run(EventQueue.java:694)<br />
	at java.security.AccessController.doPrivileged(Native Method)<br />
	at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)<br />
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:693)<br />
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)<br />
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)<br />
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)<br />
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)<br />
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)<br />
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)<br />

<br />
import java.awt.BorderLayout;<br />
import java.awt.Component;<br />
import java.awt.Dimension;<br />
import javax.swing.JFrame;<br />
import javax.swing.JPanel;<br />
import java.awt.event.ActionEvent;<br />
import java.awt.event.ActionListener;<br />
import java.awt.event.WindowAdapter;<br />
import java.awt.event.WindowEvent;<br />
import java.sql.SQLException;<br />
import javax.swing.JMenu;<br />
import javax.swing.JMenuBar;<br />
import javax.swing.JMenuItem;<br />
import javax.swing.JScrollPane;<br />
import javax.swing.JTable;<br />
import javax.swing.JOptionPane;<br />
import javax.swing.JLabel;<br />
import javax.swing.JTextField;<br />
import javax.swing.event.ListSelectionEvent;<br />
import javax.swing.event.ListSelectionListener;<br />
import javax.swing.table.TableRowSorter;<br />
import javax.swing.table.TableModel;<br />
import javax.swing.JSplitPane;<br />
import javax.swing.SwingConstants;<br />
import com.jgoodies.forms.layout.FormLayout;<br />
import com.jgoodies.forms.layout.ColumnSpec;<br />
import com.jgoodies.forms.layout.RowSpec;<br />
import com.jgoodies.forms.factories.FormFactory;</p>
<p>public class DisplayQueryResults extends JFrame<br />
{<br />
   // database Host Address, UserName and Password<br />
   static final String DATABASE_URL = "jdbc:mysql://localhost/Doctor";<br />
   static final String USERNAME = "dbuser";<br />
   static final String PASSWORD = "dbpassword";</p>
<p>   // default query retrieves all data from Patient table<br />
   static final String DEFAULT_QUERY = "SELECT * FROM Patient";<br />
// default query retrieves all data from History table<br />
   static final String DEFAULT_QUERY1 = "SELECT * FROM History";</p>
<p>   private ResultSetTableModel tableModel;<br />
   private ResultSetTableModel1 tableModel1;<br />
   private JTable resultTable;<br />
   private  JTable resultTable1;<br />
   private JMenuBar	   menuBar;<br />
   private JScrollPane scrollPane_1;</p>
<p>   // create ResultSetTableModel and GUI<br />
   public DisplayQueryResults()<br />
   {<br />
      super( " Doctors Records" );<br />
      BorderLayout borderLayout = (BorderLayout) getContentPane().getLayout();<br />
      borderLayout.setVgap(5);<br />
      borderLayout.setHgap(5);</p>
<p>      // create ResultSetTableModel and display database table<br />
      try<br />
      {<br />
         // create TableModel for results of query SELECT * FROM Patient<br />
         tableModel = new ResultSetTableModel( DATABASE_URL,<br />
            USERNAME, PASSWORD, DEFAULT_QUERY );</p>
<p>      // create TableModel1 for results of query SELECT * FROM Patient<br />
        tableModel1 = new ResultSetTableModel1( DATABASE_URL,<br />
                USERNAME, PASSWORD, DEFAULT_QUERY1 );</p>
<p>  //--------------------------------------------------------------------------------------------------------------------</p>
<p>        /**<br />
         * This Section is to Set up the Menu Bar at the Top of the Application<br />
         * and allowing Action Handlers to be added to the Menu Bar options<br />
         */</p>
<p>        JMenuBar menubar = new JMenuBar(); //Creating Menu Bar.<br />
        JMenu file = new JMenu("File");// Adding a File Menu<br />
        JMenuItem newItem = new JMenuItem("New");// Adding New Section to Menu<br />
        JMenuItem openItem = new JMenuItem("Open File");// Adding Open File Section to Menu<br />
        JMenuItem saveItem = new JMenuItem("Save");// Adding Save Section to Menu<br />
        JMenuItem printItem = new JMenuItem("Print");// Adding Print Section to Menu<br />
        JMenuItem exitItem = new JMenuItem("Exit");// Adding Exit Section to Menu<br />
        JMenu help = new JMenu("Help"); // Adding a Help Menu<br />
        JMenuItem aboutItem = new JMenuItem("About"); // Adding About Section to Menu</p>
<p>        /*<br />
         * Action Listener to Exit the Program<br />
         */<br />
       exitItem.addActionListener(new ActionListener() {<br />
        	public void actionPerformed(ActionEvent e)<br />
        	{<br />
        		System.exit(0); // Kill the Program if Exit is click on</p>
<p>        	}<br />
        });</p>
<p>        /*<br />
         * Action Listener to Have the About Page Show Up<br />
         */<br />
        aboutItem.addActionListener(new ActionListener() {<br />
        	public void actionPerformed(ActionEvent e)<br />
        	{<br />
        		About about= new About(); // Creating the About Page<br />
        		about.setSize(new Dimension(500,300)); //Setting Size for Dialog<br />
        		about.setLocation(300, 50); // Setting up the Startup Location<br />
        		 about.setVisible(true); // Setting Visible to True</p>
<p>        	}<br />
        });</p>
<p>      /*<br />
       * Adding the Menu Items to the<br />
       * Menu Bar.<br />
       */<br />
        setJMenuBar(menuBar);<br />
        file.add(newItem);<br />
        file.add(openItem);<br />
        file.add(saveItem);<br />
        file.add(printItem);<br />
        file.add(exitItem);<br />
        help.add(aboutItem);<br />
        menubar.add(file);<br />
        menubar.add(help);<br />
        setJMenuBar(menubar);</p>
<p>  //------------------------------------------------------------------------------------------------------------------		</p>
<p>        /**<br />
         * This Section is to Set Up a JSplit Pane, the First Section is set to  BorderLayout<br />
         * This JSplit Pane is Set to the Bottom of the Application.<br />
         *<br />
         * The Second Section of the JSplit Pane has its Layout Set up as FormLayout<br />
         * this Way the Labels and text Fields are in line.<br />
         */<br />
                  JSplitPane splitPane_1 = new JSplitPane(); // Creating JSplit Pane<br />
                  getContentPane().add(splitPane_1, BorderLayout.SOUTH); // Adding SplitPane_1 to the getContentPane.<br />
                  JPanel panel = new JPanel(); // Creating JPanel called Panel<br />
                  splitPane_1.setLeftComponent(panel); // Setting Panel to the Left hand Side of JSpilt Panel</p>
<p>                  /*<br />
                   * Setting the Layout for the FormLayout<br />
                   */<br />
                  panel.setLayout(new FormLayout(new ColumnSpec[] {<br />
                  		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("61px"),<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("66px"),<br />
                		FormFactory.RELATED_GAP_COLSPEC,<br />
                		FormFactory.DEFAULT_COLSPEC,<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("51px"),<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("3px"),<br />
                		FormFactory.RELATED_GAP_COLSPEC,<br />
                		FormFactory.DEFAULT_COLSPEC,<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("68px"),<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("49px"),<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("78px"),<br />
                		FormFactory.LABEL_COMPONENT_GAP_COLSPEC,<br />
                		ColumnSpec.decode("66px"),},<br />
                	new RowSpec[] {<br />
                		FormFactory.UNRELATED_GAP_ROWSPEC,<br />
                		RowSpec.decode("28px"),<br />
                		FormFactory.RELATED_GAP_ROWSPEC,<br />
                		FormFactory.DEFAULT_ROWSPEC,<br />
                		FormFactory.UNRELATED_GAP_ROWSPEC,<br />
                		RowSpec.decode("28px"),<br />
                		FormFactory.RELATED_GAP_ROWSPEC,<br />
                		FormFactory.DEFAULT_ROWSPEC,<br />
                		FormFactory.UNRELATED_GAP_ROWSPEC,<br />
                		RowSpec.decode("28px"),}));<br />
                JLabel lblPatientID = new JLabel("Patient ID"); //Set String to JLabel<br />
                panel.add(lblPatientID, "2, 2, 3, 1, left, center"); // Add Patient Label to Panel 2.<br />
                JTextField PatientID = new JTextField(); // Add PatientID Text Field<br />
                panel.add(PatientID, "6, 2, 9, 1, left, top"); // Add PatientID text field to Panel 2<br />
                PatientID.setColumns(10); // Set PatientID Columns Size to 10.<br />
                JLabel lblFirstName1 = new JLabel("First Name"); //Set String to JLabel<br />
                panel.add(lblFirstName1, "2, 4, 3, 1, left, center"); //Add First Name Label to Panel2<br />
                JTextField FirstName = new JTextField(); // Add First Name Text Field<br />
                panel.add(FirstName, "6, 4, 9, 1, left, top"); // Add First Name Text Field to Panel 2<br />
                FirstName.setColumns(10); // Set Columns Size to 10<br />
                Component lblLastName = new JLabel("Last Name");//Set String to JLabel<br />
                panel.add(lblLastName, "2, 6, 3, 1, left, center");// Add Last Name  Label to Panel 2.<br />
                JTextField LastName = new JTextField();// Add LasntName Text Field<br />
                panel.add(LastName, "6, 6, 9, 1, left, top");// Add LastName text field to Panel 2<br />
                LastName.setColumns(10);// Set Columns Size to 10<br />
                JLabel lblAddress = new JLabel("Address");//Set String to JLabel<br />
                panel.add(lblAddress, "2, 8, 3, 1, left, center");// Add Address Label to Panel 2.<br />
                JTextField Address = new JTextField();// Add Address Text Field<br />
                panel.add(Address, "6, 8, 9, 1, left, top");// Add Address text field to Panel 2<br />
                Address.setColumns(10);// Set Columns Size to 10<br />
                JLabel lblPhoneNumber = new JLabel("Phone Number");//Set String to JLabel<br />
                panel.add(lblPhoneNumber, "2, 10, 3, 1, left, center");// Add PhoneNumber Label to Panel 2.<br />
                JTextField PhoneNumber = new JTextField();// Add PhoneNumber Text Field<br />
                panel.add(PhoneNumber, "6, 10, 9, 1, left, top");// Add Phone Number text field to Panel 2<br />
                PhoneNumber.setColumns(10);// Set Columns Size to 10</p>
<p>                /*<br />
                 * Creating a New JPanel and Calling it panel_1<br />
                 * Setting the JPanel to the Right handSide<br />
                 * of the JSplit Panel_1.<br />
                 */<br />
                  JPanel panel_1 = new JPanel();<br />
                  splitPane_1.setRightComponent(panel_1);</p>
<p>  //---------------------------------------------------------------------------------------------------------------------------                </p>
<p>                  JSplitPane splitPane = new JSplitPane();<br />
                  splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);<br />
                  getContentPane().add(splitPane, BorderLayout.CENTER);</p>
<p>                  JScrollPane scrollPane = new JScrollPane();<br />
                  splitPane.setLeftComponent(scrollPane);</p>
<p>                  JTable resultTable = new JTable(tableModel);<br />
                  scrollPane.setViewportView(resultTable);<br />
                  resultTable.getSelectionModel().addListSelectionListener(<br />
                          new ListSelectionListener() {<br />
                              public void valueChanged(ListSelectionEvent e)<br />
                              {<br />
                            	  firePropertyChange("recordSelected", !isRecordSelected(), isRecordSelected());<br />
                                  JTable resultTable1 = new JTable(tableModel1);<br />
                                  scrollPane_1.setViewportView(resultTable1);</p>
<p>                              }<br />
                          });</p>
<p>                  JScrollPane scrollPane_1 = new JScrollPane();<br />
                  splitPane.setRightComponent(scrollPane_1);</p>
<p>                  JPanel panel1 = new JPanel();<br />
                  getContentPane().add(panel1, BorderLayout.NORTH);</p>
<p>                  JLabel lblPatient = new JLabel("Patient");<br />
                  lblPatient.setHorizontalAlignment(SwingConstants.LEFT);<br />
                  panel1.add(lblPatient);<br />
                //resultTable.setRowSorter( sorter );</p>
<p>             final TableRowSorter< TableModel > sorter =<br />
            new TableRowSorter< TableModel >( tableModel );<br />
         setSize( 909, 603 ); // set window size<br />
         setVisible( true );<br />
      } // end try<br />
      catch ( SQLException sqlException )<br />
      {<br />
         JOptionPane.showMessageDialog( null, sqlException.getMessage(),<br />
            "Database error", JOptionPane.ERROR_MESSAGE );</p>
<p>         // ensure database connection is closed<br />
         tableModel.disconnectFromDatabase();<br />
         tableModel1.disconnectFromDatabase();</p>
<p>         System.exit( 1 ); // terminate application<br />
      } // end catch</p>
<p>      // tracking table selection</p>
<p>      // dispose of window when user quits application (this overrides<br />
      // the default of HIDE_ON_CLOSE)<br />
      setDefaultCloseOperation( DISPOSE_ON_CLOSE );</p>
<p>      // ensure database connection is closed when user quits application<br />
      addWindowListener(</p>
<p>         new WindowAdapter()<br />
         {<br />
            // disconnect from database and exit when window has closed<br />
            public void windowClosed( WindowEvent event )<br />
            {<br />
               tableModel.disconnectFromDatabase();<br />
               tableModel1.disconnectFromDatabase();<br />
               System.exit( 0 );<br />
            } // end method windowClosed<br />
         } // end WindowAdapter inner class<br />
      ); // end call to addWindowListener</p>
<p>   } // end DisplayQueryResults constructor</p>
<p>   public boolean isRecordSelected()<br />
   {<br />
       return resultTable.getSelectedRow() != -1;<br />
   }<br />
   // execute application<br />
   public static void main( String args[] )<br />
   {<br />
      new DisplayQueryResults();<br />
   } // end main<br />
} // end class DisplayQueryResults</p>
<p>