I am working on a GUI and trying to get different buttons to perform different tasks.
Currently, each button is leading to the same ActionListener.
public class GUIController {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new GridLayout(3,3));
JLabel leight =new JLabel("8");
frame.getContentPane().add(leight);
JLabel lfive =new JLabel("0");
frame.getContentPane().add(lfive);
JLabel lthree =new JLabel("0");
frame.getContentPane().add(lthree);
JButton beight =new JButton("Jug 8");
frame.getContentPane().add(beight);
JButton bfive =new JButton("Jug 5");
frame.getContentPane().add(bfive);
JButton bthree =new JButton("Jug 3");
frame.getContentPane().add(bthree);
LISTN ccal = new LISTN (leight,lfive,lthree);
beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);
frame.pack();
frame.setVisible(true);
}
}
my actionlistener file
public class JugPuzzleGUILISTN implements ActionListener {
JLabel leight;
JLabel lfive;
JLabel lthree;
JugPuzzleGUILISTN(JLabel leight,JLabel lfive, JLabel lthree){
this.leight = leight;
this.lfive = lfive;
this.lthree = lthree;
}
public void actionPerformed(ActionEvent e) {
}
}
}
Anything I write in ActionEvent applies to all three buttons, how can I make it so that each button has their own function?
Thank you so much!
how can I make it so that each button has their own function
Add a different ActionListener to each button.
Better yet, use an Action instead of an ActionListener. An Action is just a fancy ActionListener that has a few more properties.
Read the section from the Swing tutorial on How to Use Action for examples of defining inner classes so you can create a unique Action for each button.
Anything I write in ActionEvent applies to all three buttons, how can I make it so that each button has their own function?
You have similar actions which you want all the 3 buttons to be able to trigger. However you also have different functions which you want to implement for each button.
One of the ways will creating 3 more listeners, each to be added to their respective button. So each button now will be added with 2 listeners (your current one + newly created ones).
//Example:
beight.addActionListener(ccal);
bfive.addActionListener(ccal);
bthree.addActionListener(ccal);
beight.addActionListener(ccal_beight);
bfive.addActionListener(ccal_bfive);
bthree.addActionListener(ccal_bthree);
There are other ways such as using if-statements in your current listener to check which button is clicked, but I find separate listeners easier to maintain with lower code coupling.
Related
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 am a fairly new user with programming in Java with about a week and a bit experience, as of before I have been using python for about 3 years but thought to give java a try.
I have been trying to develop my skills by creating small projects and applications and am now creating a small GUI counter.
I have achieved creating the GUI with 2 buttons and a label and have tested the maths behind the application but I am struggling to work out how the ActionListener works as it feels a lot different to python when making a button have a action.
This is My Code;
package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.*;
public class GUI{
//This creates a frame or panel to contain things
public static void main(String[] args) {
//Maths To The Counter
int Counter = 0;
System.out.println(Counter);
Counter =+ 1;
System.out.println(Counter);
//Creating The Frame
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
//Creating The Label
JLabel label3 = new JLabel("Counter: ");
panel.add(label3);
//Button Which should have a funtion to add and display the number
JButton button = new JButton("Click Here.");
panel.add(button);
//Button to reset the counter
JButton buttonReset = new JButton("Reset Counter.");
panel.add(buttonReset);
//Set Size Of Window
frame.setSize(new Dimension(500, 400));
//Set Starting Position to centre
frame.setLocationRelativeTo(null);
//Setting a default close action
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Set Title
frame.setTitle("Counter");
//Disable Resize
frame.setResizable(false);
//Setting if its visible
frame.setVisible(true);
//Fits frame to fit everything
frame.pack();
}
}
enter code here
I know that in python a action is in a function so that has been my logic to this problem however I have seen that I need to use the actionlistener instead and I am struggling to get my head around it.
If Someone could show me how this type of action should be implemented it would be great help, I have watch some youtube videos and done a bit of research but im still struggling to understand in my situation how to do it.
For any confussion im sorry, overall my question is how do I add a action to a button in my program that can implement my maths at the start.
As well any feedback on the structure of my code would be welcomed as I am just starting in java and I do know poor structure can lead to mistakes.
This code should work:
Basically, in the main method I am creating an instance of the class and calling a method to create the gui.
I also created an instance variable as the counter, otherwise you won't be able to update the variable in your action listener.
public class Gui {
private int counter;
// This creates a frame or panel to contain things
public static void main(String[] args) {
Gui gui = new Gui();
gui.create();
}
private void create() {
// Creating The Frame
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
frame.getContentPane().add(panel);
// Creating The Label
JLabel label3 = new JLabel("Counter: ");
panel.add(label3);
// Button Which should have a funtion to add and display the number
JButton button = new JButton("Click Here.");
panel.add(button);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(counter++);
}
});
// Button to reset the counter
JButton buttonReset = new JButton("Reset Counter.");
panel.add(buttonReset);
buttonReset.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
counter = 0;
}
});
// Set Size Of Window
frame.setSize(new Dimension(500, 400));
// Set Starting Position to centre
frame.setLocationRelativeTo(null);
// Setting a default close action
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set Title
frame.setTitle("Counter");
// Disable Resize
frame.setResizable(false);
// Setting if its visible
frame.setVisible(true);
// Fits frame to fit everything
}
}
With Lambda expressions, you can simplify your action listeners as follows:
button.addActionListener(a -> System.out.println(counter++));
buttonReset.addActionListener(a -> counter = 0);
If you want to write more than 1 statement, then you can just put your code in curly brackets:
button.addActionListener(a -> {
System.out.println(counter++);
System.out.println("doing more stuff...");
});
JButton has a function called addActionListener. You can pass on an action listener by doing this:
button.addActionListener(() -> {
// Do some logic here
});
Here, I use a lambda expression as an action listener. Within the lambda expression you can place whatever logic you want to have.
Also note that you can add multiple different action listeners to the same button. In a nutshell, the way the JButton interacts with the ActionListeners is based on the observer-pattern.
Imagine this: When the JButton is pressed, it will notify all of it's observers saying "Hey, I have been pressed". Each observer can then independently decide what to do. In case of the JButton, all observers are ActionListeners. If you add multiple ActionListeners then the JButton will notify all of them, and as a result all of their actionPerformed(ActionEvent e) functions are executed. In the example above, I used a lambda expression which then by java is interpreted as an ActionListener.
Other ways to achieve the exact same functionality are:
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Do some logic here
}
});
In the example above, you use an anonymous class as an actionlistener.
public class MyClass {
public MyClass() {
JButton button = new JButton("press me");
button.addActionListener(new MyActionListener());
}
private class MyActionListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
// Do some logic here
}
}
}
In the example above, an inner class is used.
In a nutshell, there is a ton of ways you can make your button have functionality. Above are just a few examples of how to do so.
Does this clarify it a bit more, or do you have some remaining questions?
I need to create a bank account management program for school, I created the "skeleton" of the first page but I do not understand some things:
How to open a new window with Swing when I click a button?
How can I have different ActionListener for each button?
If I change strategy and I want to use just one big window and let appear and disappear the working text fields/Labels, how would I do it?
Code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
public class CreditUnion extends JFrame
{
//declare buttons
private JButton openAccount;
private JButton closeAccount;
private JButton makeLodgement;
private JButton makeWithdrawal;
private JButton requestOverdraft;
//constructor
public CreditUnion()
{
super("ATM#CreditUnion");
Container c = getContentPane();
c.setLayout(new FlowLayout() );
openAccount = new JButton("Open account");
c. add(openAccount);
closeAccount = new JButton("Close account");
c. add(closeAccount);
makeLodgement = new JButton("Make lodgement");
c. add(makeLodgement);
makeWithdrawal = new JButton("Make withdrawal");
c. add(makeWithdrawal);
requestOverdraft = new JButton("Request overdraft");
c. add(requestOverdraft);
/*create instance of inner class ButtonHandler
to use for button event handling*/
ButtonHandler handler = new ButtonHandler();
openAccount.addActionListener(handler);
closeAccount.addActionListener(handler);
makeLodgement.addActionListener(handler);
makeWithdrawal.addActionListener(handler);
requestOverdraft.addActionListener(handler);
setSize(800,600);
show();
}
public static void main (String args[])
{
CreditUnion app = new CreditUnion();
app.addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}
//inner class for button event handling
private class ButtonHandler implements ActionListener
{
public void actionPerformed (ActionEvent e)
{
JOptionPane.showMessageDialog(null, "You Pressed: " + e.getActionCommand() );
}
}
how to open a new window with Swing when I click a button?
Don't, use a CardLayout, it's less distracting to the user
Have a look at How to use CardLayout for more details
how can I have different ActionListener for each button?
You can use a separate class, inner class or anonymous class depending on what you to achieve
Have a look at Nested classes for more details
if I change strategy and I want to use just one big window and let appear and disappear the working Textfields/Labels, how would I do it
See the first point
1- how to open a new window with Swing when I click a button?
The same way that you would display any window. In the button's ActionListener, create a new window -- I would suggest that you create a JDialog and not a JFrame, but this will depend on your assignment requirements too, and display it
2- how can I have different ActionListener for each button?
Add a different ActionListener to each button. An anonymous inner class (search on this) would work great for this.
3- if I change strategy and I want to use just one big window and let appear and disappear the working Textfields/Labels, how would I do it?
Use a CardLayout to swap "views", usually JPanels with components that you want to swap.
I have been told by my teacher that having a separate class for the actionListener is best. In the separate class, should I just make one actionListener method eg.
public void actionPerformed(ActionEvent e) {
if(e.getSource() == myButton) {
//do something
}
else if(e.getSource() == myComboBox) {
//do something
}
}
or should I make many? I have a feeling I should make many but I have no idea how to go about it. What would the different parameters be? I will be making an instance of this class in my View class where the button and combobox is. (this would be the Controller class as i'm trying to do MVC)
For the button I would like for the background to change colour when the mouse hovers over it and then of course do something when clicked. The combobox simply needs to return whatever option was selected as String.
I prefer to write a separate action listener for each controller action. It keeps things simpler for my simple mind.
My rule of thumb is, for very short (1 - 3 lines) action listeners, I'll make them inline anonymous classes.
For medium size action listeners (1 - 3 methods), I'll make them an inner class, especially if the action listener needs 3 or more fields from the outer main class.
For large action listeners, I'll write a separate class.
When you make a separate class for the action listener, you can reuse the action event you made.
I will give you an example for that
This class have an action listener
class AListener implements ActionListener
{
JTextField tf;
AListener(JTextField tf)
{
this.tf=tf;
}
public void actionPerformed(ActionEvent e)
{
if((e.getActionCommand()).equals("Button1"))
tf.setText("Button1 clicked");
if((e.getActionCommand()).equals("Button2"))
tf.setText("Button2 clicked");
if((e.getActionCommand()).equals("Button3"))
tf.setText("Button3 clicked");
}
}
And this is the GUI class, which has 3 buttons and one text field and each button print something different in the text field, so as you can see, it is not logical to make 3 different action listener methods in the GUI class.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ActionDemo extends JFrame
{
public ActionDemo()
{
setLayout(new FlowLayout());
// Add buttons to the frame
JButton b1=new JButton("Button1");
JButton b2=new JButton("Button2");
JButton b3=new JButton("Button3");
JTextField tf=new JTextField(10);
AListener listen=new AListener(tf);
b1.addActionListener(listen);
b2.addActionListener(listen);
b3.addActionListener(listen);
add(b1);add(b2);add(b3);add(tf);
}
public static void main(String[] args)
{
ActionDemo frame = new ActionDemo();
frame.setTitle("Action Demo");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 100);
frame.setVisible(true);
}
}
So now, every time a button clicked, one action listener method only will be called. Inside this method, I will check which button called me.
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.