JButton array ActionListener - java

In short, I would like to accumulate a bunch of JButton's to an array, and create one ActionListener class for the array.
I'm trying to create a calculator, and all the numbered buttons, such as "6", are in a JButton array, because I would like to have it input the set number into a temporary int, and it would be easier to create one method, instead of 10. I also have 40 other buttons, that I would like to apply the same principal to, but in a different array, so it would be much faster and easier to put these into a couple of ActionListener methods where the buttons data is implemented to that method.
this is the code I have:
private JButton num0, num1, num2, num3, num4, num5, num6, num7, num8, num9;
private JButton numArray[] = {num0, num1, num2, num3, num4, num5, num6, num7, num8, num9};
public GUI(){
numArray.AddActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
}
});
}

You can consider the proposal of Newb Monad. However, you can use the same listener for all your buttons, as in the following example.
public static void main(String[] args) {
ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof JButton) {
String text = ((JButton) e.getSource()).getText();
JOptionPane.showMessageDialog(null, text);
}
}
};
JPanel panel = new JPanel(new GridLayout(4,3));
JButton[] array = new JButton[10];
for (int i = 0; i < array.length; i++) {
array[i] = new JButton(String.valueOf(i));
array[i].addActionListener(listener);
panel.add(array[i]);
}
JOptionPane.showMessageDialog(null, panel);
}

You have the right idea. However, array objects do not have an addActionListener() method. You must add an action listener to each JButton individually. You can use the same listener for every button, but then you have to figure out which button was clicked inside the actionPerformed() method. IMO, a cleaner solution is to assign a separate listener to each JButton because that way each ActionListener can know which number is pressed without checking the source of the event. For example, you can create a NumberButtonListener class which takes an int as the only argument to its constructor. You can then create the JButtons and the corresponding NumberButtonListeners at the same time in a small loop.

This seems to work well for me.
I essentially loop through all of the buttons while checking it against the action (e.getSource()).
public void actionPerformed(ActionEvent e){
//loop through allbuttons to check if clicked
for(int i = 0; i < buttonArr.length; i++){
for(int j = 0; j < buttonArr[0].length; j++){
if(e.getSource() == buttonArr[i][j]){
//do stuff
}
}
}
}

I had a similar problem with a 2D array of buttons for a game of "Connect Four". I was able to use a for loop inside ActionListener to test which of my buttons had been pushed. The key was modifying the toString() method from my button class to supply the array element as a string:
Within the JPanel class definition:
...
discs = new RoundButton[6][7]; //my 2D array
...
public class RoundButton extends JButton {
...
public String toString() {
return "discs["+i+"]["+j+"]";
}
...
}
private class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent event) {
for (int i = 0; i < discs.length; i++){
for (int j= 0; j < discs[i].length; j++){
if (event.getSource() == discs[i][j]){
discs[i][j].setIcon(yellowDisc); //my particular action for that button
}
}
Sorry this is messy. I've never posted on here before.

Related

Comparing the text of different JButtons

I am currently coding a game and part of it consist of having different tiles to be put in a board. I plan on simulating this by having different buttons that will be used to represent the tiles with their corresponding coordinates. For example, one button will say "A1", "A2", etc. What I would like to accomplish, is to have the user click on the "A1" tile and then the button on the board that represents "A1" will change colors, is there any way to go through the buttons on the board and compare its text to the selection of the user? The following is what I used to create the board:
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
panel.add(buttons[r][c]);
}
}
This is what I wrote on the code of one of the tiles
JButton tile1 = new JButton ("A1");
tile1.setBounds(60,725,60,60);
frame.getContentPane().add(tile1);
tile1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String buttonText = tile1.getText();
// iterating through all buttons:
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++)
{
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText))
{
[i][j].setBackground(Color.BLACK);
}
}
}
}
} );
However, it is given me an error saying that there is an action expected after "{"
You may add an action listener to each of the JButton you are creating in the loop like below:
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// your code here
}
} );
Placing the listener in your code may look like
JButton[][] buttons = new JButton[9][12];
JPanel panel = new JPanel(new GridLayout(9,12,5,5));
panel.setBounds(10, 11, 800, 600);
frame.getContentPane().add(panel);
//board
for (int r = 0; r < 9; r++)
{
for (int c = 0; c < 12; c++)
{
buttons[r][c] = new JButton("" + (c + 1) + numberList[r]);
buttons[r][c].setBackground(Color.WHITE);
buttons[r][c].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
String buttonText = button.getText();
// now iterate over all the jbuttons you have
for(int i=0;i<buttons.length;i++){
for(int j=0;j<buttons[0].length;j++){
JButton b = buttons[i][j];
String bText = b.getText();
if(buttonText.equals(bText)){
// you found a match here
// and you have the positions i, j
//
}
}
}
}
} );
panel.add(buttons[r][c]);
}
}
And you could store the the colors to be changed to in global static array, and use that array in your action listener.
For information on adding listener to the JButton, you may refer this thread How do you add an ActionListener onto a JButton in Java
Hope this helps!
You need listeners.
Implement ActionListener to your class. This will require you to add public void actionPerformed(ActionEvent e) {} to your class.
Every JButton you use should have an action listener.
Apply one like that:
JButton but = new JButton();
but.addActionListener(this);
Finally, in the actionPerformed method we added, you need to add something like that:
public void actionPerformed(ActionEvent e) {
if (e.getSource() == but)
but.setBackground(Color.BLACK);
}
P.S. you can get a button's text value by the means of:
but.getText();

Adding ToggleButton value to an array in java

I need to create a lottery program that will allow user to select 4 numbers (image of the buttons here)
which then should be inputed into an array, I cannot get the array to fill fully, I have tried different versions of adding an int into array and I just can't seem to find the right one..
int hold;
int userNumbers[] = new int[3];
public lotteryGUI() {
initComponents();
}
private void twentyoneActionPerformed(java.awt.event.ActionEvent evt) {
hold = 21;
hold += userNumbers[0];
}
private void nineActionPerformed(java.awt.event.ActionEvent evt) {
hold = 9;
userNumbers[0]= hold + userNumbers[0];
}
private void oneActionPerformed(java.awt.event.ActionEvent evt) {
hold = 1;
userNumbers[0] = userNumbers[0] + hold ;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(Arrays.toString(userNumbers));
}
This is just a sample with 3 buttons, As you can probably tell the output i get is (10,0,0).
#edit
I have contacted my lecturer about this project and I received a little hint. I am supposed to add ActionListener and if the button is checked I am supposed to add it to an array. Not really sure how to do that, I'm going to look at some tutorials and edit this post if necessary
I would hate to hard code it, but it is really up to you to figure out how to do that for 28 buttons. Here is example for 1 button:
int counter = 0;
int[] userNumbers = new int[3];
public lotteryGUI() {
initComponents();
JButton number1 = new JButton("1");
JButton number2 = new JButton("2");
number1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
userNumbers[counter] = 1;
counter = counter + 1;
if (counter == 3)
// disable all buttons and display result maybe?
}
}
// ... the rest 27 buttons maybe?
}

gridLayout of JButtons, actionListener for each JButton

I have a gridLayout of JButtons. I'd like to distinguish every JButton from each other in the actionPerformed function.
I don't want to "name" each JButton. The user press a JButton randomly. Is there any method to know which button has been pressed?
It is possible?
[....]
tUsuariCPU = new JButton[mida][mida];
for (int i=0;i<size;i++){
for (int j=0;j<size;j++){
JButton temp = new JButton();
tUsuariCPU[i][j] = temp;
temp.addActionListener(this);
panel.add(temp);
}
}
}
public void actionPerformed(ActionEvent e) {}
[....]
}
If you wish to use a single ActionListener, you can check which Component fired the event by using the getSource button and comparing the instance to the JButton instances. Below uses a loop to loop over the 2D array of JButtons:
public void actionPerformed(ActionEvent e) {}
for ( int i = 0; i < tUsuariCPU.length; i++ ){
for ( int j = 0; j < tUsuariCPU[i].length; j++ ){
if ( e.getSource() == tUsuariCPU[i][j] ){
//do something
}
}
}
}
Alternatively, you can add a single ActionListener per button, or set the ActionCommand of the JButton and use this value to determine which JButton fired the event (e.getActionCommand().equals(myButton.getActionCommand()))

Prints whole array not single value in Java Applet

this is a telephone keypad applet.....
I am having issues with my applet it seems to be printing the the whole array up to the chosen number I would like it only to print the chosen number like what happens on a cell phone when you dial a number. Can anyone see where I went wrong? Thanks in advanced!
import java.awt.*;
import java.awt.event.*;
public class Telephone extends Frame implements ActionListener
{
Button keys[];
Panel keypad;
TextField lcd;
Label value;
boolean foundKey;
public Telephone()
{
lcd =new TextField(20);
lcd.setEditable(false);
keypad= new Panel ();
keys= new Button[13];
//construct and assign captions to the buttons
for (int i=0; i<=9; i++)
keys[i] = new Button(String.valueOf(i));
keys[10] =new Button ("*");
keys[11] =new Button ("0");
keys[12] =new Button ("#");
setBackground(Color.magenta);
setLayout(new BorderLayout());
keypad.setLayout(new GridLayout(4,3,10,10));
//add keys
for(int i=1; i<=3; i++)//1,2,3
keypad.add(keys[i]);
for (int i=4; i<=6; i++)//4,5,6
keypad.add(keys[i]);
for (int i=7; i<=9; i++)//7,8,9
keypad.add(keys[i]);
keypad.add(keys[10]);
keypad.add(keys[11]);
keypad.add(keys[12]);
for (int i=0; i<keys.length; i++)
keys[i].addActionListener(this);
//add componets to display
add(lcd, BorderLayout.NORTH);
add(keypad,BorderLayout.CENTER);
//add()
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
}//constructor ends
public void actionPerformed(ActionEvent e)
{
foundKey = false;
for (int i=0; i<keys.length &&!foundKey;i++)
{
if(e.getSource() == keys[i])
foundKey=true;
//switch(i)
//{
// case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:case 10:case 11:case 12:
lcd.setText(lcd.getText()+ keys[i].getLabel());
// break;
// }//end switch
}//end for
}//end actionPerformed
public static void main(String args[])
{
Telephone f = new Telephone();
f.setTitle("Telephone Application");
f.setBounds(50,130,250,300);
f.setVisible(true);
}
}//class ends
As your statement
if(e.getSource() == keys[i])
has no brackets, only the next statement will be conditionally executed:
foundKey=true;
. But the statement
lcd.setText(lcd.getText()+ keys[i].getLabel());
will be printed, regardless of the if-condition.
Solution: Learn to always put brackets on if, switch, while, for and so on.

New to JButtons, how to make them preform an event?

Basically, what I have are 2 arrays. One array of JButtons 26 long, one array of Strings with each letter of the alphabet, and a for loop to create a button for each letter of the alphabet and insert it into the JButton array:
JButton[] buttons = new JButton[26];
String letters[]{"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(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
panel.add(buttons[i]);
}
What I want to do is create an event for all the buttons. Whenever a button is pressed, whatever letter it coincides with will be set as the value for a String called guess.
So far I understand that I need to do something like this:
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Insert what I want to happen
}
});
My problem is with where I wrote x. I am not sure what to put there. I need this to work for all 26 buttons in the array...
Sorry if this seems obvious/simple. I am obviously new to java and I just don't understand how JButtons work and how to do this.
Define an ActionListener like shown below.
ActionListener aListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent event){
//find the actioncommand and do what is required.
}
};
Associate this ActionListener to every button.
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
buttons[i].setActionCommand(letters[i]);
buttons[i].addActionListener(aListener);
panel.add(buttons[i]);
}
Just test the actionCommand which is a String value and compare it with a the letter, and do something.
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("A")
// do something
else if (e.getActionCommand().equals("B")
// do soemthing
...
...
}
});
I prefer to use a switch though for cases like this.
public void actionPerformed(ActionEvent e){
String letter = e.getActionCommand();
switch(letter) {
case "A" : do something; break;
case "B" : do something; break;
case "C" : do something; break;
...
...
}
}

Categories

Resources