Two listeners for one event? - java

I am trying to create a file according to two events:
the first is a JRadioButton: according to which radio button is selected, the file will be saved in the respective folder, the second event is the "add" button. I am struggling with creating the file in the right folder, so far I managed to create the file in the right folder when the radio button is selected, but that is not what I want.
How can I create the file at the right moment (when "add" button is pressed) according to the previously selected radio button?
Things like:
if(e.getSource() == button && e.getActionCommand() == jradio1)
Doesn't work and neither deos nested if.
I think I'm missing the big picture, anyone can help?

You could create a object that stores the location (possibly a String containing the filepath) of where you want the file, and which will update when you click on a given jradiobutton.
When you click the add button, you can then reference the same object to see where you should put the file.

Selected radio and the event that is fired when you select the radio button are two different thing.
From what you have have stated is that you want to create the file on click of the add button.
Do this
You can just ignore the event fired on the radio selection.
When the event is fired on the press of the Add button, read the state of the
radio and save the file
You can keep the instance of the radio class wide so that you can read it in the event handler for the button listener.

Just use the name of the Radio button as the action command. Same for the Add button. When the radio button is selected, it saves its name as the target location. Here is an example of how it can work.
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingUtilities;
public class SavingFiles extends JPanel {
String selectedLocation = null;
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new SavingFiles().start());
}
public void start() {
String[] fileLocations =
{ "f:/location1", "c:/location2", "G:/location3"
}; // etc
int nRadioButtons = fileLocations.length;
int defaultLoc = 0;
YourActionListener listener = new YourActionListener();
ButtonGroup group = new ButtonGroup();
for (int i = 0; i < nRadioButtons; i++) {
if (i == defaultLoc) {
selectedLocation = fileLocations[i];
}
JRadioButton button =
new JRadioButton(fileLocations[i], i == defaultLoc);
group.add(button);
button.addActionListener(listener);
// do something with button
// store it or add it to panel.
add(button);
}
JButton addButton = new JButton("Add"); // also acts as actionCommand
addButton.addActionListener(listener);
add(addButton);
// Boiler plate
JFrame frame = new JFrame("SavingFiles");
frame.add(this);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(300, 80));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Note that if actionCommand is not set, then the button name
// serves the same function.
private class YourActionListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
String actionCommand = ev.getActionCommand();
if (actionCommand.equals("Add")) {
// add file to 'selectedLocation'
System.out.println("adding file to " + selectedLocation);
}
else {
selectedLocation = actionCommand;
System.out.println("Location set to " + selectedLocation);
}
}
}
}

Related

Most efficient way of using an action listener in Java?

I was tasked with creating a program that displays a numeric keypad (like one on a phone) and has a screen that displays the numbers that are picked. Also included is a clear button that clears the screen.
In creating my program, I created three classes. The Phone class simply creates a JFrame that adds a PhonePanel to the screen. The PhonePanel class adds a JLabel which acts as a screen, a JButton which acts as a clear button, and a KeypadPanel which is a GridLayout of JButtons which acts as the numeric keys.
The clear button and numeric buttons both use separate action listeners. Is this the most efficient way of going about this? Is there a way I can use one action listener instead of two?
// ******************************************************************************************
// Phone.java
// David Read
// This class creates a JFrame that contains a PhonePanel. The PhonePanel provides a
// user interface that allows one to input numeric symbols on a screen and allows clearing
// of the screen.
// ******************************************************************************************
package lab5;
import javax.swing.JFrame;
public class Phone {
public static void main(String[] args)
{
// Create a JFrame object.
JFrame frame = new JFrame ("Phone");
// Set the default close operation for the JFrame.
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Add a Phone panel to the screen.
frame.getContentPane().add(new PhonePanel());
frame.pack();
frame.setVisible(true);
}
}
// ******************************************************************************************
// PhonePanel.java
// David Read
// This class creates a JPanel that includes an output label which displays inputed numeric
// symbols, a clear button that clears what is displayed on the output label, and a KeypadPanel
// which displays a GridLayout of buttons that when pressed, display their corresponding symbols
// on the output label.
// ******************************************************************************************
package lab5;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class PhonePanel extends JPanel
{
private static JLabel labelOutput;
private JButton buttonClear;
//-----------------------------------------------------------------------
// Creates a JPanel that arranges three objects in a Border layout. The
// north component contains a JLabel, the east component contains a JButton
// and the center component contains a KeypadPanel.
//-----------------------------------------------------------------------
public PhonePanel()
{
// Set the layout manager, size and background color of the Phone Panel.
setLayout(new BorderLayout());
setPreferredSize (new Dimension(400, 200));
setBackground (Color.yellow);
// Output label created.
labelOutput = new JLabel(" ");
// Clear button created, assigned a button title and assigned an action listener.
buttonClear = new JButton();
buttonClear.setText("Clear");
buttonClear.addActionListener(new ClearButtonListener());
// Add the JLabel, JButton and KeypadPanel to the PhonePanel.
add(labelOutput, BorderLayout.NORTH);
add(buttonClear, BorderLayout.EAST);
add(new KeypadPanel(), BorderLayout.CENTER);
}
//-----------------------------------------------------------------------
// Adds the specified symbol to the output label.
//-----------------------------------------------------------------------
public static void addToOutputLabel(String input)
{
// Create a String object to hold the current value of the output label.
String label = labelOutput.getText();
// Append the inputed String onto the String.
label += input;
// Update the output label with the appended String.
labelOutput.setText(label);
}
//-----------------------------------------------------------------------
// Listens for the clear button to be pressed. When pressed, the output
// label is reassigned as blank.
//-----------------------------------------------------------------------
private class ClearButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
labelOutput.setText(" ");
}
}
}
// ******************************************************************************************
// KeypadPanel.java
// David Read
// This class creates a JPanel that contains several buttons which when pressed, adds their
// corresponding numeric symbol to the output label in the PhonePanel.
// ******************************************************************************************
package lab5;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class KeypadPanel extends JPanel
{
private JButton button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonStar, button0, buttonNumber;
//-----------------------------------------------------------------------
// Creates a JPanel that arranges several JButtons in a GridLayout. Each
// of the buttons are assigned button titles, action listeners and
// action commands.
//-----------------------------------------------------------------------
public KeypadPanel()
{
// Set layout to a GridLayout with 4 rows and 3 columns.
setLayout(new GridLayout(4,3));
// Create new JButtons.
button1 = new JButton();
button2 = new JButton();
button3 = new JButton();
button4 = new JButton();
button5 = new JButton();
button6 = new JButton();
button7 = new JButton();
button8 = new JButton();
button9 = new JButton();
buttonStar = new JButton();
button0 = new JButton();
buttonNumber = new JButton();
// Assign button titles to the JButtons.
button1.setText("1");
button2.setText("2");
button3.setText("3");
button4.setText("4");
button5.setText("5");
button6.setText("6");
button7.setText("7");
button8.setText("8");
button9.setText("9");
buttonStar.setText("*");
button0.setText("0");
buttonNumber.setText("#");
// Create a new KeypadButtonListener.
KeypadButtonListener listener = new KeypadButtonListener();
// Assign the listener as an action listener for all of the JButton objects.
button1.addActionListener(listener);
button2.addActionListener(listener);
button3.addActionListener(listener);
button4.addActionListener(listener);
button5.addActionListener(listener);
button6.addActionListener(listener);
button7.addActionListener(listener);
button8.addActionListener(listener);
button9.addActionListener(listener);
buttonStar.addActionListener(listener);
button0.addActionListener(listener);
buttonNumber.addActionListener(listener);
// Set the action commands for all of the JButtons.
button1.setActionCommand("1");
button2.setActionCommand("2");
button3.setActionCommand("3");
button4.setActionCommand("4");
button5.setActionCommand("5");
button6.setActionCommand("6");
button7.setActionCommand("7");
button8.setActionCommand("8");
button9.setActionCommand("9");
buttonStar.setActionCommand("*");
button0.setActionCommand("0");
buttonNumber.setActionCommand("#");
// Add the JButtons to the KeypadPanel.
add(button1);
add(button2);
add(button3);
add(button4);
add(button5);
add(button6);
add(button7);
add(button8);
add(button9);
add(buttonStar);
add(button0);
add(buttonNumber);
}
//-----------------------------------------------------------------------
// Listens for all of the buttons to be pressed. When a particular button
// is pressed, the addToOutputLabel method of the PhonePanel is called
// with the input being the action command of the button pressed.
//-----------------------------------------------------------------------
private class KeypadButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
// Add the action command string to the output label.
PhonePanel.addToOutputLabel(e.getActionCommand());
}
}
}
In this case it is better to use two separate action listeners as functionality for clear button and for number buttons is different.
It is considered as best practice to use single responsibility principle (https://en.wikipedia.org/wiki/Single_responsibility_principle) when developing your classes. This will make your code more maintainable and easier to read and modify.
It is better to use multiple ActionListeners here, however, if you still desire to use one ActionListener instead you may make a separate class to handle all actions similar to this.
public class KeyListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
//Get the name of the ActionEvent
String cmd = e.getActionCommand();
//Here the Actionevent is only checked to see if it is a "Clear" or not
//If you need to impliment more then a switch statment may be appropriate
if(cmd.equals("Clear")) {
//Clear Label with additional setter method
PhonePanel.clearLabel();
}
else {
PhonePanel.addToOutputLabel(e.getActionCommand());
}
}

Returning result from the first clicked Jbutton from multiple JButtons java swing

Basically I have n JButtons. If any of them is clicked, they return a certain number.
I have a menu with each of the buttons and when the user clicks one, my menu method returns the number returned by the Button handler. Is it possible?
Something like:
frame.add(button1..)
frame.add(button2..)
frame.add(button3..)
if (button1.isClicked()) {
return button1ActionHandler();
} else if (button2.isClicked()) {
return button2ActionHandler();
} else if (button3.isClicked()) {
return button3ActionHandler();
}
The problem is, the code is not waiting for me to click a button so it won't enter in any of those if's. What can I do for the program to wait for click and how can I check if a button is clicked?
Start by having a look at How to Use Buttons, Check Boxes, and Radio Buttons and How to Write an Action Listeners.
Remember, a GUI is an event driven environment, that is, something and then you respond to it.
You need to register an ActionListener against each button, when the button is triggered, you need to take appropriate action.
There are a number of ways you could achieve this, you could set the actionCommand of the buttons with appropriate information that you can use to ascertain what should be done when the button is clicked. You could use the source property of the ActionEvent to determine the source of the event and take appropriate action, as exampels
It sounds like you want to present the user with several options, let him choose one of the options, and then have him press a "submit" button to submit that option to the program. If so, then I think that your best bet is to use JRadioButtons, all added to a ButtonGroup -- this allows only one of the radio buttons to be selected at any time, or use a JComboBox. Either way, it would be easy to extract the information regarding which selection the user made. If you use the first option, use of JRadioButtons, ButtonGroup and a "submit" button, you simply get the selected ButtonModel from the ButtonGroup by calling its getSelection() method, and then extract the actionCommand String from this model by calling getActionCommand(). If you decide on the second option, use of a JComboBox together with a "submit" button, then simply call getSelectedItem() on the JComboBox within your submit button's ActionListener.
Below I show you both options. Note that my submit button doesn't use an ActionListener but rather an AbstractAction, which is kind of like an ActionListener on steroids.
import java.awt.event.ActionEvent;
import javax.swing.*;
public class SelectionEg extends JPanel {
private static final String[] SELECTIONS = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday"};
private ButtonGroup buttonGroup = new ButtonGroup();
private JComboBox<String> selectionComboBox = new JComboBox<>(SELECTIONS);
public SelectionEg() {
for (String selection : SELECTIONS) {
JRadioButton radioButton = new JRadioButton(selection);
radioButton.setActionCommand(selection);
add(radioButton);
buttonGroup.add(radioButton);
}
add(selectionComboBox);
add(new JButton(new SubmitAction("Submit")));
}
private class SubmitAction extends AbstractAction {
public SubmitAction(String name) {
super(name);
putValue(MNEMONIC_KEY, (int) name.charAt(0));
}
#Override
public void actionPerformed(ActionEvent e) {
ButtonModel model = buttonGroup.getSelection();
if (model == null) {
// nothing selected yet, ignore this
return;
}
String message = "The selected radio button is: " + model.getActionCommand();
System.out.println(message);
message = "The selection from the combo box is: " + selectionComboBox.getSelectedItem();
System.out.println(message);
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("Selelection Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new SelectionEg());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}

How to turn off a key listener in NetBeans wizard panels?

I developed a simple plugin for NetBeans IDE. I have a little problem with default key event on TopComponenet of Wizard panel:
For example:
I have a wizard with 3 steps. In second step I have a JTextField where user put some values and after that appear a JList below this text field. Everything is okay until user choose a some value from list and than press key ENTER then my panel goes to next Step 3. I attach a key listener to list something like:
list = new JList(new PackagesListModel());
list.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(java.awt.event.KeyEvent evt) {
int keyCode = evt.getKeyCode();
if(keyCode == KeyEvent.VK_ENTER){
JList list = (JList)evt.getSource();
Object selectedPackage = list.getSelectedValue();
typePackageField.setText((String)selectedPackage);
}
}
});
But this listener probably is invoking after default listener of TopComponenet on wizard. How can I prevent moving user to next step using ENTER key?
I don't want this action (when user press ENTER then they go to the next step).
UPDATE:
Forwarding to Kraal answer:
Problem is that i dont know where i can lookking for a JButton Next (to shuting down a listener). It sound strange but how i wrote. Im using a Netbeans Plaform WizzardDescriptor to generate a Wizzard (with 3 steps) . WizzardDescriptor is from package:
org.openide.WizardDescriptor; // Dialogs API
i puted to him a 3 instances of panels: WizardDescriptor.Panel from same package:
org.openide.WizardDescriptor // Dialogs API
it looks like:
panels = new ArrayList<>();
panels.add(new LayoutWizardPanel1(selectedLayout));
panels.add(new LayoutWizardPanel2(selectedLayout));
panels.add(new LayoutWizardPanel3(selectedLayout));
WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<>(panels));
After this will generated something like:
in my program i have access to WizardDescriptor
http://bits.netbeans.org/dev/javadoc/org-openide-dialogs/org/openide/WizardDescriptor.html
I'm not sure but if you know which JComponent causes this behaviour, try this:
suspectedComponent.getInputMap().put(KeyStroke.getKeyStrokeForEvent(KeyEvent.VK_ENTER),"none");
To check which keystrokes are bound on a JComponent:
suspectedComponent.getInputMap().keys()
Or in the parent InputMap:
suspectedComponent.getInputMap().getParent().keys()
See the docs for InputMap for details.
Everything is okay until user choose a some value from list and than press key ENTER then my panel goes to next Step 3. I attach a key
listener to list something like [...]
If you want Enter key in your list has precedence over the default Next -> button then you have to use Key binding to attach an action to your list when it's focused:
KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
Action updateTextfieldAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
JList list = (JList)evt.getSource();
Object selectedPackage = list.getSelectedValue();
typePackageField.setText((String)selectedPackage );
}
};
list = new JList(new PackagesListModel());
list.getInputMap().put(enterKeyStroke, "enter");
list.getActionMap().put("enter", updateTextfieldAction);
Note that getInputMap() is a shortcut for getInputMap(JComponent.WHEN_FOCUSED). This means that if your list has focus and Enter key is pressed, then the action attached to this key stroke will be performed.
By this way your action will always have precedence over the next button's action, either if this button is the default button or it has attached an action using key bindings using WHEN_IN_FOCUSED_WINDOW like this:
JButton button = new JButton(nextStepAction);
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKeyStroke, "enter");
button.getActionMap().put("enter", nextStepAction);
Where nextStepAction would be the action to go to wizard's next step.
See also Key bindings vs. key listeners in Java
Example
Please cosider the example below. Note if you focus another component but list the the default action is performed. I've set the button as frame's root pane default button and I've attached an action using WHEN_IN_FOCUSED_WINDOW just to prove that WHEN_FOCUSED action has precedence over those.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
public class Demo {
private JList list;
private JTextField textField;
private void createAndShowGUI() {
KeyStroke enterKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0);
Action nextStepAction = new AbstractAction("Next") {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Going to step 3!", "Message", JOptionPane.INFORMATION_MESSAGE);
}
};
Action updateTextfieldAction = new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
textField.setText((String)list.getSelectedValue());
}
};
list = new JList(new String[]{"Item 1", "Item 2", "Item 3"});
list.setPrototypeCellValue("This is a list's prototype cell value.");
list.getInputMap().put(enterKeyStroke, "enter");
list.getActionMap().put("enter", updateTextfieldAction);
textField = new JTextField(15);
JPanel listPanel = new JPanel();
listPanel.add(new JScrollPane(list));
listPanel.add(textField);
JButton button = new JButton(nextStepAction);
button.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(enterKeyStroke, "enter");
button.getActionMap().put("enter", nextStepAction);
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
buttonsPanel.add(button);
JFrame frame = new JFrame("Demo");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.add(listPanel);
frame.add(buttonsPanel, BorderLayout.PAGE_END);
frame.getRootPane().setDefaultButton(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Demo().createAndShowGUI();
}
});
}
}
Other comments
Please note that if you want avoid all this matter, you could attach a ListSelectionListener to your list and update the text field on selection change with no need to press Enter key at all. In fact if you have access to the next step action you could enable/disable it based on list selection. By doing this you'll be sure that wizard can't continue if no item is selected in your list. IMHO that would be a more elegant way to handle this situation. See Selecting Items in a List for further details.

Return the choice from an array of buttons

I've got an array that creates buttons from A-Z, but I want to use it in a
Method where it returns the button pressed.
this is my original code for the buttons:
String b[]={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(i = 0; i < buttons.length; i++)
{
buttons[i] = new JButton(b[i]);
buttons[i].setSize(80, 80);
buttons[i].setActionCommand(b[i]);
buttons[i].addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
String choice = e.getActionCommand();
JOptionPane.showMessageDialog(null, "You have clicked: "+choice);
}
});
panel.add(buttons[i]);
}
I wasn't sure exactly what you question was, so I have a few answers:
If you want to pull the button creation into a method - see the getButton method in the example
If you want to access the actual button when it's clicked, you can do that by using the ActionEvent.getSource() method (not shown) or by marking the button as final during declaration (shown in example). From there you can do anything you want with the button.
If you question is "How can I create a method which takes in a array of letters and returns to me the last clicked button", you should modify you question to explicitly say that. I didn't answer that here because unless you have a very special situation, it's probably not a good approach to the problem you're working on. You could explain why you need to do that, and we can suggest a better alternative.
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TempProject extends Box{
/** Label to update with currently pressed keys */
JLabel output = new JLabel();
public TempProject(){
super(BoxLayout.Y_AXIS);
for(char i = 'A'; i <= 'Z'; i++){
String buttonText = new Character(i).toString();
JButton button = getButton(buttonText);
add(button);
}
}
public JButton getButton(final String text){
final JButton button = new JButton(text);
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "You have clicked: "+text);
//If you want to do something with the button:
button.setText("Clicked"); // (can access button because it's marked as final)
}
});
return button;
}
public static void main(String args[])
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setContentPane(new TempProject());
frame.pack();
frame.setVisible(true);
new TempProject();
}
});
}
}
ActionListener can return (every Listeners in Swing) Object that representing JButton
from this JButton you can to determine, getActionCommand() or getText()
I'm not sure what exactly you want, but what about storing the keys in a queue (e.g. a Deque<String>) and any method that needs to poll the buttons that have been pressed queries that queue. This way you would also get the order of button presses.
Alternatively, you could register other action listeners on each button (or a central one that dispatches the events) that receive the events in the moment they are fired. I'd probably prefer this approach, but it depends on your exact requirements.
try change in Action listener to this
JOptionPane.showMessageDialog(null, "You have clicked: "+((JButton)e.getSource()).getText());
1. First when you will be creating the button, please set the text on them from A to Z.
2. Now when your GUI is all ready, and you click the button, extract the text on the button, and then display the message that you have clicked this button.
Eg:
I am showing you, how you gonna extract the name of the button pressed, i am using the getText() method
butt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(null, "You have clicked: "+butt.getText());
}
});

java detect clicked buttons

I have multiple panels on a JFrame window. I am going to populate each panel differently every time. For example:
i start the GUI: (image center panel, right panel, bottom panel). Center panel is populated with 20 buttons, right panel with 10 buttons and bottom panel with 3.
second start of the GUI (same gui). Center panel has 50 buttons, right panel has 12 buttons, bottom has 3.
So everytime there is a random number of buttons, impossible to be all uniquely named.
Given the fact that I don't have a unique name for each button (just a list) I would like to know which buttons were clicked according to the panel they belong to. is that possible?
Somehow the buttons are being created; Let's assume you are somehow numbering them in a way you can retrieve later.
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.List;
import java.util.ArrayList;
import javax.swing.JButton;
public class ButtonTest extends JFrame implements ActionListener {
public ButtonTest() {
super();
initGUI();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
private final List<JButton> buttons = new ArrayList<JButton>();
private static final int NUM_BUTTONS = 20;
public void initGUI() {
JPanel panel = new JPanel();
for (int i = 0; i < NUM_BUTTONS; i++) {
String label = "Button " + i;
JButton button = new JButton(label);
button.setActionCommand(label);
button.addActionListener(this);
buttons.add(button);
panel.add(button);
}
getContentPane().add(panel);
}
public static void main(String[] args) {
new ButtonTest();
}
public void actionPerformed(ActionEvent e) {
String actionCommand = ((JButton) e.getSource()).getActionCommand();
System.out.println("Action command for pressed button: " + actionCommand);
// Use the action command to determine which button was pressed
}
}
The ActionEvent has a getSource() method which will be the reference to the button that was clicked. You can then check the action command of the button if you need to.
If you want to know which panel contains the button, try calling getParent() on the JButton itself. To find out which button was clicked, as camickr suggests, use getSource() on the ActionEvent.

Categories