Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 716
  • Last Modified:

JButtons and ActionEvents

Hello

I got these three functions here, that I would to run as a unit.

With that I mean the following: Then You press search I would like the SQL-statement in getTable() to be executed.

Secondly how do I finish the ActionEvent below, so that the contens of firstname- TextField is read into the String str and afterwhich is executed as part of the sql-statement in getTable().

How its possible to make sence of my Questions !!

Cheers
Frank

private void getTable()
{
Statement statement;
ResultSet resultSet;
try {  
    String query = "select*from contacts where firstname like'" + str +"'";
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
  displayResultSet( resultSet );
        statement.close();
}
catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
}
}

private void locateRecord()
{
    Container cont = getContentPane();
    cont.setLayout(new FlowLayout());
    ImageIcon magnif = new ImageIcon("magnif.gif");
    JLabel label = new JLabel("firstname:");
    JButton button = new JButton("Search", magnif);
    JTextField firstname = new JTextField();
    firstname.setPreferredSize(new Dimension(125,20));
    cont.add(label);
    cont.add(firstname);
    cont.add(button);
}
  public void actionPerformed( ActionEvent ae ) {
   String str = firstname.getText();
........

 

0
Frank-22
Asked:
Frank-22
  • 11
  • 7
1 Solution
 
jimmackCommented:
Pass it in as a parameter to getTable:

private void getTable(String firstName)
{
   .
   .


public void actionPerformed(ActionEvent as)
{
   String str = firstname.getText();
   getTable(str);

// or just:
//  getTable(firstname.getText());
}
0
 
SuperKarateMonkeyCommented:
You need to think OO:

What you need to do is have the class that this whole program is contained in extend JFrame, (which I _think_ you do, I can't be positive,) and also implement the ActionListener interface, so that you can just add the actionlistener to the button by calling the line:

button.addActionListener( this );

Then the class itself will listen for when the button gets pressed, and call the getText() method.
0
 
SuperKarateMonkeyCommented:
The key here is that there is no actual ActionListener _listening_ to the button, and your class doesn't actually implement it, so that just adding the actionPerformed( ActionEvent e ) method to the class doesn't do anything.

check this out:

http://java.sun.com/docs/books/tutorial/uiswing/components/button.html

0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
SuperKarateMonkeyCommented:
This URL also contains good stuff on ActionListeners:

http://java.sun.com/docs/books/tutorial/uiswing/events/actionlistener.html

Basically, everything I ever needed to know about Swing is contained in the Sun tutorial on the subject located at:

http://java.sun.com/docs/books/tutorial/uiswing/TOC.html#events
0
 
Frank-22Author Commented:
Hello

Thanks for all Your answers ....

the basic structure of my program is like this:

public class Addressbook extends JFrame {
....................
public Addressbook()
{
 getTable();
setSize( 500, 109 );
show();
}

private void getTable(String str)
{
Statement statement;
ResultSet resultSet;
try {  
    String query = "select*from contacts where firstname like'" + str +"'";
    statement = connection.createStatement();
    resultSet = statement.executeQuery( query );
  displayResultSet( resultSet );
        statement.close();
}
catch ( SQLException sqlex ) {
    sqlex.printStackTrace();
}
}

private void locateRecord implements ActionListener() {
    Container cont = getContentPane();
    cont.setLayout(new FlowLayout());
    ImageIcon magnif = new ImageIcon("magnif.gif");
    JLabel label = new JLabel("firstname:");
    JButton button = new JButton("Search", magnif);
     button.addActionListener(this);
    JTextField firstname = new JTextField();
    firstname.setPreferredSize(new Dimension(125,20));
    cont.add(label);
    cont.add(firstname);
    cont.add(button);
}
  public void actionPerformed( ActionEvent ae ) {
      String str = firstname.getText();
}

Is this what You Guys mean ?

If yes, I get a couple of compiler problems such as:
String query = "select*from contacts where firstname like'" + str +"'";
                                                                                         ^
Cannot resolve Symbol Str.....


String str = firstname.getText();
                       ^
cannot resolve Symbol firstname

getTable in addressbook cannot be applied to getTable(str) !

To me it seems like a connection between getTable() and locateRecord() is missing !

So if anybody have an idear on how to makes those two functions talk to one and another I would really appricate it !!

Sincerely
Franki
0
 
SuperKarateMonkeyCommented:
Yep.  That's your problem.  You're trying to get a METHOD, ( locateRecord() ) to implement an interface.  CLASSES implement interfaces, not methods.

Change your code like this:

public class AddressBook extends JFrame implements AcitonListener {

public AddressBook()
{
    // All this assembles the frame, so it belongs in the constructor.
    Container cont = getContentPane();
    cont.setLayout(new FlowLayout());
    ImageIcon magnif = new ImageIcon("magnif.gif");
    JLabel label = new JLabel("firstname:");
    JButton button = new JButton("Search", magnif);
    button.addActionListener(this);
    JTextField firstname = new JTextField();
    firstname.setPreferredSize(new Dimension(125,20));
    cont.add(label);
    cont.add(firstname);
    cont.add(button);
   
    setSize( 500, 109 );
    show();
}

public void actionPerformed( ActionEvent ae )
{
    str = firstname.getText();
    getTable( str );
}

private void getTable( String str )
{
...
}

public static void main( String[] args )
{
  AddressBook ab = new AddressBook();
}


It might also be nice if you actually implement the WindowListener interface as well, or at least register an anonymous WindowAdapter, but that'll confuse the issue for now.
0
 
SuperKarateMonkeyCommented:
To implement windowListener you'd add this code:

public class AddressBook extends JFrame implements AcitonListener, WindowListener{
...
button.addActionListener(this);
this.addWindowListener(this);
// I know, this is funny:  Your class is adding itself TO ITSELF to listen for window events.
...

and at the end of the code add these methods

public void windowActivated( WindowEvent we ) {};
public void windowClosed( WindowEvent we ) {};
public void windowClosing( WindowEvent we )
{
      System.exit(0);
}
public void windowDeactivated( WindowEvent we ) {};
public void windowDeiconified( WindowEvent we ) {};
public void windowIconified( WindowEvent we ) {};
public void windowOpened( WindowEvent we ) {};



Or you could just add an anonymous inner class, extending WindowAdapter.  To add an anonymous WindowAdapter, you'd add this to the constructor, immediately after adding the ActionListener to the button:

this.addWindowListener( new WindowAdapter()
                                    {
                                        public void windowClosing( WindowEvent we )
                                        {
                                            system.exit(0);
                                        }
                                    } );
0
 
Frank-22Author Commented:
Hi

Thanks for Your answer.

This WindowListener does it go into the main function ?

I have put it there in the main, but then I compile it the error :

non-static variable this contens can not be referenced from a static context
this.addWindowListener( new WindowAdapter()
  ^                                  {
.
this is my main:
public static void main( String args[] ) {
Addressbook adr = new Addressbook();
adr.show();

       adr.addWindowListener(
                        new WindowAdapter() {
                          public void windowEvent( WindowEvent we ) {
                              System.exit(0);
                          }
                        }
                        );
}
}
.

Secondly the is a compiler- problem under the ActionEvent...

str = firstname.getText();
^
Cannot resolve symbol str..

Secondly

str = firstname.getText();
            ^
Cannot resolve symbol firstname...

Thats strange because the firstname JTextField is defined just before the public void ActionPerformed(ActionEvent ae) .

Again thank you for you answers..

Sincerely
Frank                            
0
 
SuperKarateMonkeyCommented:
You don't put the line:

this.addWindowListener( new WindowApadpter()... );

in the main()

You put it in the CONSTRUCTOR.

As for the second problem, make the change I just told you, then recompile.  If you still have an error, make 2 posts:

1.  You source.
2.  Your compiler output.
0
 
Frank-22Author Commented:
Hi

Thank You for Your answer...

I have added Your coding surgestions to the full-source....

import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Addressbook extends JFrame implements ActionListener, WindowListener {
private Connection connection;
private JTable table;
public Addressbook()
{
String username = "root";
String password = "";

String url = "jdbc:mysql://localhost:3306/addresstest";
try {
Class.forName( "com.mysql.jdbc.Driver" );
connection = DriverManager.getConnection(url);
}
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"Failed to load JDBC/ODBC driver." );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
}
//deleteRecord();
//updateRecord();
  // All this assembles the frame, so it belongs in the constructor.
    Container cont = getContentPane();
    cont.setLayout(new FlowLayout());
    ImageIcon magnif = new ImageIcon("magnif.gif");
    JLabel label = new JLabel("firstname:");
    JButton button = new JButton("Search", magnif);  
  button.addActionListener(this);
  this.addWindowListener(this);
  JTextField firstname = new JTextField();
    firstname.setPreferredSize(new Dimension(125,20));
    cont.add(label);
    cont.add(firstname);
    cont.add(button);
    //getTable();
setSize( 500, 109 );
show();
}
public void windowActivated( WindowEvent we ) {};
public void windowClosed( WindowEvent we ) {};
public void windowClosing( WindowEvent we )
{
     System.exit(0);
}
public void windowDeactivated( WindowEvent we ) {};
public void windowDeiconified( WindowEvent we ) {};
public void windowIconified( WindowEvent we ) {};
public void windowOpened( WindowEvent we ) {};
public void actionPerformed( ActionEvent ae )
{
     str = firstname.getText();
     getTable( str );
}

private void getTable(String str)
{
Statement statement;
ResultSet resultSet;
try {  
    String query = "select *from contacts where firstname like'" + str +"'";
    statement = connection.createStatement();
    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;
}

setTitle( "Addressbook for ModMail" );
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 );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
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();

}
}

These are the compiler errors:

javac Addressbook.java
Addressbook.java:61: cannot resolve symbol
symbol  : variable str
location: class Addressbook
     str = firstname.getText();
     ^
Addressbook.java:61: cannot resolve symbol
symbol  : variable firstname
location: class Addressbook
     str = firstname.getText();
           ^
Addressbook.java:62: cannot resolve symbol
symbol  : variable str
location: class Addressbook
     getTable( str );
               ^
3 errors

I guess there is still a connection missing somewhere ?

Sincerely

Frank
0
 
SuperKarateMonkeyCommented:
Error #1.  Declare str as a String object:

String str = firstname.getText();

Error #2.  Declare firstname OUTSIDE of the constructor, making it a private member variable, so that all methods can access it:

public class Addressbook extends JFrame implements ActionListener, WindowListener
{

private Connection connection;
private JTable table;
private JTextField firstname;
...

Obviously, you'll have to remove the declaration of the variable INSIDE the constructor as well.

Error #3.   Already fixed when you ameliorated error #1.
0
 
SuperKarateMonkeyCommented:
Incidentally, you're missing a best practice here:

Don't load the driver in the constructor.  You should load the driver in a static{} block when you load the class, and only get the CONNECTION when you construct, like this:

public class Addressbook extends JFrame implements ActionListener, WindowListener
{

private Connection connection;
private JTable table;

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

}

public Addressbook()
{
      String username = "root";
      String password = "";
      String url = "jdbc:mysql://localhost:3306/addresstest";
      try
      {
            connection = DriverManager.getConnection(url);
      }
      catch ( SQLException sqlex )
      {
            System.err.println( "Unable to connect" );
            sqlex.printStackTrace();
      }
etc...


This loads your driver when you load up the class, BEFORE you instantiate it, and reduces your overhead, since you only need load the driver once, and since you don't really care about the driver string once you do.
0
 
Frank-22Author Commented:
Hi

Many thanks for You answers I really appricate all Your help...

I got "One" final question regarding my Addressbook-program.

I compiles without any error. Thank You for that...

But two problems remain then I start the load the program:

1. Then I type in a firstname - String which is present in Datebase in the JTextField and press "search", no JTable is displayed.

Instead I get this "very" long nullpointerexception:

java.lang.NullPointerException
      at Addressbook.actionPerformed(Addressbook.java:71)
      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)

Secondly the Program-name, which I defined with setTitle( "Addressbook for ModMail" ); is not displayed for some reason..

Sincerely
Frank
0
 
SuperKarateMonkeyCommented:
Send me the source again.  I need to figure out what's going on at line 71.
0
 
Frank-22Author Commented:
Okay thanks ....

Here is my source-code again...

import java.sql.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Addressbook extends JFrame implements ActionListener, WindowListener {
private Connection connection;
private JTable table;
    private JTextField firstname;

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

}


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

String url = "jdbc:mysql://localhost:3306/addresstest";
try {
connection = DriverManager.getConnection(url,username, password);
}
catch ( SQLException sqlex ) {
System.err.println( "Unable to connect" );
sqlex.printStackTrace();
}
//deleteRecord();
//updateRecord();
  // All this assembles the frame, so it belongs in the constructor.
    Container cont = getContentPane();
    cont.setLayout(new FlowLayout());
    ImageIcon magnif = new ImageIcon("magnif.gif");
    JLabel label = new JLabel("firstname:");
    JButton button = new JButton("Search", magnif);  
  button.addActionListener(this);
  this.addWindowListener(this);
  JTextField firstname = new JTextField();
    firstname.setPreferredSize(new Dimension(125,20));
    cont.add(label);
    cont.add(firstname);
    cont.add(button);
setSize( 500, 109 );
show();
}
public void windowActivated( WindowEvent we ) {};
public void windowClosed( WindowEvent we ) {};
public void windowClosing( WindowEvent we )
{
     System.exit(0);
}
public void windowDeactivated( WindowEvent we ) {};
public void windowDeiconified( WindowEvent we ) {};
public void windowIconified( WindowEvent we ) {};
public void windowOpened( WindowEvent we ) {};
public void actionPerformed( ActionEvent ae )
{
 String str = firstname.getText();
     getTable( str );
}

private void getTable(String str)
{
Statement statement;
ResultSet resultSet;
try {  
    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 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;
}

setTitle( "Addressbook for ModMail" );
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 );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(
scroller, BorderLayout.CENTER );
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
 
SuperKarateMonkeyCommented:
Yeah, I see your problem.  You didn't follow my solution to Error #2, or at least you only PARTIALLY followed it.

On line 10 you DID declar firstname as an instance class member.

HOWEVER:

On line 51 you declared a NEW variable, also name firstname, and added THAT to your content pane, not the member variable that has class scope.

Your code right now:

JTextField firstname = new JTextField();

The correct code:

firstname = new JTextField();
0
 
Frank-22Author Commented:
Hi

Thank "very" much now the search - function works..

But one funny detail remains: Then I start the program, there is no program-title

(Addressbook for ModMail), but when I press search the title suddenly appears in the titlebar !!

Very Strange !!

Cheers
Frank  
0
 
SuperKarateMonkeyCommented:
That's because you never set it in the constructor, you just 'reset' it in the actionPerformed() method.  Try setting it in the constructor:

this.setTitle( "Yackitty-Smackitty" );
0
 
Frank-22Author Commented:
Thank You now works......

Cheers
Frank
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 11
  • 7
Tackle projects and never again get stuck behind a technical roadblock.
Join Now