1

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]);
}
Roman C
  • 49,761
  • 33
  • 66
  • 176
Night Programmer
  • 237
  • 1
  • 5
  • 14
  • to define an array of buttons from A-Z u need not to define an array of String. You can do it simply initializing `char title = 'A';`. And then iterating your loop to 26 and incrementing `title = title + 1;`. I didn't get the question u asked bytheway. – pratikabu Aug 24 '12 at 11:30
  • 2
    unrelated (to the question you forgot to ask :-) _never-ever_ do any manual sizing/locating of components, that's the exclusive task of a LayoutManager – kleopatra Aug 24 '12 at 12:11
  • 1
    See also this [alternative way to initialize button names](http://stackoverflow.com/a/12024012/230513). – trashgod Aug 24 '12 at 15:00

5 Answers5

2
  • ActionListener can return (every Listeners in Swing) Object that representing JButton

  • from this JButton you can to determine, getActionCommand() or getText()

mKorbel
  • 109,525
  • 20
  • 134
  • 319
2

I wasn't sure exactly what you question was, so I have a few answers:

  1. If you want to pull the button creation into a method - see the getButton method in the example

  2. 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.

  3. 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();
            }
        });
    }   
}
Nick Rippe
  • 6,465
  • 14
  • 30
1

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.

Thomas
  • 87,414
  • 12
  • 119
  • 157
0

try change in Action listener to this

 JOptionPane.showMessageDialog(null, "You have clicked: "+((JButton)e.getSource()).getText());
Nirmal- thInk beYond
  • 11,847
  • 8
  • 35
  • 46
0

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

       }


   });
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75