使用菜单栏按钮Java将标签内容保存到文件

时间:2019-01-14 15:17:45

标签: java swing

我必须能够将order(label)的内容写到在桌面上输出的文本文件中,我有一个按钮可以将菜单保存在菜单栏上,但是不知道如何添加功能。

这是我为主要课程准备的完整代码,如果有什么我可以做的来改善代码的其他部分,请在我还在学习的同时也说

import java.awt.event.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JFrame;

/**
 *
 * @author
 */
public class Main extends javax.swing.JFrame {

    private javax.swing.JButton addDrinkButton;
    private javax.swing.JButton addSandwichButton;
    private javax.swing.JButton addSideButton;
   //private javax.swing.JButton addNewDrinkButton;
   //private javax.swing.JButton addNewSandwichButton;
   //private javax.swing.JButton addNewSideButton;
    private javax.swing.JButton quitButton;
    private javax.swing.JComboBox<String> drinkComboBox;
    private javax.swing.JLabel drinkLabel;
    private javax.swing.JButton editOrderButton;
    private javax.swing.JMenu JMenuVar;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JMenuItem loadMenu;
    private javax.swing.JTextPane orderDisplay;
  //private javax.swing.JMenuItem quitMenuOption;
    private javax.swing.JComboBox<String> sandwichComboBox;
    private javax.swing.JLabel sandwichLabel;
    private javax.swing.JMenuItem saveMenuOption;
    private javax.swing.JComboBox<String> sideComboBox;
    private javax.swing.JLabel sideLabel;
    private javax.swing.JButton sortByNameButton;
    private javax.swing.JButton sortByPriceButton;
    private javax.swing.JButton startOrderButton;

    private Menu sandwichMenu = new Menu("Our Sandwiches");
    private Menu sideMenu = new Menu("Our Sides");
    private Menu drinkMenu = new Menu("Our Drinks");
    private Order order;

    public Main() {
        initComponents();
        initMenus();
        addEventListeners();
    }

    private void initMenus() {
        //Initialise sandwich menu object
        Sandwich sandwich = new Sandwich("BLT", 275, "Bacon, Lettuce and Tomato", Bread.WHITE);
        sandwichMenu.addMenuItem(sandwich);
        sandwich = new Sandwich("Pastrami", 250, "Pastrami and Mustard", Bread.RYE);
        sandwichMenu.addMenuItem(sandwich);
        sandwich = new Sandwich("Veggie", 300, "Veggie Ham and Salad", Bread.WHOLEMEAL);
        sandwichMenu.addMenuItem(sandwich);
        sandwich = new Sandwich("Cheese Bagel", 400, "Cream Cheese Bagel", Bread.BAGEL);
        sandwichMenu.addMenuItem(sandwich);
        sandwich = new Sandwich("Greek Salad Pita", 400, "Salad filled Pita", Bread.PITA);
        sandwichMenu.addMenuItem(sandwich);
        sandwichComboBox.setModel(new javax.swing.DefaultComboBoxModel(sandwichMenu.getItems().toArray()));

        //Initialise drink menu object
        Drink drink = new Drink("Irn Bru", 100 ,false);
        drinkMenu.addMenuItem(drink);
        drink = new Drink("Beer", 350, true);
        drinkMenu.addMenuItem(drink);
        drink = new Drink("Water", 60, false);
        drinkMenu.addMenuItem(drink);
        drink = new Drink("Juice", 70, false);
        drinkMenu.addMenuItem(drink);
        drink = new Drink("Cider", 350, true);
        drinkMenu.addMenuItem(drink);
        drinkComboBox.setModel(new javax.swing.DefaultComboBoxModel(drinkMenu.getItems().toArray()));

        //Initialise side menu
        Side side = new Side("Chips", 120);
        sideMenu.addMenuItem(side);
        side = new Side("Chips with Sauce", 120, "Mustard or Ketchup");
        sideMenu.addMenuItem(side);
        side = new Side("Salad", 100);
        sideMenu.addMenuItem(side);
        side = new Side("Hot Dog", 250);
        sideMenu.addMenuItem(side);
        side = new Side("Hot Dog with Sauce", 250, "Mustard or Ketchup");
        sideMenu.addMenuItem(side);
        sideComboBox.setModel(new javax.swing.DefaultComboBoxModel(sideMenu.getItems().toArray()));
    }

    private void initComponents() {

        this.setTitle("Sandwich Shop");
        quitButton = new javax.swing.JButton();
        startOrderButton = new javax.swing.JButton();
        sandwichComboBox = new javax.swing.JComboBox<>();
        sandwichLabel = new javax.swing.JLabel();
        drinkComboBox = new javax.swing.JComboBox<>();
        drinkLabel = new javax.swing.JLabel();
        sideComboBox = new javax.swing.JComboBox<>();
        sideLabel = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        orderDisplay = new javax.swing.JTextPane();
        addSandwichButton = new javax.swing.JButton();
        addDrinkButton = new javax.swing.JButton();
        addSideButton = new javax.swing.JButton();
        //addNewSandwichButton = new javax.swing.JButton();
        //addNewDrinkButton = new javax.swing.JButton();
        //addNewSideButton = new javax.swing.JButton();
        sortByPriceButton = new javax.swing.JButton();
        sortByNameButton = new javax.swing.JButton();
        editOrderButton = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        JMenuVar = new javax.swing.JMenu();
        saveMenuOption = new javax.swing.JMenuItem();
        loadMenu = new javax.swing.JMenuItem();
        //quitMenuOption = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        startOrderButton.setText("Start Order");

        sandwichComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        sandwichLabel.setText("Sandwiches");

        drinkComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }));
        drinkLabel.setText("Drinks");

        sideComboBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" }));
        sideLabel.setText("Sides");

        quitButton.setText("Quit Program");
        jScrollPane2.setViewportView(orderDisplay);
        addSandwichButton.setText("Add Sandwich to order");
        addDrinkButton.setText("Add Drink to order");
        addSideButton.setText("Add Side to order");
        //addNewSandwichButton.setText("Add a new sandwich");
        //addNewDrinkButton.setText("Add a new drink");
        //addNewSideButton.setText("Add a new side");
        sortByPriceButton.setText("Sort menus by price");
        sortByNameButton.setText("Sort menus by name");
        editOrderButton.setText("Edit Current Order");

        JMenuVar.setText("File");
        saveMenuOption.setText("Save Menu");
        JMenuVar.add(saveMenuOption);
        loadMenu.setText("Load new menu");
        JMenuVar.add(loadMenu);
        //quitMenuOption.setText("Quit");
     //   JMenuVar.add(quitMenuOption);
        jMenuBar1.add(JMenuVar);
        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(startOrderButton)
                                                        .addComponent(editOrderButton))
                                                .addGap(18, 18, 18)
                                                .addComponent(sandwichLabel)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(sandwichComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(addSandwichButton)))
                                                .addGap(11, 11, 11)
                                                .addComponent(drinkLabel)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(drinkComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(addDrinkButton)))
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(sideLabel)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                        .addComponent(sideComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                                .addComponent(addSideButton)))
                                                .addGap(5, 5, 5)
                                                .addComponent(sortByNameButton)
                                                .addComponent(sortByPriceButton)
                                                .addComponent(quitButton)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addGap(0, 10, Short.MAX_VALUE))
                                        .addComponent(jScrollPane2))
                                .addContainerGap())
        );
        layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup()
                                                .addContainerGap()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                        .addComponent(drinkComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                        .addComponent(sideComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                                                        .addComponent(sandwichLabel)
                                                                                        .addComponent(drinkLabel)
                                                                                        .addComponent(sideLabel))
                                                                                .addGap(3, 3, Short.MAX_VALUE))
                                                                        .addComponent(sandwichComboBox, 5, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                .addComponent(addSandwichButton)
                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                .addComponent(addSideButton)
                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                                                                        .addGroup(layout.createSequentialGroup()
                                                                                .addComponent(addDrinkButton)
                                                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                                                                .addGap(18, 18, 18))
                                                        .addGroup(layout.createSequentialGroup()
                                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                                                        .addComponent(sortByNameButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                        .addComponent(sortByPriceButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                                                        .addComponent(quitButton, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                                                                .addGap(0, 0, Short.MAX_VALUE))))
                                        .addGroup(layout.createSequentialGroup()
                                                .addGap(94, 94, 94)
                                                .addComponent(startOrderButton, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                .addComponent(editOrderButton, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 125, Short.MAX_VALUE)))
                                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addContainerGap())
        );
        pack();
    }


    private void addEventListeners() {
        addSandwichButton.addActionListener(evt -> addSandwichButtonEvent(evt));
        addSideButton.addActionListener(evt -> addSideButtonActionPerformed(evt));
        addDrinkButton.addActionListener(evt -> addDrinkButtonEvent(evt));
        startOrderButton.addActionListener(evt -> startNewOrder());
        //quitMenuOption.addActionListener(evt -> System.exit(0));
        quitButton.addActionListener(evt -> System.exit(0));
        sortByNameButton.addActionListener(evt -> sortMenusByName());
        sortByPriceButton.addActionListener(evt -> sortMenusByPrice());
    }

    private void sortMenusByPrice() {
        sandwichMenu.sortItemsByPrice();
        sideMenu.sortItemsByPrice();
        drinkMenu.sortItemsByPrice();
        resetComboBoxes();
    }


    private void sortMenusByName() {
        sandwichMenu.sortItemsByTitle();
        sideMenu.sortItemsByTitle();
        drinkMenu.sortItemsByTitle();
        resetComboBoxes();
    }

    private void resetComboBoxes() {
        sandwichComboBox.setModel(new javax.swing.DefaultComboBoxModel(sandwichMenu.getItems().toArray()));
        drinkComboBox.setModel(new javax.swing.DefaultComboBoxModel(drinkMenu.getItems().toArray()));
        sideComboBox.setModel(new javax.swing.DefaultComboBoxModel(sideMenu.getItems().toArray()));
    }


    private void addSandwichButtonEvent(ActionEvent evt) {

        if(order != null) {
            order.addMenuItem((MenuItem) sandwichComboBox.getSelectedItem());
            updateOrder();
        } else {
            JOptionPane.showMessageDialog(null, "Please start an order before adding items");
            return;
        }
    }

    private void addDrinkButtonEvent(ActionEvent evt) {

        if(order != null) {
            Drink receivedItem = (Drink) drinkComboBox.getSelectedItem();

            if(receivedItem.hasAlcohol()) {
                int r = JOptionPane.showConfirmDialog(null, "Are you over 18?", null, JOptionPane.YES_NO_OPTION);
                if(r == JOptionPane.NO_OPTION) {
                    return;
                } else {
                    order.addMenuItem(receivedItem);
                }
            } else {
                order.addMenuItem(receivedItem);
            }
            updateOrder();
        } else {
            JOptionPane.showMessageDialog(null, "Please click start order before adding items");
            return;
        }

    }

    private void addSideButtonActionPerformed(ActionEvent evt) {
        if(order != null) {
            order.addMenuItem((MenuItem) sideComboBox.getSelectedItem());
            updateOrder();
        } else {
            JOptionPane.showMessageDialog(null, "Please click start order before adding items");
            return;
        }
    }

    private void startNewOrder() {

        if(order == null) {
            String name = JOptionPane.showInputDialog(null,"Please enter customers name: ",null);
            System.out.println(name);
            int i = 0;
            while (name == "null" && i < 3) {
                int attempts = 3 - i;
                name = JOptionPane.showInputDialog(null,"Please click start order before adding items " + attempts + " remaining",null);
                i++;
            } if (name == "null") {
                return;
            } else {
                order = new Order(name);
                updateOrder();
            }
        } else {
            int r = (int) JOptionPane.showConfirmDialog(null, "Are you sure you want to start a new Order? Your current order will be lost!", null, JOptionPane.YES_NO_OPTION);
            System.out.println(r);
            if(r == JOptionPane.YES_OPTION){
                String name = JOptionPane.showInputDialog(null,"please enter the customer's name",null);
                System.out.println(name);
                int i = 0;
                while (name == "null" && i < 3){
                    int attempts = 3 - i;
                    name = JOptionPane.showInputDialog(null,"please enter the customer's name you have " + attempts +" remaining",null);
                    i++;
                } if (name == "null"){
                    return;
                } else {
                    order = new Order(name);
                    updateOrder();
                }
            } else {
                return;
            }
        }

    }
    private void updateOrder() {
        String orderString = order.getCustomer() + "'s Order (order id " + order.getOrderID() + "):\n\n";
        int price = 0;

        ArrayList<MenuItem> items = order.getItems();
        for(MenuItem item : items){
            orderString += item.toString()+"\n";
            price += item.price();
        }

        orderString += "\nprice: " + price + "p";

        orderDisplay.setText(orderString);
    }

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }
}

0 个答案:

没有答案