Solved

Getting stuff to work in second JFrame in a Swing GUI program

Posted on 2003-11-14
16
1,470 Views
Last Modified: 2013-11-23
Hi

I have build this Addressbook-program in Java.

For this program I'm trying to implement an add - feature that works like this:

The user click on the button "new" in the Main Gui a new JFrame is opened.

On this JFrame there are a couple of JTextFields and a button called "add".

In this second JFrame the use was suppose to able to add record to the mysql-db my typing in the contens of the record in JTextFields("emailadr, firstname, lastname");

the above happens in the launchAnotherFrame() and setContents() functions.

But I have some problems with it.

First of all i'm trying add some JLabel to this new JFrame, which all were suppose appear on the left side of their respective JTextField.
They don't, they appear on the right side, and I can't get them to appear on the left ! Whats wrong ?

Secondly then I press the "new" button to launch theNewJFrame I get a very long nullpointer exception .
Why do I get that ?

Finally the actionListener for add - button in the new JFrame where is the best place to put it ?

inside the setcontens()  function or what ?

Sincerely
Frank





import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Addressbook extends JFrame implements ActionListener {
    private Connection connection;
    private JTable table;
    private JTextField firstname;
    private JScrollPane scroller;
    private JButton button = new JButton("search");
    private JButton button3;
        private DataPanel scnvar;
static
{
     try
     {
          Class.forName( "com.mysql.jdbc.Driver" );
     }
     catch ( ClassNotFoundException cnfex )
     {
          System.err.println( "Failed to load JDBC driver." );
          cnfex.printStackTrace();
          System.exit( 1 );
     }

}


public Addressbook()
{
String username = "root";
String password = "";

String url = "jdbc:mysql:///addresstest";
try {
    connection = DriverManager.getConnection(url,username, password);
}
catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
}
// All this assembles the frame, so it belongs in the constructor.
    Container cont = getContentPane();
    this.setTitle( "Addressbook for ModMail" );
 
cont.setLayout(new BorderLayout());
JPanel buttonsPane = new JPanel();

ImageIcon greenV = new ImageIcon("greenV.gif");
button3 = new JButton("New", greenV);

 
ImageIcon magnif = new ImageIcon("magnif.gif");
JLabel label = new JLabel("firstname:");
button = new JButton("Search", magnif);  



ImageIcon redX = new ImageIcon("redX.gif");
JButton button1 = new JButton("Delete", redX);  


ImageIcon v = new ImageIcon("v.gif");
JButton button2 = new JButton("Update", v);  


firstname = new JTextField();
scroller = new JScrollPane();
firstname.setPreferredSize(new Dimension(125,20));
   
buttonsPane.add(button3);
buttonsPane.add(button1);
buttonsPane.add(button2);
buttonsPane.add(label);
buttonsPane.add(firstname);
buttonsPane.add(button);

cont.add(buttonsPane,BorderLayout.SOUTH);
cont.add(scroller,BorderLayout.CENTER);
setSize( 600, 150 );

button3.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button.addActionListener(this);

}
public void actionPerformed(ActionEvent e) {
    JButton src = (JButton)e.getSource();
    if (src == button) {
      this.getTable(); }
    else if (src == button3) {
      this.launchAnotherFrame();
    }
}

private void getTable()
{
Statement statement;
ResultSet resultSet;

try {  
    String str = firstname.getText();
    String query = "select* from contacts where firstname like '" + str + "'";
    statement = connection.createStatement();
    System.out.println(query);
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
}
catch ( SQLException sqlex ) {
    sqlex.printStackTrace();

}
}
private void launchAnotherFrame() {
    JFrame frame = new JFrame("Add a record");
    frame.setSize(200, 100);
    this.setContents(frame.getContentPane());
    frame.show();
}

private void setContents(Container con) {
    Statement statement;
    ResultSet resultSet;

    JButton btn = new JButton("add");
    JButton clr = new JButton("clear");
    JLabel eml = new JLabel("emailadr:");
    JLabel frst = new JLabel("firstname:");
    JLabel lst = new JLabel("lastname:");
    JLabel als = new JLabel("alias:");
    JTextField emailadr = new JTextField(20);
    JTextField firstname = new JTextField(20);
    JTextField lastname = new JTextField(20);
    JTextField alias = new JTextField(20);

    JPanel panel = new JPanel();
    con.add(panel);
    con.setLayout(new GridLayout(5,1));
 
 panel.add(emailadr);
panel.add(eml);
 panel.add(firstname);
 panel.add(frst);
panel.add(lastname);
panel.add(lst);

        JPanel pn = new JPanel();
 
    con.add(pn);
    con.setLayout(new GridLayout(2,1));
    pn.add(btn);
btn.addActionListener(this);
   pn.add(clr);

 try {
    String st = emailadr.getText();
    String str = firstname.getText();
    String strr = lastname.getText();
    // String strrr = alias.getText();
    String query = "INSERT INTO addressbook4 (emailadr, firstname, lastname) VALUES ('" +  
             st + "','" +
             str  + "','" +    
               strr + "')";

    statement = connection.createStatement();
    System.out.println(query);
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
}
catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
}
}

private void displayResultSet( ResultSet rs )
throws SQLException
{
// position to first record
boolean moreRecords = rs.next();

// If there are no records, display a message
if ( ! moreRecords ) {
JOptionPane.showMessageDialog( this,
"ResultSet contained no records" );
//setTitle( "No records to display");
return;
}

Vector columnHeads = new Vector();
Vector rows = new Vector();

try {
// firstname.setPreferredSize(new Dimension(125,20));get column heads
ResultSetMetaData rsmd = rs.getMetaData();

for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );

// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );

// display table with ResultSet contents
table = new JTable( rows, columnHeads );
getContentPane().remove(scroller);
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
validate();
getContentPane().validate();
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
}
}

private Vector getNextRow( ResultSet rs,
ResultSetMetaData rsmd )
throws SQLException
{
Vector currentRow = new Vector();

for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
switch( rsmd.getColumnType( i ) ) {
case Types.VARCHAR:
currentRow.addElement( rs.getString( i ) );
break;
case Types.INTEGER:
currentRow.addElement(
new Long( rs.getLong( i ) ) );
break;
default:
System.out.println( "Type was: " +
rsmd.getColumnTypeName( i ) );
}

return currentRow;
}

public void shutDown()
{
try {
connection.close();
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to disconnect" );
sqlex.printStackTrace();
}
}

public static void main( String args[] ) {
Addressbook adr = new Addressbook();
adr.show();

}
}
0
Comment
Question by:Frank-22
  • 9
  • 7
16 Comments
 
LVL 15

Expert Comment

by:jimmack
ID: 9751815
To sort out the label positions, switch round the order in which you add the components to the panel in setContents().  ie.

        panel.add(eml);
        panel.add(emailadr);
        panel.add(frst);
        panel.add(firstname);
        panel.add(lst);
        panel.add(lastname);

Add the following line to your constructor (just after the try...catch), in order to exit the application when the "x" in the top right corner is clicked:

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

The NullPointerException is occurring because you haven't successfully created a "connection".  Do you get any other exceptions when you start the software (possibly indicating that your MySQL driver isn't loaded/working)?

Set the action listener for the add button to "this" and update the actionPerformed() method to handle the event when the src == btn.  In order to achieve this, you'll need to change the definition of btn from a local variable (in setContents()) to an attribute of the class.
0
 

Author Comment

by:Frank-22
ID: 9753798
HI Thanks for Your answer..

I only the the nullpointer exception then I click on the button "new" which loads the new JFrame.

I have a search-function in the main-gui and it connects without any trouble to the mysql-db.

Secondly I have added the buttons in the Second JFrame to a panel, but then I load the JFrame by pressing the button the JTextFields aren't alligned propperly.

What do I need to put inside my panel, so they get alligned and displayed properly ?

Is it something to do with size of JFrame ?


Sincerely
Frank


 

0
 

Author Comment

by:Frank-22
ID: 9753915
Hi

I have made the changes You surgested, but then I try to compile I get these errors :


javac Addressbook.java
Addressbook.java:182: illegal start of expression
 public void actionPerformed (ActionEvent ae) {
 ^
Addressbook.java:188: ';' expected
}
^
2 errors.


Maybe You can see where the problem is ?

Here is my new source-code.


import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Addressbook extends JFrame implements ActionListener {
    private Connection connection;
    private JTable table;
    private JTextField firstname;
    private JScrollPane scroller;
    private JButton button = new JButton("search");
    private JButton button3;
    private JButton btn;
   static
{
     try
     {
          Class.forName( "com.mysql.jdbc.Driver" );
     }
     catch ( ClassNotFoundException cnfex )
     {
          System.err.println( "Failed to load JDBC driver." );
          cnfex.printStackTrace();
          System.exit( 1 );
     }

}


public Addressbook()
{
String username = "root";
String password = "";

String url = "jdbc:mysql:///addresstest";
try {
    connection = DriverManager.getConnection(url,username, password);
}
catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
}
// All this assembles the frame, so it belongs in the constructor.
    Container cont = getContentPane();
    this.setTitle( "Addressbook for ModMail" );
 
cont.setLayout(new BorderLayout());
JPanel buttonsPane = new JPanel();

ImageIcon greenV = new ImageIcon("greenV.gif");
button3 = new JButton("New", greenV);

 
ImageIcon magnif = new ImageIcon("magnif.gif");
JLabel label = new JLabel("firstname:");
button = new JButton("Search", magnif);  



ImageIcon redX = new ImageIcon("redX.gif");
JButton button1 = new JButton("Delete", redX);  


ImageIcon v = new ImageIcon("v.gif");
JButton button2 = new JButton("Update", v);  


firstname = new JTextField();
scroller = new JScrollPane();
firstname.setPreferredSize(new Dimension(125,20));
   
buttonsPane.add(button3);
buttonsPane.add(button1);
buttonsPane.add(button2);
buttonsPane.add(label);
buttonsPane.add(firstname);
buttonsPane.add(button);

cont.add(buttonsPane,BorderLayout.SOUTH);
cont.add(scroller,BorderLayout.CENTER);
setSize( 600, 150 );

button3.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
button.addActionListener(this);

}
public void actionPerformed(ActionEvent e) {
    JButton src = (JButton)e.getSource();
    if (src == button) {
      this.getTable(); }
    else if (src == button3) {
      this.launchAnotherFrame();  
    }
}

private void getTable()
{
Statement statement;
ResultSet resultSet;

try {  
    String str = firstname.getText();
    String query = "select* from contacts where firstname like '" + str + "'";
    statement = connection.createStatement();
    System.out.println(query);
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
}
catch ( SQLException sqlex ) {
    sqlex.printStackTrace();

}
}

private void launchAnotherFrame() {
    JFrame frame = new JFrame("Add a record");
    frame.setSize(350, 450);
    this.setContents(frame.getContentPane());
    frame.show();
}

private void setContents(Container con) {
    Statement statement;
    ResultSet resultSet;

    btn = new JButton("add");
    JButton clr = new JButton("clear");
    JLabel eml = new JLabel("emailadr:");
    JLabel frst = new JLabel("firstname:");
    JLabel lst = new JLabel("lastname:");
    JLabel als = new JLabel("alias:");
    JTextField emailadr = new JTextField(20);
    JTextField firstname = new JTextField(20);
    JTextField lastname = new JTextField(20);
    JTextField alias = new JTextField(20);

    JPanel panel = new JPanel();
    con.add(panel);
    con.setLayout(new GridLayout(4,2));
    panel.add(eml);
    panel.add(emailadr);
    panel.add(frst);
    panel.add(firstname);
    panel.add(lst);
    panel.add(lastname);
    panel.add(als);
    panel.add(alias);
    panel.add(btn);
    btn.addActionListener(this);

    try {
      String st = emailadr.getText();
      String str = firstname.getText();
      String strr = lastname.getText();
      String strrr = alias.getText();
      String query = "INSERT INTO addressbook4 (emailadr, firstname, lastname, alias) VALUES ('" +  
          st + "','" +
          str  + "','" +    
          strr + "','" +
          strrr + "')";

      statement = connection.createStatement();
      resultSet = statement.executeQuery( query );
      displayResultSet( resultSet );
      statement.close();
    }
    catch ( SQLException sqlex ) {
      sqlex.printStackTrace();
    }

 public void actionPerformed (ActionEvent ae) {
 JButton src = (JButton)ae.getSource();
     if (src == btn) {
       this.setContents();
     }    
 }
}

private void displayResultSet( ResultSet rs )
    throws SQLException
{
    // position to first record
    boolean moreRecords = rs.next();

    // If there are no records, display a message
    if ( ! moreRecords ) {
      JOptionPane.showMessageDialog( this,
                               "ResultSet contained no records" );
      //setTitle( "No records to display");
      return;
    }
   
    Vector columnHeads = new Vector();
    Vector rows = new Vector();

    try {
      // get column heads
      ResultSetMetaData rsmd = rs.getMetaData();

      for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
          columnHeads.addElement( rsmd.getColumnName( i ) );

      // get row data
      do {
          rows.addElement( getNextRow( rs, rsmd ) );
      } while ( rs.next() );

// display table with ResultSet contents
      table = new JTable( rows, columnHeads );
      getContentPane().remove(scroller);
      JScrollPane scroller = new JScrollPane( table );
      getContentPane().add(
                       scroller, BorderLayout.CENTER );
      validate();
      getContentPane().validate();
    }
    catch ( SQLException sqlex ) {
      sqlex.printStackTrace();
    }
}

private Vector getNextRow( ResultSet rs,
                     ResultSetMetaData rsmd )
    throws SQLException
{
    Vector currentRow = new Vector();

    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
      switch( rsmd.getColumnType( i ) ) {
      case Types.VARCHAR:
          currentRow.addElement( rs.getString( i ) );
          break;
      case Types.INTEGER:
          currentRow.addElement(
                          new Long( rs.getLong( i ) ) );
          break;
      default:
          System.out.println( "Type was: " +
                        rsmd.getColumnTypeName( i ) );
      }
   
    return currentRow;
}

public void shutDown()
{
    try {
      connection.close();
    }
    catch ( SQLException sqlex ) {
      System.err.println( "Unable to disconnect" );
      sqlex.printStackTrace();
    }
}

public static void main( String args[] ) {
Addressbook adr = new Addressbook();
adr.show();

}
}

Sincerely

Frank

0
 
LVL 15

Expert Comment

by:jimmack
ID: 9754598
I'll deal with your compilation error now, but it will be a couple of hours before I have time to answer your layout question.

"I'll be back" ;-)

You should only have one actionPerformed() method.  You already had this:

public void actionPerformed(ActionEvent e) {
    JButton src = (JButton)e.getSource();
    if (src == button) {
     this.getTable(); }
    else if (src == button3) {
     this.launchAnotherFrame();  
    }
}

remove the code you added:

 public void actionPerformed (ActionEvent ae) {
 JButton src = (JButton)ae.getSource();
     if (src == btn) {
      this.setContents();
     }    


and update your original actionPerformed to this:

public void actionPerformed(ActionEvent e) {
    JButton src = (JButton)e.getSource();
    if (src == button) {
     this.getTable();
    }
    else if (src == button3) {
     this.launchAnotherFrame();  
    }
    else if (src == btn) {
      this.setContents();
    }
}


As I said, I'll be back later to deal with the layout bit ;-)
0
 

Author Comment

by:Frank-22
ID: 9754824
Okay thanks ....

I will login later.

I only get one compiler error now:

Addressbook.java:107: setContents(java.awt.Container) in Addressbook cannot be applied to ()
      this.setContents();
      ^
1 error

I have a feeling that its something to do with the Container cont argument in the setContens function ?

Sincerely
Frank
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9754838
Yes.  That's right.  I've just found this now that I've come back to start work on the layout ;-)

Details to follow soon :-)
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9754989
Hi Frank.

First, I strongly recommend that you replace your three JButton definitions at the top of the class with the following, this will really help you when you have problems:

    private JButton searchButton = new JButton("search");
    private JButton newButton;
    private JButton addButton;

Make this change first and all the other references throughout the code to match these.  ie.

  "button" becomes "searchButton"
  "button3" becomes "newButton"
  "btn" becomes "addButton"

OK. Part two (the layout of the Add popup):

Replace the first part of the setContents() method (up to the "try") with the following code.  It puts the labels in one GridLayout (with 1 column) and the input boxes in another GridLayout (also with 1 column), then adds these to another panel (using a FlowLayout).  This is then added to the CENTER of the panel and the button is added to another FlowLayout panel, which in turn is added to the SOUTH.

    private void setContents(Container con)
    {
        Statement statement;
        ResultSet resultSet;

        addButton = new JButton("add");
        JButton clr = new JButton("clear");
        JLabel eml = new JLabel("emailadr:");
        JLabel frst = new JLabel("firstname:");
        JLabel lst = new JLabel("lastname:");
        JLabel als = new JLabel("alias:");
        JTextField emailadr = new JTextField(20);
        JTextField firstname = new JTextField(20);
        JTextField lastname = new JTextField(20);
        JTextField alias = new JTextField(20);

        JPanel labelsPanel = new JPanel(new GridLayout(4, 1));
        labelsPanel.add(eml);
        labelsPanel.add(frst);
        labelsPanel.add(lst);
        labelsPanel.add(als);
       
        JPanel inputPanel = new JPanel(new GridLayout(4, 1));
        inputPanel.add(emailadr);
        inputPanel.add(firstname);
        inputPanel.add(lastname);
        inputPanel.add(alias);
       
        JPanel labelsAndInputs = new JPanel(new FlowLayout());
        labelsAndInputs.add(labelsPanel);
        labelsAndInputs.add(inputPanel);
       
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(addButton);
       
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(labelsAndInputs, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
       
        con.add(panel);
        addButton.addActionListener(this);

Then replace the launchAnotherFrame() method with the following (the "pack()" will make the frame fit the contents):

    private void launchAnotherFrame()
    {
        JFrame frame = new JFrame("Add a record");
        this.setContents(frame.getContentPane());
        frame.pack();
        frame.show();
    }


The next part is the actionPerformed() method.  I don't think that you actually want to do a setContents in there.  That method is used to create the add JFrame.  For now, I've just replaced this with a System.out.println(), just to prove that the method is called :-)

    public void actionPerformed(ActionEvent e)
    {
        JButton src = (JButton)e.getSource();
        if (src == searchButton)
        {
            this.getTable();
        }
        else if (src == newButton)
        {
            this.launchAnotherFrame();
        }
        else if (src == addButton)
        {
            System.out.println("Add pressed");
        }
    }

I'm not too sure about the NullPointerException (other than to say that it seems that the "connection" variable seems to be null).  This is difficult for me to find without creating a database to test with ;-)

I think I've covered everything ;-)  If not, please post again.
0
 

Author Comment

by:Frank-22
ID: 9755110
Hi

Many thanks for all you help..

Now the problem compiles, but then I try to run it I get a nullpointer exception.

java.lang.NullPointerException
      at java.awt.Container.addImpl(Unknown Source)
      at java.awt.Container.add(Unknown Source)
      at Addressbook.<init>(Addressbook.java:76)
      at Addressbook.main(Addressbook.java:280)
Exception in thread "main"

Regarding the db-problem...

I can give You my ip-address, so if possible You can connect to my mysql-db !

Frank
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 15

Expert Comment

by:jimmack
ID: 9755144
Which is line 76?  It looks like you're probably doing an add() to the buttonPane with a button that you haven't initialised.  This is probably because you still have one of the old button references around (button, button3 or btn) that hasn't been created.  Make sure that you deleted all these from the top of the class ;-)

Also (I've just remembered ;-), you haven't added the following line yet

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Add this just after the try...catch block in the constructor (just before the "Container cont = getContentPane()").

0
 

Author Comment

by:Frank-22
ID: 9755258
Hi again and many thanks for Your answer.

I can see then I press the JButton named new in the main GUI I get the nullpointer exception where the following line is at the top:

java.sql.SQLException: Can not issue data manipulation statements with executeQuery()

What does that mean ?

Frank
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9755319
Hmm.  Sounds like your driver is being a bit fussy ;-)

Change the line to executeUpdate(...) instead ;-)
0
 

Author Comment

by:Frank-22
ID: 9755409
Hi Again...

I found out that the best way ge the SQL to work was to move it to a new function called addRecord();

 private void addRecord() {
     
   Statement statement;
  ResultSet resultSet;  
 
    try {
       String st = emailadr.getText();
       String str = firstname.getText();
       String strr = lastname.getText();
       String strrr = alias.getText();
       String query = "INSERT INTO addressbook4 (emailadr, firstname, lastname, alias) VALUES ('" +  
           st + "','" +
           str  + "','" +    
           strr + "','" +
           strrr + "')";

       statement = connection.createStatement();
       resultSet = statement.executeUpdate( query );
       statement.close();
    }
    catch ( SQLException sqlex ) {
      sqlex.printStackTrace();
    }
 }



But then I try to compile I get the error:

Addressbook.java:202: incompatible types
found   : int
required: java.sql.ResultSet
resultSet = statement.executeUpdate( query );

I know that it has something to do with I have set the length of the JTextField like so :

JTextField emailadr = new JTextField(20);

So instead of reading what I write I the JTextField in the GUI, the problem reads the int length 20 as the contents of the JTextfield.

Any idear on how I get it to read the correct input instead ?

Sincerely
Frank



0
 
LVL 15

Expert Comment

by:jimmack
ID: 9755466
No, no.  I didn't include all the information that I should have with the last comment.

executeQuery() returns a result set containing the results of the query that you executed.  In this case, you are doing an "INSERT", so you use executeUpdate().

executeUpdate() returns the number of rows "affected" by the SQL command.  In this case, it should just return 1 because you've just inserted a single line.

A couple of points:

1)  You can ignore the result if you want, eg. instead of:

resultSet = statement.executeUpdate( query );

just use:

statement.executeUpdate( query );

2) If you try to add a duplicate row (ie. one that repeats the primary key in the table), you'll get an SQL exception.  You could use this to identify this problem if you wish.


0
 

Author Comment

by:Frank-22
ID: 9755612
Sorry to trouble You again..

The program compiles now..

But one tiny detail remain..

While in the new frame after inputting stuff in JTextFields I get this error after then pressing add.

java.lang.NullPointerException
      at Addressbook.addRecord(Addressbook.java:190)
      at Addressbook.actionPerformed(Addressbook.java:111)
      at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
      at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
      at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
      at java.awt.Component.processMouseEvent(Unknown Source)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Window.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForHierarchy(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)

From I can see that there is something wrong in Line 190 and line 111.

But what ?

Here is my latest sourcecode:

import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Addressbook extends JFrame implements ActionListener {
    private Connection connection;
    private JTable table;
    private JTextField emailadr;
    private JTextField firstname;
    private JTextField lastname;
    private JTextField alias;
    private JScrollPane scroller;
    private JButton searchButton;
    private JButton newButton;
    private JButton addButton;

   static
{
     try
     {
          Class.forName( "com.mysql.jdbc.Driver" );
     }
     catch ( ClassNotFoundException cnfex )
     {
          System.err.println( "Failed to load JDBC driver." );
          cnfex.printStackTrace();
          System.exit( 1 );
     }

}


public Addressbook()
{
String username = "root";
String password = "";

String url = "jdbc:mysql:///addresstest";
try {
    connection = DriverManager.getConnection(url,username, password);
}
catch ( SQLException sqlex ) {
    System.err.println( "Unable to connect" );
    sqlex.printStackTrace();
}
// All this assembles the frame, so it belongs in the constructor.
    Container cont = getContentPane();
    this.setTitle( "Addressbook for ModMail" );
 
cont.setLayout(new BorderLayout());
JPanel buttonsPane = new JPanel();

ImageIcon greenV = new ImageIcon("greenV.gif");
newButton = new JButton("New", greenV);

 
ImageIcon magnif = new ImageIcon("magnif.gif");
JLabel label = new JLabel("firstname:");
searchButton = new JButton("Search", magnif);  

ImageIcon redX = new ImageIcon("redX.gif");
JButton button1 = new JButton("Delete", redX);  

ImageIcon v = new ImageIcon("v.gif");
JButton button2 = new JButton("Update", v);  

firstname = new JTextField();
scroller = new JScrollPane();
firstname.setPreferredSize(new Dimension(125,20));
   
buttonsPane.add(newButton);
buttonsPane.add(button1);
buttonsPane.add(button2);
buttonsPane.add(label);
buttonsPane.add(firstname);
buttonsPane.add(searchButton);

cont.add(buttonsPane,BorderLayout.SOUTH);
cont.add(scroller,BorderLayout.CENTER);
setSize( 600, 150 );

newButton.addActionListener(this);
button1.addActionListener(this);
button2.addActionListener(this);
searchButton.addActionListener(this);

}

public void actionPerformed(ActionEvent e)
    {
        JButton src = (JButton)e.getSource();
        if (src == searchButton)
        {
            this.getTable();
        }
        else if (src == newButton)
        {
            this.launchAnotherFrame();
        }
        else if (src == addButton)
        {
          this.addRecord();
        }
    }

private void getTable()
{
Statement statement;
ResultSet resultSet;

try {  
    String str = firstname.getText();
    String query = "select* from contacts where firstname like '" + str + "'";
    statement = connection.createStatement();
    System.out.println(query);
    resultSet = statement.executeQuery( query );
    displayResultSet( resultSet );
    statement.close();
}
catch ( SQLException sqlex ) {
    sqlex.printStackTrace();

}
}

 private void launchAnotherFrame()
    {
        JFrame frame = new JFrame("Add a new record");
        this.setContents(frame.getContentPane());
        frame.pack();
        frame.show();
    }

private void setContents(Container con) {
   
    addButton = new JButton("add");      
      addButton.addActionListener(this);
       JButton clr = new JButton("clear");
        JLabel eml = new JLabel("emailadr:");
        JLabel frst = new JLabel("firstname:");
        JLabel lst = new JLabel("lastname:");
        JLabel als = new JLabel("alias:");
        JTextField emailadr = new JTextField( 20 );
        JTextField firstname = new JTextField( 20 );
        JTextField lastname = new JTextField( 20 );
        JTextField alias = new JTextField( 20 );

        JPanel labelsPanel = new JPanel(new GridLayout(4, 1));
        labelsPanel.add(eml);
        labelsPanel.add(frst);
        labelsPanel.add(lst);
        labelsPanel.add(als);
       
        JPanel inputPanel = new JPanel(new GridLayout(4, 1));
        inputPanel.add(emailadr);
        inputPanel.add(firstname);
        inputPanel.add(lastname);
        inputPanel.add(alias);
       
        JPanel labelsAndInputs = new JPanel(new FlowLayout());
        labelsAndInputs.add(labelsPanel);
        labelsAndInputs.add(inputPanel);
       
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(addButton);
       
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(labelsAndInputs, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
       
        con.add(panel);
       
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

 private void addRecord() {
     
     Statement statement;
 
    try {
      String st = emailadr.getText();
      String str = firstname.getText();
      String strr = lastname.getText();
      String strrr = alias.getText();
      String query = "INSERT INTO addressbook4 (emailadr, firstname, lastname, alias) VALUES ('" +  
          st + "','" +
          str  + "','" +    
          strr + "','" +
          strrr + "')";
      
      statement = connection.createStatement();
      statement.executeUpdate( query );
      statement.close();
    }
    catch ( SQLException sqlex ) {
      sqlex.printStackTrace();
    }
 }


private void displayResultSet( ResultSet rs )
    throws SQLException
{
    // position to first record
    boolean moreRecords = rs.next();
   
    // If there are no records, display a message
    if ( ! moreRecords ) {
      JOptionPane.showMessageDialog( this,
                               "ResultSet contained no records" );
      return;
    }
   
    Vector columnHeads = new Vector();
    Vector rows = new Vector();

    try {
      // get column heads
      ResultSetMetaData rsmd = rs.getMetaData();

      for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
          columnHeads.addElement( rsmd.getColumnName( i ) );

      // get row data
      do {
          rows.addElement( getNextRow( rs, rsmd ) );
      } while ( rs.next() );

// display table with ResultSet contents
      table = new JTable( rows, columnHeads );
      getContentPane().remove(scroller);
      JScrollPane scroller = new JScrollPane( table );
      getContentPane().add(
                       scroller, BorderLayout.CENTER );
      validate();
      getContentPane().validate();
    }
    catch ( SQLException sqlex ) {
      sqlex.printStackTrace();
    }
}

private Vector getNextRow( ResultSet rs,
                     ResultSetMetaData rsmd )
    throws SQLException
{
    Vector currentRow = new Vector();

    for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
      switch( rsmd.getColumnType( i ) ) {
      case Types.VARCHAR:
          currentRow.addElement( rs.getString( i ) );
          break;
      case Types.INTEGER:
          currentRow.addElement(
                          new Long( rs.getLong( i ) ) );
          break;
      default:
          System.out.println( "Type was: " +
                        rsmd.getColumnTypeName( i ) );
      }
   
    return currentRow;
}

public void shutDown()
{
    try {
      connection.close();
    }
    catch ( SQLException sqlex ) {
      System.err.println( "Unable to disconnect" );
      sqlex.printStackTrace();
    }
}

public static void main( String args[] ) {
Addressbook adr = new Addressbook();
adr.show();

}
}

Again thanks for all You help..

Sincerely

Frank

0
 
LVL 15

Accepted Solution

by:
jimmack earned 125 total points
ID: 9755680
That's OK.  This is a nice easy one ;-)

In your setContents() method, you have the following lines:

        JTextField emailadr = new JTextField( 20 );
        JTextField firstname = new JTextField( 20 );
        JTextField lastname = new JTextField( 20 );
        JTextField alias = new JTextField( 20 );

This is creating a local instance of each of these text fields (effectively ignoring your class attributes).  Just remove the JTextField from the beginning of each line:

        emailadr = new JTextField( 20 );
        firstname = new JTextField( 20 );
        lastname = new JTextField( 20 );
        alias = new JTextField( 20 );

;-)
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9755971
;-) Thanx.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Here is a helpful source code for C++ Builder programmers that allows you to manage and manipulate HTML content from C++ code, while also handling HTML events like onclick, onmouseover, ... Some objects defined and used in this source include: …
Jaspersoft Studio is a plugin for Eclipse that lets you create reports from a datasource.  In this article, we'll go over creating a report from a default template and setting up a datasource that connects to your database.
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now