midrigs
midrigs

Reputation: 65

ActionListener for Buttons

So I have developed a program for a class of mine to use ActionListener for events when a button is clicked. I have the program working however when clicking any button you have to click the input buttons multiple times for the answer to register and move to the next level of the program.

example1: Alert button open's 2 sometimes 3 "Hey There's a bug on you!" message dialogs.

example2: Yes/No prompts you 3-4 times to return your yes/no answer to txt.

example3: Color takes 3/4 clicks before returning the input to txt.

(I think you get the picture...)

For the life of me I cannot find out why it won't just take one input and move on...

The code of my program for your review... Thank you in advanced.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MessageBoxes{

  private JButton alert = new JButton("Alert");
  private JButton yesNo = new JButton("Yes/No");
  private JButton color = new JButton("Color");
  private JButton vals = new JButton("3 Vals");
  private JButton input = new JButton("Input");

  private JTextField txt = new JTextField(15);

  private JFrame frame;

  private ActionListener al = new ActionListener(){
    public void actionPerformed(ActionEvent e){

    alert.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            JOptionPane.showMessageDialog(null,
                                  "There's a bug on you!", "Hey!",
                                  JOptionPane.ERROR_MESSAGE);
        }
    });  

    yesNo.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            int val = JOptionPane.showConfirmDialog(null,
                                  "Choose yes or no", "Your Call...",
                                  JOptionPane.YES_NO_OPTION);

            if(val != JOptionPane.CLOSED_OPTION){
              if(val == 0){
                txt.setText("Yes");
            }
            else{
                txt.setText("No");
            }
            }
        }
    });  

    color.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            Object[] options = {"Red", "Green"};

            int sel = JOptionPane.showOptionDialog(null,
                            "Choose a Color!", "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE, null,
                                        options, options[0]);

            if(sel != JOptionPane.CLOSED_OPTION){
                txt.setText("Color Selected: " + options[sel]);
            }
        }
    });  

    vals.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            Object[] selections = {"First", "Second", "Third"};

            Object val = JOptionPane.showInputDialog(null,
                                             "Choose one", "Input",
                                             JOptionPane.INFORMATION_MESSAGE,
                                             null, selections, selections[0]);

            if(val != null){
                txt.setText(val.toString());
            }
        }
    });

    input.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e)
        {
            //Execute when button is pressed
            String val = JOptionPane.showInputDialog("How mant fingers do you see?");

                txt.setText(val);
        }
    });  
  }
  };



  public MessageBoxes(){

    frame = new JFrame("Title");

    frame.setSize(250, 250);

    frame.getContentPane().setLayout(new FlowLayout());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(alert);
    frame.getContentPane().add(yesNo);
    frame.getContentPane().add(color);
    frame.getContentPane().add(vals);
    frame.getContentPane().add(input);
    frame.getContentPane().add(txt);

    frame.setVisible(true);

  }

  public void launchJFrame(){

    alert.addActionListener(al);
    yesNo.addActionListener(al);
    color.addActionListener(al);
    vals.addActionListener(al);
    input.addActionListener(al);

}

 public static void main(String [] args){

    MessageBoxes messageBoxes = new MessageBoxes();
    messageBoxes.launchJFrame();
 }
}

Upvotes: 2

Views: 2643

Answers (3)

midrigs
midrigs

Reputation: 65

Here is the solution I found works best for me:

private ActionListener alertAction = new ActionListener(){
  public void actionPerformed(ActionEvent e){
    //Execute when button is pressed
            JOptionPane.showMessageDialog(null,
                                  "There's a bug on you!", "Hey!",
                                  JOptionPane.ERROR_MESSAGE);
}
};

private ActionListener yesNoAction = new ActionListener(){
  public void actionPerformed(ActionEvent e){
    //Execute when button is pressed
            //Execute when button is pressed
            int val = JOptionPane.showConfirmDialog(null,
                                  "Choose yes or no", "Your Call...",
                                  JOptionPane.YES_NO_OPTION);

            if(val != JOptionPane.CLOSED_OPTION){
              if(val == 0){
                txt.setText("Yes");
            }
            else{
                txt.setText("No");
            }
            }
}
};

private ActionListener colorAction = new ActionListener(){
  public void actionPerformed(ActionEvent e){
    //Execute when button is pressed
            Object[] options = {"Red", "Green"};

            int sel = JOptionPane.showOptionDialog(null,
                            "Choose a Color!", "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE, null,
                                        options, options[0]);

            if(sel != JOptionPane.CLOSED_OPTION){
                txt.setText("Color Selected: " + options[sel]);
            }
}
};

private ActionListener valsAction = new ActionListener(){
  public void actionPerformed(ActionEvent e){
    //Execute when button is pressed
            Object[] selections = {"First", "Second", "Third"};

            Object val = JOptionPane.showInputDialog(null,
                                             "Choose one", "Input",
                                             JOptionPane.INFORMATION_MESSAGE,
                                             null, selections, selections[0]);

            if(val != null){
                txt.setText(val.toString());
            }
}
};

private ActionListener inputAction = new ActionListener(){
  public void actionPerformed(ActionEvent e){
            //Execute when button is pressed
            String val = JOptionPane.showInputDialog("How mant fingers do you see?");

                txt.setText(val);
            }
};





public MessageBoxes(){

  frame = new JFrame("Title");

  frame.setSize(250, 250);

  frame.getContentPane().setLayout(new FlowLayout());

  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  frame.getContentPane().add(alert);
  frame.getContentPane().add(yesNo);
  frame.getContentPane().add(color);
  frame.getContentPane().add(vals);
  frame.getContentPane().add(input);
  frame.getContentPane().add(txt);

  frame.setVisible(true);

}

public void launchJFrame(){

  alert.addActionListener(alertAction);
  yesNo.addActionListener(yesNoAction);
  color.addActionListener(colorAction);
  vals.addActionListener(valsAction);
  input.addActionListener(inputAction);

}

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347334

The problem is, each time actionPerformed is called within you ActionListener al, it is registering new ActionListeners with your buttons

private ActionListener al = new ActionListener() {
    public void actionPerformed(ActionEvent e) {

        alert.addActionListener(new ActionListener() {
            //...
        });

        yesNo.addActionListener(new ActionListener() {
            //...
        });

        color.addActionListener(new ActionListener() {
            //...
        });

        vals.addActionListener(new ActionListener() {
            //...
        });

        input.addActionListener(new ActionListener() {
            //...
        });
    }
};

So, each time the actionPerformed method is called, each button registers a NEW actionListener.

Instead, you could use an if-else statement to determine the source of the event, for example...

Object source = e.getSource();
if (source == alert) {
    JOptionPane.showMessageDialog(null,
                    "There's a bug on you!", "Hey!",
                    JOptionPane.ERROR_MESSAGE);
} else if (...

Or you could get rid of the ActionListener al altogether and simple register the individual ActionListeners to the buttons within the launchJFrame method...

public void launchJFrame() {

    alert.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //Execute when button is pressed
        }
    });

    yesNo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //Execute when button is pressed
            int val = JOptionPane.showConfirmDialog(null,
                            "Choose yes or no", "Your Call...",
                            JOptionPane.YES_NO_OPTION);

            if (val != JOptionPane.CLOSED_OPTION) {
                if (val == 0) {
                    txt.setText("Yes");
                } else {
                    txt.setText("No");
                }
            }
        }
    });

    color.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //Execute when button is pressed
            Object[] options = {"Red", "Green"};

            int sel = JOptionPane.showOptionDialog(null,
                            "Choose a Color!", "Warning",
                            JOptionPane.DEFAULT_OPTION,
                            JOptionPane.WARNING_MESSAGE, null,
                            options, options[0]);

            if (sel != JOptionPane.CLOSED_OPTION) {
                txt.setText("Color Selected: " + options[sel]);
            }
        }
    });

    vals.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //Execute when button is pressed
            Object[] selections = {"First", "Second", "Third"};

            Object val = JOptionPane.showInputDialog(null,
                            "Choose one", "Input",
                            JOptionPane.INFORMATION_MESSAGE,
                            null, selections, selections[0]);

            if (val != null) {
                txt.setText(val.toString());
            }
        }
    });

    input.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            //Execute when button is pressed
            String val = JOptionPane.showInputDialog("How mant fingers do you see?");

            txt.setText(val);
        }
    });

}

Upvotes: 3

Mshnik
Mshnik

Reputation: 7042

It's because your actionlistener construction/addition is nested within another actionlistener, al. So the actionlisteners you care about (the ones that pop up the messages) aren't actually being added to the buttons till you click them once. Adding the actionlisteners to your buttons in launchJFrame() fixes the problem. Here's a fixed version of your code:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;


public class MessageBoxes{

  private JButton alert = new JButton("Alert");
  private JButton yesNo = new JButton("Yes/No");
  private JButton color = new JButton("Color");
  private JButton vals = new JButton("3 Vals");
  private JButton input = new JButton("Input");

  private JTextField txt = new JTextField(15);

  private JFrame frame;

  public MessageBoxes(){

    frame = new JFrame("Title");

    frame.setSize(250, 250);

    frame.getContentPane().setLayout(new FlowLayout());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(alert);
    frame.getContentPane().add(yesNo);
    frame.getContentPane().add(color);
    frame.getContentPane().add(vals);
    frame.getContentPane().add(input);
    frame.getContentPane().add(txt);

    frame.setVisible(true);

  }

  public void launchJFrame(){

      alert.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                JOptionPane.showMessageDialog(null,
                                      "There's a bug on you!", "Hey!",
                                      JOptionPane.ERROR_MESSAGE);
            }
        });  

        yesNo.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                int val = JOptionPane.showConfirmDialog(null,
                                      "Choose yes or no", "Your Call...",
                                      JOptionPane.YES_NO_OPTION);

                if(val != JOptionPane.CLOSED_OPTION){
                  if(val == 0){
                    txt.setText("Yes");
                }
                else{
                    txt.setText("No");
                }
                }
            }
        });  

        color.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                Object[] options = {"Red", "Green"};

                int sel = JOptionPane.showOptionDialog(null,
                                "Choose a Color!", "Warning",
                                JOptionPane.DEFAULT_OPTION,
                                JOptionPane.WARNING_MESSAGE, null,
                                            options, options[0]);

                if(sel != JOptionPane.CLOSED_OPTION){
                    txt.setText("Color Selected: " + options[sel]);
                }
            }
        });  

        vals.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                Object[] selections = {"First", "Second", "Third"};

                Object val = JOptionPane.showInputDialog(null,
                                                 "Choose one", "Input",
                                                 JOptionPane.INFORMATION_MESSAGE,
                                                 null, selections, selections[0]);

                if(val != null){
                    txt.setText(val.toString());
                }
            }
        });

        input.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent e)
            {
                //Execute when button is pressed
                String val = JOptionPane.showInputDialog("How mant fingers do you see?");

                    txt.setText(val);
            }
        });  

}

 public static void main(String [] args){

    MessageBoxes messageBoxes = new MessageBoxes();
    messageBoxes.launchJFrame();
 }
}

Upvotes: 3

Related Questions