ActionListener with a mousepress in java - java

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");
}
});

Related

Closing JFrame with a JButton

Im having problem with this code , it doesn't compile . Could you help me ?
I need to close the JFrame when i click the button
public class SlotMachine extends JFrame
{
/*
*
*/
JButton btnExit = new JButton("Exit");
btnExit.addMouseListener(new MouseAdapter()
{
#Override
public void mouseClicked(MouseEvent arg0)
{
this.dispose();
}
});
}
The error is = The method dispose() is undefined for the type new MouseAdapter(){}
I dont know how to get the SlotMachine object from the mouseClicked method
You're calling this.dispose(); the key here being that this refers to the inner class, the MouseListener, and MouseListener doesn't have a dispose() method.
Solution: get rid of this, and it should work, since the compiler will then look into the outer class if the inner class does not contain the method. Alternatively you could specify which this you mean: SlotMachine.this.dispose(); will tell the compiler to call the method of the outer SlotMachine class.
Use an ActionListener on a JButton for several reasons:
Default behavior of buttons is to be activated by spacebar press if the button has focus. This will not work for a MouseListener.
Also an expected behavior is that if the button is disabled via setEnabled(false), then pressing it should not cause the action to be fired. This does not work with MouseListener but does with ActionListener.
You can easily share the ActionListener (or better yet, an AbstractAction) with other components including JMenuItems.

JPanel button not responding?

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);
}
});

for ComboBox, addActionListener -> actionPerformed?

if I have
ComboBox box = b;
b.addActionListener(this);
shouldn't I expect this.actionPerformed(event) to be called
when the combobox is operated?
I have a test frame with a few combo boxes, which seem to operate
normally, but no actionPerformed is ever called. Perhaps the frame
itself needs to be armed in some way?
Your question is not so clear and you didn't give it a proper title.
If you want to add ActionListener to a ComboBox, this is how you do it:
ComboBox box = new ComboBox();
box.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
}
});
From what I understand you just want to create a ComboBox from within a class that with be handling the action events. To do so I would suggest that the class inherits from ActionListener and override (use the #Override tag) the actionPerformed. Just Overriding the action perform is not enough if the class is not inheriting from ActionListener.
public class MyListener extends ActionListener {
#Override
public void actionPerformed (ActionEvent evt){
//code you want to execute when the event happens
}
public void methodCreatingComboBox(){
ComboBox b = new ComboBox();
b.addActionListener(this);
//other stuffs
}
}
that would work like a charm ! And you can use that same instance of MyListener for multiple events.
Here's the correct answer. I was using com.codename1.ui.Dialog as
the top level window. I switched to using com.codename1.ui.Form
and now the actions are firing as expected.
Something in the environment constructed by Dialog (which extends Form)
is interfering with the event mechanism. Perhaps by design.

How to add actions to a button in java

I have been working with java buttons, and I have created a button ,but when i click the button, I want the shape of the object to change. This is the code I've worked on
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class shapes {
public static void main(String[] a) {
JFrame f = new JFrame("Change shapes");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b = new JButton("Shapes Change");
f.getContentPane().add(b);
f.pack();
f.setVisible(true);
}
Public void paint (Graphics g)
{
//no clue what to do here
}
private static abstract class MyButton extends JButton implements ActionListener {
MyButton()
{
addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b)
{
//no clue what to do here
}
}
}
}
At first, There is a shape created, once the button is clicked it I want to change it to another shape.
There really should be any need to subclass JButton. If you want to customise the button, you could use the Action API instead, see How to Use Actions.
To perform custom painting your should extend a Swing component like JComponent or JPanel and override the paintComponent method...
See Performing Custom Painting for more details.
You would then need to provide some method which you could call to tell the component that the shape should change to how the shape should be changed.
You would then provide a means for your buttons ActionListener to reference the instance of the paint panel and call these methods...
You simply add an ActionListener to the button:
b.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// do some action
}
});
A couple other things to note:
You should not run Swing methods outside the Event Dispatch Thread (EDT) or you may run into unpredictable errors.
Java naming conventions specify that class names should be capitalized. In your code, you named the class "shapes" but it is more proper to name it "Shapes".
First declare and define methods for drawing objects. For example drawSquare (), drawCircle () which draws required shapes. Define radio button or something similar to that to get the users choice (to know which object has to be drawn) . In actionPerformed () check which radiobutton is selected and call the appropriate method for drawing objects and call the repaint () for updating in user interface

ActionListener problem

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.

Categories

Resources