-
Invoking Action Listeners via code
Hi guys,
I have a question about action listeners and i've been searching forever but can't seem to find anything to help me. Basically, I have a Jbutton setup, but upon certain instances, when a boolean flag is set, i need to automatically invoke the button via code.
Example: I am creating a simple board game that requires AI. But the interface is all Jbuttons. So when it is the computer's turn, i need to be able to invoke the Jbutton (basically, I need to pretend the computer had a mouse and pushed the button itself), but i'm not sure how to go about doing that. Any help would be greatly appreciated .
I grabbed some sample code off java's website, perhaps someone could show me how it would work in this example?
public class SwingApplication implements ActionListener {
...
JButton button = new JButton("I'm a Swing button!");
button.addActionListener(this);
....
public void actionPerformed(ActionEvent e) {
numClicks++;
label.setText(labelPrefix + numClicks);
}
}
Thanks,
Mo
-
on jdk documentation for jbutton you will recognize, that a jbutton inherits from a class that has the method fireActionPerformed. This one you can invoke.
but it's a better aproach to make the action in an seperate method:
Code:
myclass{
public myclass(){
mybutton = new JButton();
mybutton.addActionListener(
new actionlsitener(){
public actionperformed(){
doaction();
}
}
}
}
public void doaction(){
// do sthg when button is pressed
}
}
so the code for the action really performed (here doaction()) can be accessed anywhere and you don't have to bother about pressing buttons.
Similar Threads
-
By Gary Nelson in forum .NET
Replies: 277
Last Post: 10-01-2003, 12:00 AM
-
Replies: 246
Last Post: 10-26-2002, 12:30 AM
-
Replies: 125
Last Post: 10-05-2002, 04:34 PM
-
By Patrick Ireland in forum .NET
Replies: 19
Last Post: 04-24-2001, 04:19 PM
-
By Dharmesh Sanghavi in forum VB Classic
Replies: 0
Last Post: 02-28-2001, 01:10 PM
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
Forum Rules
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks