I have a problem with my actionListener.
It seems that the actionListener runs automatically before I click the button?
The "This should not appear in the console before button click" appear in the console before I click the button".... This is strange.
....
button1.addActionListener(this);
button2.addActionListener(this);
....
public void actionPerformed(ActionEvent e) {
System.out.println("This should not appear in the console before button click");
if (e.getSource()==button1)
System.out.println ("answer1");
else if (e.getSource()==button2)
System.out.println ("answer2");
.....
}
You can tell where methods are being called from by calling Thread.dumpStack(). That will print the stack trace to the error stream (possibly the Java console). Alternatively use a debugger and place a break point on the first line of the method.
public void actionPerformed(ActionEvent e) {
Thread.duumpStack();
System.out.println("This should not appear in the console before button click");
...
BTW: I recommend not using EventObject.getSource. Instead add a new listener for every action.
So your example code would become:
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("answer1");
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("answer2");
}
});
Unfortunately the boilerplate associated with anonymous inner classes is distinctly verbose, but the intention is clearer.
Also make sure that you have not added 'this' as an ActionListener to any other components that might be use before you click either of the buttons. You could also search your code for doClick() calls to make sure you dont call it programatically.
Related
I am a studying programming we just started Swing I have to make a simple boat management I need about 20 buttons. I am using the setVisible() method for every button I just wonder if is there another way of doing that.
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e) {
button.setVisible(false);
button1.setVisible(false);
button2.setVisible(true);
button3.setVisible(true);
}
});
If I understand your question, you could define two utility methods like
static void setVisible(JButton... btns) {
for (JButton btn : btns) {
btn.setVisible(true);
}
}
static void setInvisible(JButton... btns) {
for (JButton btn : btns) {
btn.setVisible(false);
}
}
Then you could call those with any number of buttons; like
setInvisible(button, button1);
setVisible(button2, button3);
As for making different buttons do different things, define an ActionListener per button (or per unique action).
Just add another new ActionListener(){....} to each button and modify the actionPerformed(ActionEvent e) method accordingly
You can just implement the action listener in your class like:
public class XYZ implements ActionListener
Then add it to your buttons like:
b1.addActionListener(this);
b2.addActionListener(this);
...
Then override the actionPerformed method:
public void actionPerformed(ActionEvent e) {
//Here do your tasks.
// To identify the button, use : e.getSource();
}
I implemented the following code to get my character image to change when I clicked the button I created in the JPanel of Netbeans but it's not even being called (tested this by adding a line to print out in console but that's not even being printed. Any help would be appreciated.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
System.out.println("Switch!");
snowman.removeAllImages();
snowman.addImage(image2);
make try and catch statement in your action e.pritntrace it very helpful to debug you code and find your bugs hope this will help you
to change when I clicked the button I created in the JPanel of Netbeans but it's not even being called (tested this by adding a line to print out in console but that's not even being printed.
You may want to ensure the following:
Make sure the button you are interested to generate an event on click has already added as ActionListener object
Example:
If you create an inner class for your ActionListener object,
btn.addActionListener(new ButtonHandler());
If you implements your current class with ActionListener,
btn.addActionListener(this);
If you create an anonymous ActionListener object,
btn.addActionListner(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
//To do when button is clicked
}
});
I see that you created your own method to handle an action event:
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt)
If you do that, remember to fill up your codes in the actionPerformed() method of the ActionListener object which was added to your button.
Example:
#Override
public void actionPerformed(ActionEvent e){
jButton2ActionPerformed(e);
}
Well explained by user3437460. If that doesn't help please copy more code here to understand it. Add a button listener and make sure you called your private method from it as shown below.
btn.addActionListner(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
jButton2ActionPerformed(e);
}
});
I just began using JMenu. To ease into it, I decided to use Netbeans form design tool, which has worked great for all components in this app.
Clicking a top-level menu item works great.
For one menu item, I made a submenu with 3 items, each with a mouse click listener.
Here's relevant code for one of the 3 submenus:
private JMenuItem mnuEditDicAddAllScratch;
mnuEditDicAddAllScratch = new JMenuItem();
private void mnuEditDicAddAllScratchMouseClicked(MouseEvent evt) {
new WordsToAdd(); // never happened
}
mnuEditDicAddAllScratch.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
mnuEditDicAddAllScratchMouseClicked(evt);
}
});
mnuEdit.add(mnuEditDicAddAllScratch);
It didn't work. Clicks ignored.
So I tried an Action listener:
private void mnuEditDicAddAllScratchActionPerformed(ActionEvent evt) {
new WordsToAdd(); // WORKED
}
mnuEditDicAddAllScratch.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
mnuEditDicAddAllScratchActionPerformed(evt);
}
});
And it worked.
So a question is, "Why didn't mouse click listener listen?"
Also, "If I should stay away from mouse click events, why or under what circumstances?"
(And, pre-emptive strike: I should stay away from Netbeans form designer.)
You should use the best tool for the job at hand. This means that for JMenuItems and for JButtons, you should use ActionListeners, not MouseListeners (exceptions notwithstanding). For instance if you disable a button, you want the button to not work, right? This works with ActionListeners but not with MouseListeners.
For the best information on this type of stuff, go to the source: Swing Tutorials.
mnuEditDicAddAllScratch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
mnuEditDicAddAllScratchActionPerformed();
}
});
This should be a basic Java program for beginners to be found on
"Head First Java 2nd Edition" on the topic of ActionListener interface.
I didn't understand some of the terminologies used in this program such as
button.addActionListener(this);
when this code executes how is the method actionPerformed is triggered or run or
any terminologies you use??
//Program begins from now!!
import javax.swing.*;
import java.awt.event.*;
public class SimpleGui1B implements ActionListener {
JButton button;
public static void main(String[] args) {
SimpleGui1B gui = new SimpleGui1B();
gui.go();
}
public void go(){ //start go
JFrame frame= new JFrame();
button=new JButton("Click me");
frame.getContentPane().add(button);
button.addActionListener(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
frame.setVisible(true);
}//close go()
public void actionPerformed(ActionEvent event){
button.setText("I’ve been clicked!");
}
}
Let's break down this statement shall we:
button.addActionListener(this);
Okay, so you're referencing the button object. This is an object of type JButton I presume. The button object has a method called addActionListener. What this does, is add an object that implements the ActionListener interface.
The class that this occurs in is one of those objects. As you can see at the top it says:
public class SimpleGui1B implements ActionListener
So what the program is doing, is saying that the current class (this) will work as a parameter for your method. Then if you look in this class, you have a method actionPerformed.
public void actionPerformed(ActionEvent event){
button.setText("I’ve been clicked!");
}
This means that whenever the button is clicked, the code inside the actionPerformed method is called. Another alternative is to say:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// Add some code here.
}
This is doing the exact same thing, only it's defining the class inside the brackets.
In the JButton class, the keyboard and mouse events are handled, and once the button detects a click, it iterates to its action listeners and calls them:
ActionEvent event = new ActionEvent(...);
for (ActionListener listener : addedListeners) {
listener.actionPerformed(event);
}
Listeners are just callback objects.
Let's walk through the code:
In javax.swing.AbstractButton there is a method called addActionListener where the code is:
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
listenerList is defined in javax.swing.JComponent as:
protected EventListenerList listenerList = new EventListenerList();
When an event occurs fireActionPerformed in javax.swing.AbstractButton is called. The code looks like:
protected void fireActionPerformed(ActionEvent event) {
// Guaranteed to return a non-null array
Object[] listeners = listenerList.getListenerList();
ActionEvent e = null;
// Process the listeners last to first, notifying
// those that are interested in this event
for (int i = listeners.length-2; i>=0; i-=2) {
if (listeners[i]==ActionListener.class) {
// Lazily create the event:
if (e == null) {
String actionCommand = event.getActionCommand();
if(actionCommand == null) {
actionCommand = getActionCommand();
}
e = new ActionEvent(AbstractButton.this,
ActionEvent.ACTION_PERFORMED,
actionCommand,
event.getWhen(),
event.getModifiers());
}
((ActionListener)listeners[i+1]).actionPerformed(e);
}
}
}
The most important part is the last line that says:
((ActionListener)listeners[i+1]).actionPerformed(e);
This is the line of code that calls your actionPerformed() method
That means that the class which is invoking this code is a listener of button changes. So that button will invoke "actionPerformed" on this particular class.
button.addActionListener(this); tells button that this wants to know whenever the button is clicked. From then on, whenever the button is clicked it will go through its list of registered ActionListeners and call the actionPerformed method on each one.
What the code
button.addActionListener(this);
does is add your class (using the keyword this) to be the action listener of the button you created.
What this means, is that the button will call your class whenever an action (such as click) happens. This is why you need the method
public void actionPerformed(ActionEvent event){
button.setText("I’ve been clicked!");
}
Because it will be called by the button
Basically you are going thru observer pattern where observers registers themselves with subject.Now whenever this is some event triggers on subject , subject notifies the different observers. Here Button is subject and SimpleGui1B(basically listener) is observer.Now lets come to your code snippet
button.addActionListener(this);
In above line , button is subject and this is listener/observer. JButton has designed in a way, whenever some event(click in this case) happens on button, observers will be notified thru the method actionPerformed
I am trying to Make a action performed method activate when the mouse is pressed. is this possible. i can only find example like:
if(e.getsource() == button1){
....
}
can this method be activated by a mouseclick?
You could use a MouseListener to your component (and then call the actionListener from its mouse clicked event.
See: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
You may want to create a third function taking a JComponent source and having that containing your actionlistener code and being called by both your mouselistener and actionlistener.
You can try the following code...
This will just print "Hi" to terminal every time you click whatever you put the mouseListener on. Replace contentPane with whatever you called it, and don't forget your import statements.
contentPane.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
System.out.println("Hi");
}
});