So I'm trying to create a button in Java using the Swing library. When you click the button, it's supposed to find the shortest route in a map. Does anybody know how to add in an action listener?
You don't. I do not think this is the best way to go about making a button connected to a map. Check out http://s.goel.im/wDM
If I understand your question,
Does anybody know how to add in an action listener?
Then yes. JButton has addActionListener(ActionListener l). So you create a class that implements ActionListener and then pass an instance of that class to your button. Something like this,
JButton btn = new JButton("Hello");
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Hello clicked"); // <-- or, find the shortest route in a map
}
});
Related
Which way of implementing an ActionListener is more correct?
Is there any major performance differences?
Implementing an ActionListener to the class:
public class MainFrame implements ActionListener {
JButton exampleButton1 = new JButton();
JButton exampleButton2 = new JButton();
JButton exampleButton3 = new JButton();
public MainFrame(){
exampleButton1.addActionListener(this);
exampleButton2.addActionListener(this);
exampleButton3.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
Object src = e.getSource();
if(src.equals(exampleButton1)){
//Do something
}else if(src.equals(exampleButton2)){
//Do something
}else if(src.equals(exampleButton3)){
//Do something
}
}
}
Versus adding ActionListeners to each JButton:
public class MainFrame {
JButton exampleButton1 = new JButton();
JButton exampleButton2 = new JButton();
JButton exampleButton3 = new JButton();
public MainFrame(){
exampleButton1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Do something
}
});
exampleButton2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Do something
}
});
exampleButton3.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
//Do something
}
});
}
}
Or perhaps even using Lambdas..?
I would prefer to use an individual Action as the listener for the button. An Action is a slightly more advanced listener that can be used anywhere an ActionListener can be used.
It provides additional functionality such as:
The same Action can be used by multiple components, such as a JButton, JMenuItem
You can disable the Action, which will disable all components that use the Action
It allows to assign mnemonics and accelerators to your components
See the Swing tutorial on How to Use Actions for more information and examples on this concept.
As you can spot, for single ActionListener-approach there are three more branches for each single if test, which button was pressed. There was nothing done yet, so no real action, just testing which button was pressed.
Now, if you want to achieve high quality work there are metrics like branch coverage. Firstly, If you go for the single ActionListener-approach each of your if is creating two branches. So you have to come up with 6 tests to just test if the base idea of your ActionListener is working correctly, so to find out which button was pressed and the correct if part was used. This is some overhead effort.
Secondly, there is the Single Responsibility Paradigm (SRP). It states that each class should be responsibly for one task only. Now, there are three things this single ActionListener is handling.
Thirdly, the reusage of the single ActionListener is very limited and highly depending on the buttons.
Fourthly, I also call this kind of single ActionListener-approach Manual written Object Orientation, because this would be an approach if there was no object orientation and you have to switch or if/else for calling different methods, like exampleButton1Pressed(), exampleButton2Pressed() etc. But, this can be achieved by three dedicated ActionListeners.
So go for dedicated ActionListeners.
I understand how to create a button and it's application in Java. Would anyone be able to show me the code to be able to make the button in the code below be able to print something as simple as hello world in the terminal. I am using bluej if that is of any matter. I am very sorry I am a beginner coder.
JButton button = new JButton();
button.setActionListener(e -> System.out.println("Clicked"));
This uses a lambda expression. Inside it, you can add as much code as you like, but add it between {} if it's more than a line.
More on buttons here
You need a listener for your button.
JButton button= new JButton("Button");
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Hello World");
}
});
the button will 'listen' for the action and preform whatever task you define for it.
ActionListener is what you are looking for. There is a very nice guide on Oracle's website. You should look into this tutorial and understand different ways of creating ActionListeners. I will give you a simple example which doesn't involve Anonymous Classes because I am not sure of how much you know about them.
public class Frame extends JFrame implements ActionListener {
public Frame() {
super("Test"); // calling the superclass
setLayout(new FlowLayout()); // creating a layout for the frame
setDefaultCloseOperation(EXIT_ON_CLOSE);
// create the button
JButton jbTest = new JButton("Click me!");
/* 'this' refers to the instance of the class
because your class implements ActionListener
and you defined what to do in case a button gets pressed (see actionPerformed)
you can add it to the button
*/
jbTest.addActionListener(this);
add(jbTest);
pack();
}
// When a component gets clicked, do the following
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Hello!");
}
}
private JButton jBtnDrawCircle = new JButton("Circle");
private JButton jBtnDrawSquare = new JButton("Square");
private JButton jBtnDrawTriangle = new JButton("Triangle");
private JButton jBtnSelection = new JButton("Selection");
How do I add action listeners to these buttons, so that from a main method I can call actionperformed on them, so when they are clicked I can call them in my program?
Two ways:
1. Implement ActionListener in your class, then use jBtnSelection.addActionListener(this); Later, you'll have to define a menthod, public void actionPerformed(ActionEvent e). However, doing this for multiple buttons can be confusing, because the actionPerformed method will have to check the source of each event (e.getSource()) to see which button it came from.
2. Use anonymous inner classes:
jBtnSelection.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed();
}
} );
Later, you'll have to define selectionButtonPressed().
This works better when you have multiple buttons, because your calls to individual methods for handling the actions are right next to the definition of the button.
2, Updated. Since Java 8 introduced lambda expressions, you can say essentially the same thing as #2 but use fewer characters:
jBtnSelection.addActionListener(e -> selectionButtonPressed());
In this case, e is the ActionEvent. This works because the ActionListener interface has only one method, actionPerformed(ActionEvent e).
The second method also allows you to call the selectionButtonPressed method directly. In this case, you could call selectionButtonPressed() if some other action happens, too - like, when a timer goes off or something (but in this case, your method would be named something different, maybe selectionChanged()).
Your best bet is to review the Java Swing tutorials, specifically the tutorial on Buttons.
The short code snippet is:
jBtnDrawCircle.addActionListener( /*class that implements ActionListener*/ );
I don't know if this works but I made the variable names
public abstract class beep implements ActionListener {
public static void main(String[] args) {
JFrame f = new JFrame("beeper");
JButton button = new JButton("Beep me");
f.setVisible(true);
f.setSize(300, 200);
f.add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// Insert code here
}
});
}
}
To add an action listener, you just call addActionListener from Abstract Button.
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 am developing a calculator in Java language. The problem is that, i put ten buttons for digits(0,1,2..9) and i want that when i clicked one of them, all perform the same mouse clicked function. Is it possible? In netbeans, it does not let me do that, or i couldnt achieve. Thank you for helping.
Yes. Add the same listener to both buttons you are using.
For example, suppose you are using actionListener then:
public class ListenerClass implements Action{
#override
public void actionPerformed(ActionEvent e) {
//here retrieve information on which button has generated the event
}
}
ListenerClass listener = new ListenerClass();
JButton first = new JButton();
JButton second = new JButton();
first.addActionListener(listener);
second.addActionListener(listener);