Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Events

 
Danish Shaukat
Ranch Hand
Posts: 341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all!
What code should i write in the following program so that when the button is pressed the label changes to "Hello all !".
I don't know how to write the action listeners.

import java.awt.*;
import java.awt.event.*;
public class hello1
{

public static void main(String args[])
{
Frame f=new Frame("Event testing !");
f.setSize(500,500);
static Label l1=new Label("Hello World !");
Button b=new Button("Hit me!");
f.add(b,BorderLayout.East);
f.add(l1,BorderLayout.WEST);
f.setVisible(true);
}
}
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Inside your main code after creating b you have two choices:
1. Use your class Hello1 to be the action listener:

Or you can use an anonymous class to perform the function:
[CODE]
public class Hello1
{
public static void main( String[] args )
{
...
Button b = new Button( "Hello" );
b.addActionListener( new ActionListener()
{
public void actionPerformed( ActionEvent ae )
{
// Perform label change here
ae.getSource().setLabel( "Changed" );
}
});
}
}
[CODE]
Good Luck,
Manfred.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic