Question

JAVA Hello I am trying to add a menu to my Java code if someone can...

JAVA

Hello I am trying to add a menu to my Java code if someone can help me I would really appreacite it thank you.

I found a java menu code but I dont know how to incorporate it to my code this is the java menu code that i found.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;

public class MenuExp extends JFrame {

    public MenuExp() {

        setTitle("Menu Example");
        setSize(150, 150);

        // Creates a menubar for a JFrame
        JMenuBar menuBar = new JMenuBar();

        // Add the menubar to the frame
        setJMenuBar(menuBar);

        // Define and add two drop down menu to the menubar
        JMenu fileMenu = new JMenu("File");
        JMenu editMenu = new JMenu("Edit");
        menuBar.add(fileMenu);
        menuBar.add(editMenu);

        // Create and add simple menu item to one of the drop down menu
        JMenuItem newAction = new JMenuItem("New");
        JMenuItem openAction = new JMenuItem("Open");
        JMenuItem exitAction = new JMenuItem("Exit");
        JMenuItem cutAction = new JMenuItem("Cut");
        JMenuItem copyAction = new JMenuItem("Copy");
        JMenuItem pasteAction = new JMenuItem("Paste");

        // Create and add CheckButton as a menu item to one of the drop down
        // menu
        JCheckBoxMenuItem checkAction = new JCheckBoxMenuItem("Check Action");
        // Create and add Radio Buttons as simple menu items to one of the drop
        // down menu
        JRadioButtonMenuItem radioAction1 = new JRadioButtonMenuItem(
                "Radio Button1");
        JRadioButtonMenuItem radioAction2 = new JRadioButtonMenuItem(
                "Radio Button2");
        // Create a ButtonGroup and add both radio Button to it. Only one radio
        // button in a ButtonGroup can be selected at a time.
        ButtonGroup bg = new ButtonGroup();
        bg.add(radioAction1);
        bg.add(radioAction2);
        fileMenu.add(newAction);
        fileMenu.add(openAction);
        fileMenu.add(checkAction);
        fileMenu.addSeparator();
        fileMenu.add(exitAction);
        editMenu.add(cutAction);
        editMenu.add(copyAction);
        editMenu.add(pasteAction);
        editMenu.addSeparator();
        editMenu.add(radioAction1);
        editMenu.add(radioAction2);
        // Add a listener to the New menu item. actionPerformed() method will
        // invoked, if user triggred this menu item
        newAction.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("You have clicked on the new action");
            }
        });
    }
    public static void main(String[] args) {
        MenuExp me = new MenuExp();
        me.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        me.setVisible(true);
    }
}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

and this is the code that I created where I want to add the menu to

//Header File section
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import java.awt.*;  //Contains all of the classes for creating user interfaces and for painting graphics and images.

import javax.swing.*;   //Provides a set of "lightweight" (all-Java language) components that, to maximum degree possible, work the same on all platforms.
import javax.swing.JOptionPane; //JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value of informs them of something.

import java.text.DecimalFormat; //DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers.
//======================================================================================================================

//Class name declaration
public class TravelExpenses extends JFrame {




    //This section contains the information that my GUI program is going to display to the user.

    //JPanel is a generic lightweight container.

    private JPanel travelInfoPanel;
    private JPanel buttonPanel;


    // Labels
    /*
    A JLabel object can display either text, an image, or both. You can specify where in the label's contents are aligned
    by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area.
    Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.
     */
    private JLabel numDaysOnTripLabel;
    private JLabel amountAirfairLabel;
    private JLabel amountCarRentalLabel;
    private JLabel milesDrivenLabel;
    private JLabel parkingFeesLabel;
    private JLabel taxiFeesLabel;
    private JLabel confRegLabel;
    private JLabel lodgingChargesPerNightLabel;


    // Text Fields
    /*
    JTextField is a lightweight component that allows the editing of a single line of text. It is intended to be source-
    compatible with java.awt.TextField where it is reasonable to do so. This component has capabilities not found in the
    java.awt.TextField class. The superclass should be consulted for additional capabilities.
     */
    private JTextField numDaysOnTripTextField;
    private JTextField amountAirfairTextField;
    private JTextField amountCarRentalTextField;
    private JTextField milesDrivenTextField;
    private JTextField parkingFeesTextField;
    private JTextField taxiFeesTextField;
    private JTextField confRegTextField;
    private JTextField lodgingChargesPerNightTextField;


    // Buttons
    /*
    An implementation of a "push" button. Buttons can be configured, and to some degree controlled, by Actions. Using
    an Action with a button has many benefits beyond directly configuring a button.
     */
    private JButton resetButton;
    private JButton calcButton;

//======================================================================================================================
    /*
    The company reimburses travel expenses according to the following policy:
        > $37 per day for meals
        > Parking fees, up to $10.00 per day
        > Taxi charges up to $20.00 per day
        > Lodging charges up to $95.00 per day
        > If a private vehicle is used, $0.27 per mile driven
     */


    //This section will apply the reimbursement restrictions that the company apply to their employees.

    // Meals amount reimbursed by company per day.
    private double mealsAmount = 37.00;
    // Parking Fees amount reimbursed by company per day.
    private double parkingFeesReimbursed = 10.00;
    // Taxi Charges amount reimbursed by company per day.
    private double taxiChargesReimbursed = 20.00;
    // Lodging Charges amount reimbursed by company per day.
    private double lodgingChargesReimbursed = 95.00;
    // Private Vehicle per miles reimbursement rate.
    private double prVechiclePerMileReimbursed = 0.27;

//======================================================================================================================

    // Constructor
    public TravelExpenses() {

        //set the title.
        super("TRAVEL EXPENSES CALCULATOR");
        // Set the main window
        setLocationRelativeTo(null);
        // Specify an action for the close button.
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Create a BorderLayout manager for the content pane.
        setLayout(new BorderLayout());
        // Build the TravelInfo and Buttons panels
        buildTravelInfoPanel();
        buildButtonPanel();
        // Add the panels to the frame's content pane
        add(travelInfoPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.SOUTH);
        // Pack the contents of the window and display it.
        pack();
        setVisible(true);
    }
    // The buildTravelInfoPanel method adds the labels and text fields to the TravelInfo panel.

    //======================================================================================================================
    private void buildTravelInfoPanel() {
        // Create the labels for TravelInfo fields
        //This is what the program is going to ask the user to enter.
        numDaysOnTripLabel = new JLabel("Number of days on the trip: ");
        amountAirfairLabel = new JLabel("Amount of airfare: ");
        amountCarRentalLabel = new JLabel("Amount of car rental: ");
        milesDrivenLabel = new JLabel("Miles driven: ");
        parkingFeesLabel = new JLabel("Parking fees: ");
        taxiFeesLabel = new JLabel("Taxi fees: ");
        confRegLabel = new JLabel("Conference registration: ");
        lodgingChargesPerNightLabel = new JLabel("Lodging charges per night: ");

        // Create the text boxes for TravelInfo user input
        numDaysOnTripTextField = new JTextField(3);
        amountAirfairTextField = new JTextField(8);
        amountCarRentalTextField = new JTextField(8);
        milesDrivenTextField = new JTextField(4);
        parkingFeesTextField = new JTextField(6);
        taxiFeesTextField = new JTextField(6);
        confRegTextField = new JTextField(8);
        lodgingChargesPerNightTextField = new JTextField(6);

        // Create a panel to hold labels and text fields.
        travelInfoPanel = new JPanel();

        // Create GridLayout manager
        travelInfoPanel.setLayout(new GridLayout(10, 2));

        // Add the labels and text fields to this panel.
        travelInfoPanel.add(numDaysOnTripLabel);
        travelInfoPanel.add(numDaysOnTripTextField);
        travelInfoPanel.add(amountAirfairLabel);
        travelInfoPanel.add(amountAirfairTextField);
        travelInfoPanel.add(amountCarRentalLabel);
        travelInfoPanel.add(amountCarRentalTextField);
        travelInfoPanel.add(milesDrivenLabel);
        travelInfoPanel.add(milesDrivenTextField);
        travelInfoPanel.add(parkingFeesLabel);
        travelInfoPanel.add(parkingFeesTextField);
        travelInfoPanel.add(taxiFeesLabel);
        travelInfoPanel.add(taxiFeesTextField);
        travelInfoPanel.add(confRegLabel);
        travelInfoPanel.add(confRegTextField);
        travelInfoPanel.add(lodgingChargesPerNightLabel);
        travelInfoPanel.add(lodgingChargesPerNightTextField);

        // Add an empty border around the panel for spacing.
        travelInfoPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 1, 10));
    }

//======================================================================================================================
    //The buildButtonPanel method creates and adds the Reset and Calculate buttons to the TravelExpense panel as its own panel.

    private void buildButtonPanel() {
        // Create the calcButton.
        calcButton = new JButton("CALCULATE");
        // Register an event listener
        calcButton.addActionListener(new CalcButtonListener());
        //Create the resetButton.
        resetButton = new JButton("RESET");
        // Create the Buttons panels.
        buttonPanel = new JPanel();
        // Create BorderLayout manager.
        buttonPanel.setLayout(new BorderLayout(5, 5));
        // Add the two buttons to the buttonPanel.
        buttonPanel.add(resetButton, BorderLayout.WEST);
        buttonPanel.add(calcButton, BorderLayout.CENTER);
        // Add an empty border around the panel for spacing.
        buttonPanel.setBorder(BorderFactory.createEmptyBorder(1, 10, 10, 10));
    }

//======================================================================================================================
    // Private inner class that handles the event when the user clicks the Calculate button.

    private class CalcButtonListener implements ActionListener {

        // Declare variables
        String input;
        int days;
        double air;
        double carRental;
        double miles;
        double parking;
        double taxi;
        double confReg;
        double lodging;
        double mealsAmount;

        public void actionPerformed(ActionEvent e) {

            //Declare variables
            double actualExpenses;
            double milesExpenses;
            double allowableExpenses;
            double excessAir;
            double excessCarRental;
            double excessParking;
            double excessTaxi;
            double excessLodging;
            double excessAmountTotal;
            double amountSaved = 0;
            double paidBackAmount = 0;

            // Create a DecimalFormat object to format the totals as dollar amounts.
            DecimalFormat dollar = new DecimalFormat("$#,##0.00");

            // Get Input Data the user entered in the text fields.
            days = Integer.parseInt(numDaysOnTripTextField.getText());
            air = Double.parseDouble(amountAirfairTextField.getText());
            carRental = Double.parseDouble(amountCarRentalTextField.getText());
            miles = Double.parseDouble(milesDrivenTextField.getText());
            parking = Double.parseDouble(parkingFeesTextField.getText());
            taxi = Double.parseDouble(taxiFeesTextField.getText());
            confReg = Double.parseDouble(confRegTextField.getText());
            lodging = Double.parseDouble(lodgingChargesPerNightTextField.getText());

            // Determine actualExpenses method.
            milesExpenses = miles * prVechiclePerMileReimbursed;
            actualExpenses = (carRental + parking + taxi + lodging + mealsAmount) * days + air + milesExpenses + confReg;

            // Calculate the allowableExpenses.
            allowableExpenses = (mealsAmount + parkingFeesReimbursed + taxiChargesReimbursed + lodgingChargesReimbursed) * days + milesExpenses + air + confReg;

            // Calculate the paidBackAmount.
            if (actualExpenses > allowableExpenses)
                paidBackAmount = actualExpenses - allowableExpenses;
            else
                amountSaved = allowableExpenses - actualExpenses;

            // Display the Totals message box.
            if (paidBackAmount > 0)
                JOptionPane.showMessageDialog(null, "Total expenses: "
                        + dollar.format(actualExpenses) + "\n" + "Allowable expenses: "
                        + dollar.format(allowableExpenses) + "\n" + "Amount to be paid back: " + dollar.format(paidBackAmount));
            else if (amountSaved > 0)
                JOptionPane.showMessageDialog(null, "Total expenses: " + dollar.format(actualExpenses)
                        + "\n" + "Allowable expenses: " + dollar.format(allowableExpenses) + "\n" + "\n" + "Amount Saved: " + dollar.format(amountSaved));
            else
                JOptionPane.showMessageDialog(null, "Total expenses: " + dollar.format(actualExpenses)
                        + "\n" + "Allowable expenses: " + dollar.format(allowableExpenses) + "\n");
        }
    }

//======================================================================================================================
    // Private inner class that handles the event when the user clicks the RESET button .


    private class ResetButtonListener implements ActionListener {

        public void actionPerformed(ActionEvent e) {

            numDaysOnTripTextField.setText("");

            amountAirfairTextField.setText("");

            amountCarRentalTextField.setText("");

            milesDrivenTextField.setText("");

            parkingFeesTextField.setText("");

            taxiFeesTextField.setText("");

            confRegTextField.setText("");

            lodgingChargesPerNightTextField.setText("");

        }

    }

    //======================================================================================================================
    // The main method
    public static void main(String[] args) {

        new TravelExpenses();

    }
}

Thank you in advance

0 0
Add a comment Improve this question Transcribed image text
Answer #1

At TravelExpenses class please add the following code which incorporates the menu:

JFrame frame = new JFrame("MenuSample Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = new MenuExp();

// File Menu, F - Mnemonic
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
menuBar.add(fileMenu);

// File->New, N - Mnemonic
JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
fileMenu.add(newMenuItem);

frame.setJMenuBar(menuBar);
frame.setSize(350, 250);
frame.setVisible(true);

Add a comment
Know the answer?
Add Answer to:
JAVA Hello I am trying to add a menu to my Java code if someone can...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • tart from the following code, and add Action Listener to make it functional to do the...

    tart from the following code, and add Action Listener to make it functional to do the temperature conversion in the direction of the arrow that is clicked. . (Need about 10 lines) Note: import javax.swing.*; import java.awt.GridLayout; import java.awt.event.*; import java.text.DecimalFormat; public class temperatureConverter extends JFrame { public static void main(String[] args) {     JFrame frame = new temperatureConverter();     frame.setTitle("Temp");     frame.setSize(200, 100);     frame.setLocationRelativeTo(null);     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     frame.setVisible(true); }    public temperatureConverter() {     JLabel lblC = new...

  • Can someone modify my code so that I do not get this error: Exception in thread...

    Can someone modify my code so that I do not get this error: Exception in thread "main" java.lang.NullPointerException at java.awt.Container.addImpl(Container.java:1043) at java.awt.Container.add(Container.java:363) at RatePanel.<init>(RatePanel.java:64) at CurrencyConverter.main(CurrencyConverter.java:16) This code should get the amount of money in US dollars from user and then let them select which currency they are trying to convert to and then in the textfield print the amount //********************************************************************* //File name: RatePanel.java //Name: Brittany Hines //Purpose: Panel for a program that convers different currencyNamerencies to use dollars //*********************************************************************...

  • With the Code below, how would i add a "Back" Button to the bottom of the...

    With the Code below, how would i add a "Back" Button to the bottom of the history page so that it takes me back to the main function and continues to work? import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; public class RecipeFinder { public static void main(String[]...

  • This is all I have regarding the question import java.awt.*; import java.awt.event.*; import javax.swing.*; public class...

    This is all I have regarding the question import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Quiz8_GUI { private JFrame frame;    /** * Create an Quiz8_GUI show it on screen. */ public Quiz8_GUI() { makeFrame(); } // ---- swing stuff to build the frame and all its components ---- /** * Create the Swing frame and its content. */ private void makeFrame() { frame = new JFrame("Quiz8_GUI"); makeMenuBar(frame); Container contentPane = frame.getContentPane(); //set the Container to flow layout //Your...

  • Please fix and test my code so that all the buttons and function are working in...

    Please fix and test my code so that all the buttons and function are working in the Sudoku. CODE: SudokuLayout.java: import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.JTextField; public class SudokuLayout extends JFrame{ JTextArea txtArea;//for output JPanel gridPanel,butPanel;//panels for sudoku bord and buttons JButton hint,reset,solve,newPuzzel;//declare buttons JComboBox difficultyBox; SudokuLayout() { setName("Sudoku Bord");//set name of frame // setTitle("Sudoku Bord");//set...

  • please help me debug this Create a GUI for an application that lets the user calculate...

    please help me debug this Create a GUI for an application that lets the user calculate the hypotenuse of a right triangle. Use the Pythagorean Theorem to calculate the length of the third side. The Pythagorean Theorem states that the square of the hypotenuse of a right-triangle is equal to the sum of the squares of the opposite sides: alidate the user input so that the user must enter a double value for side A and B of the triangle....

  • Can you please help me to run this Java program? I have no idea why it...

    Can you please help me to run this Java program? I have no idea why it is not running. import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; @SuppressWarnings({"unchecked", "rawtypes"}) public class SmartPhonePackages extends JFrame { private static final long serialVersionID= 6548829860028144965L; private static final int windowWidth = 400; private static final int windowHeight = 200; private static final double SalesTax = 1.06; private static JPanel panel;...

  • Swing File Adder: Build a GUI that contains an input file, text box and Infile button....

    Swing File Adder: Build a GUI that contains an input file, text box and Infile button. It also must contain and output file, text box and Outfile button. Must also have a process button must read the infile and write to the outfile if not already written that is already selected and clear button. It must pull up a JFile chooser that allows us to brows to the file and places the full path name same with the output file.  Program...

  • I have been messing around with java lately and I have made this calculator. Is there...

    I have been messing around with java lately and I have made this calculator. Is there any way that I would be able to get a different sound to play on each different button 1 - 9 like a nokia phone? Thank you. *SOURCE CODE* import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; class Calculator extends JFrame { private final Font BIGGER_FONT = new Font("monspaced",Font.PLAIN, 20); private JTextField textfield; private boolean number = true; private String equalOp = "="; private...

  • In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show...

    In Java Swing, in my ButtonHandler class, I need to have 2 different showDialog messages show when my acceptbutton1 is pressed. One message is if the mouse HAS been dragged. One is if the mouse HAS NOT been dragged. /// I tried to make the Points class or the Mouse Dragged function return a boolean of true, so that I could construct an IF/THEN statement for the showDialog messages, but my boolean value was never accepted by ButtonHandler. *************************ButtonHandler class************************************...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT