Search code examples
javaswingjlabelmouselistener

mouse listener to JLabels


stuck here for days....what is wrong here pls tell

Exception in thread "main" java.lang.NullPointerException
    at java.awt.Container.addImpl(Unknown Source)
    at java.awt.Container.add(Unknown Source)
    at contacts3.<init>(contacts3.java:41)
    at contacts3.main(contacts3.java:75)

part of my code---

contacts3()
{
    try
    {
        f1=new JFrame();
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        Connection con=DriverManager.getConnection("jdbc:odbc:login321", "", "");
        Statement st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
        String fet="Select * from Contacts";
        ResultSet rs=st.executeQuery(fet);
        int i=0;
        while(rs.next())
        {
            l[i]=new JLabel(rs.getString(1));
            l[i].setFont(ft);
            i++;
        }
    }
    catch(Exception e)
    {
        System.out.println("acccc");
        e.printStackTrace();        
    }
    p1.setLayout(new GridLayout(500,1));
    for(int i=0;i<500;i++)
    {
        p1.add(l[i]);
        l[i].addMouseListener(this);
    }

    f1.getContentPane().add(p1);
    f1.setSize(600,300);
    f1.setVisible(true);

}
public void mouseClicked(MouseEvent m)
{
    try
    {
        JLabel label=(JLabel)m.getSource();
        //new convall(label.getText());
        f1.dispose();
    }
    catch(Exception e)
    {
        System.out.println("avc");
        e.printStackTrace();
    }
}

Solution

  • Looks like your code is erroring out on this line

    p1.add(l[i]);
    

    Where do you initialize your array l? Also you only set the first n records of that array where n is the number of Rows in your ResultSet. But later you add the first 500 elements of the array. Do you get at least 500 elements from the SQL query?