Question

In: Computer Science

Modify the following 'MessageBoxes' application so it uses a single action listener for each button. This...

Modify the following 'MessageBoxes' application so it uses a single action listener for each button. This will require you to separate the single action listener logic into multiple listeners, one for each button. Then modify the code to provide additional options to two or more buttons.

/*
* The source code for this assignment started with
* a sample from "Thinking in Java" 3rd ed. page 825
* by Bruce Eckel. I have finished adding the rest of the action logic.
*
* Try to implement one new action listener at a time
* do not try to do all of them and then compile
*/

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

public class MessageBoxes{

private JButton[] b = {
                         new JButton("Alert"),
                         new JButton("Yes/No"),
                         new JButton("Color"),
                         new JButton("Input"),
                         new JButton("3 Vals"),
                         };

private JTextField txt = new JTextField(15);

private JFrame frame;

private ActionListener al = new ActionListener(){
    public void actionPerformed(ActionEvent e){
      String id = ((JButton)e.getSource()).getText();

      if(id.equals("Alert")){

        JOptionPane.showMessageDialog(null,
                                      "There's a bug on you!", "Hey!",
                                      JOptionPane.ERROR_MESSAGE);
      }
      else if(id.equals("Yes/No")){

        int val = JOptionPane.showConfirmDialog(null,
                                                "or no", "Chose yes",
                                                JOptionPane.YES_NO_OPTION);

        if(val != JOptionPane.CLOSED_OPTION){

          if(val == 0){

            txt.setText("Yes");
          }
          else{

            txt.setText("No");
          }
        }
      }
      else if(id.equals("Color")){

        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]);
        }
      }
      else if(id.equals("Input")){

        String val = JOptionPane.showInputDialog("How mant fingers do you see?");

        txt.setText(val);
      }
      else if(id.equals("3 Vals")){

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


public MessageBoxes(){

    frame = new JFrame("Title");

    frame.setSize(250, 250);

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

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    for(int i = 0; i < b.length; i++){

      frame.getContentPane().add(b[i]);
    }

    frame.getContentPane().add(txt);

    frame.setVisible(true);

}

public void launchJFrame(){

     for(int i = 0; i < b.length; i++){

      b[i].addActionListener(al);
    }
}

public static void main(String [] args){

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

Solutions

Expert Solution

/*
* The source code for this assignment started with
* a sample from "Thinking in Java" 3rd ed. page 825
* by Bruce Eckel. I have finished adding the rest of the action logic.
*
* Try to implement one new action listener at a time
* do not try to do all of them and then compile
*/

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

public class MessageBoxes{

private JButton[] b = {
new JButton("Alert"),
new JButton("Yes/No"),
new JButton("Color"),
new JButton("Input"),
new JButton("3 Vals"),
};

private JTextField txt = new JTextField(15);

private JFrame frame;

private ActionListener al1 = new ActionListener(){
public void actionPerformed(ActionEvent e){
   //alert
JOptionPane.showMessageDialog(null,
"There's a bug on you!", "Hey!",
JOptionPane.ERROR_MESSAGE);
}
};

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

   //yes/no
int val = JOptionPane.showConfirmDialog(null,
"or no", "Chose yes",
JOptionPane.YES_NO_OPTION);

if(val != JOptionPane.CLOSED_OPTION){

if(val == 0){

txt.setText("Yes");
}
else{

txt.setText("No");
}
}
  
}
};

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

   //color
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 al4 = new ActionListener(){
public void actionPerformed(ActionEvent e){
   //input

String val = JOptionPane.showInputDialog("How mant fingers do you see?");

txt.setText(val);
  
}
};

private ActionListener al5 = new ActionListener(){
public void actionPerformed(ActionEvent e){
   //3val

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


public MessageBoxes(){

frame = new JFrame("Title");

frame.setSize(250, 250);

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

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

for(int i = 0; i < b.length; i++){

frame.getContentPane().add(b[i]);
}

frame.getContentPane().add(txt);

frame.setVisible(true);

}

public void launchJFrame(){
   ActionListener al[] = new ActionListener[5];
   al[0] = al1;
   al[1] = al2;
   al[2] = al3;
   al[3] = al4;
   al[4] = al5;
for(int i = 0; i < b.length; i++){
b[i].addActionListener(al[i]);
}
}

public static void main(String [] args){

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


Related Solutions

Enhance the Future Value application Modify this application so it uses a persistent session to save...
Enhance the Future Value application Modify this application so it uses a persistent session to save the last values entered by the user for 2 weeks.. Index.php -------------------------- <?php     //set default value of variables for initial page load     if (!isset($investment)) { $investment = '10000'; }     if (!isset($interest_rate)) { $interest_rate = '5'; }     if (!isset($years)) { $years = '5'; } ?> <!DOCTYPE html> <html> <head>     <title>Future Value Calculator</title>     <link rel="stylesheet" type="text/css" href="main.css"/> </head> <body>    ...
Modify the GreenvilleRevenue program so that it uses the Contestant class and performs the following tasks:...
Modify the GreenvilleRevenue program so that it uses the Contestant class and performs the following tasks: The program prompts the user for the number of contestants in this year’s competition; the number must be between 0 and 30. The program continues to prompt the user until a valid value is entered. The expected revenue is calculated and displayed. The revenue is $25 per contestant. For example if there were 3 contestants, the expected revenue would be displayed as: Revenue expected...
Finish the following java question:  Modify a Encryption program so that it uses the following encryption algorithm:...
Finish the following java question:  Modify a Encryption program so that it uses the following encryption algorithm: Every letter (both uppercase and lowercase) converted to its successor except z and Z, which are converted to 'a' and 'A' respectively (i.e., a to b, b to c, …, y to z, z to a, A to B, B to C, …, Y to Z, Z to A) Every digit converted to its predecessor except 0, which is converted to 9 (i.e., 9...
Java 2D Drawing Application. The application will contain the following elements: a) an Undo button to...
Java 2D Drawing Application. The application will contain the following elements: a) an Undo button to undo the last shape drawn. b) a Clear button to clear all shapes from the drawing. c) a combo box for selecting the shape to draw, a line, oval, or rectangle. d) a checkbox which specifies if the shape should be filled or unfilled. e) a checkbox to specify whether to paint using a gradient. f) two JButtons that each show a JColorChooser dialog...
Using NetBeans, Modify your sales application so that it polymorphically processes any account objects that are...
Using NetBeans, Modify your sales application so that it polymorphically processes any account objects that are created. Complete the following:     Create a 2-item array of type Account.     Store each account object created into the array.     For each element in this array, call the calculateSales() method, and use the toString() method to display the results.     Code should be fully commented.     Program flow should be logical. Code before revision: /* * To change this license header, choose...
Modify the FeetInches class so that it overloads the following operators: <= >= != Demonstrate the...
Modify the FeetInches class so that it overloads the following operators: <= >= != Demonstrate the class's capabilities in a simple program. this is what needs to be modified // Specification file for the FeetInches class #ifndef FEETINCHES_H #define FEETINCHES_H #include <iostream> using namespace std; class FeetInches; // Forward Declaration // Function Prototypes for Overloaded Stream Operators ostream &operator << (ostream &, const FeetInches &); istream &operator >> (istream &, FeetInches &); // The FeetInches class holds distances or measurements...
Modify the program below so the driver class (Employee10A) uses a polymorphic approach, meaning it should...
Modify the program below so the driver class (Employee10A) uses a polymorphic approach, meaning it should create an array of the superclass (Employee10A) to hold the subclass (HourlyEmployee10A, SalariedEmployee10A, & CommissionEmployee10A) objects, then load the array with the objects you create. Create one object of each subclass. The three subclasses inherited from the abstract superclass print the results using the overridden abstract method. Below is the source code for the driver class: public class EmployeeTest10A { public static void main(String[]...
Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right)...
Modify the partition.java program (Listing 7.2) so that the partitionIt() method always uses the highest-index (right) element as the pivot, rather than an arbitrary number. (This is similar to what happens in the quickSort1.java program in Listing 7.3.) Make sure your routine will work for arrays of three or fewer elements. To do so, you may need a few extra statements. // partition.java // demonstrates partitioning an array // to run this program: C>java PartitionApp //////////////////////////////////////////////////////////////// class ArrayPar { private...
Using C#, modify the codes below to do the following: Develop a polymorphic banking application using...
Using C#, modify the codes below to do the following: Develop a polymorphic banking application using the Account hierarchy created in the codes below. Create an array of Account references to SavingsAccount and CheckingAccount objects. For each Account in the array, allow the user to specify an amount of money to withdraw from the Account using method Debit and an amount of money to deposit into the Account using method Credit. As you process each Account, determine its type. If...
Provide immediate feedback for each mistyped sentence. To do so, modify the Test class’s present_test method...
Provide immediate feedback for each mistyped sentence. To do so, modify the Test class’s present_test method so that it informs the player a mistake has been made, then display the challenge sentence followed by the player’s sentence so the player can determine where the error lies. #-------------------------------------------------------------------------- # # Script Name: TypingChallenge.rb # Version: 1.0 # Author: Jerry Lee Ford, Jr. # Date: March 2010 # # Description: This Ruby script demonstrates how to apply conditional logic # in order...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT