Как использовать номер дисплея, чтобы получить гаджет от массива и отправить его на мобильный?Кроме того, как мне вызвать makeCall () в классе Mobile? - PullRequest
0 голосов
/ 19 апреля 2019

Я работаю над созданием графического интерфейса для хранения сведений о гаджетах, таких как мобильные телефоны и MP3.

Это то, что я пытаюсь сделать:

Когда метод, чтобы получить номер дисплеявызывается, проверяется и не равно -1:

  • Отображаемый номер используется для получения гаджета из списка массивов и его трансляции в Mobile.

  • Кроме того, метод вызова в классе Mobile вызывается с указанием номера телефона и продолжительности.

Я перепробовал все, что мог придумать, ноне повезло.

Это класс GUI.Вы найдете Гаджет Суперкласс и Мобильный подкласс ниже.

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

public class GadgetShop implements ActionListener
{
    // instance variables - replace the example below with your own
    private JTextField modelTextField;
    private JTextField priceTextField;
    private JTextField weightTextField;
    private JTextField sizeTextField;
    private JTextField initialCreditTextField;
    private JTextField initialMemoryTextField;
    private JTextField phoneNumberTextField;
    private JTextField durationTextField;
    private JTextField downloadSizeTextField;
    private JTextField displayNumberTextField;
    private JButton addMobileButton;
    private JButton addMp3Button;
    private JButton clearButton;
    private JButton displayAllButton;
    private JButton makeCallButton;
    private JButton downloadMusicButton;
    private JLabel modelLabel;
    private JLabel priceLabel;
    private JLabel weightLabel;
    private JLabel sizeLabel;
    private JLabel creditLabel;
    private JLabel memoryLabel;
    private JLabel phoneNumLabel;
    private JLabel durationLabel;
    private JLabel downloadLabel;
    private JLabel dispNumLabel;
    private JFrame frame;
    private ArrayList<Gadget> gadgets;

    /**
     * The GUI is created in the constructor.
     */
    public GadgetShop()
    {
        // initialise instance variables

        gadgets = new ArrayList<Gadget>();

        frame = new JFrame("The Gadget Shop");
        Container contentPane = frame.getContentPane();
        contentPane.setLayout(new GridLayout(7, 4));

        JLabel modelLabel = new JLabel("Model:");
        contentPane.add(modelLabel);

        JLabel priceLabel = new JLabel("Price:");
        contentPane.add(priceLabel);

        JLabel weightLabel = new JLabel("Weight:");
        contentPane.add(weightLabel);

        JLabel sizeLabel = new JLabel("Size:");
        contentPane.add(sizeLabel);

        modelTextField = new JTextField(15);
        contentPane.add(modelTextField);

        priceTextField = new JTextField(15);
        contentPane.add(priceTextField);

        weightTextField = new JTextField(15);
        contentPane.add(weightTextField);

        sizeTextField = new JTextField(15);
        contentPane.add(sizeTextField);

        JLabel creditLabel = new JLabel("Credit:");
        contentPane.add(creditLabel);

        JLabel memoryLabel = new JLabel("Memory:");
        contentPane.add(memoryLabel);

        addMobileButton = new JButton("Add Mobile");
        contentPane.add(addMobileButton);
        addMobileButton.addActionListener(this);

        addMp3Button = new JButton("Add MP3");
        contentPane.add(addMp3Button);
        addMp3Button.addActionListener(this);

        initialCreditTextField = new JTextField(15);
        contentPane.add(initialCreditTextField);

        initialMemoryTextField = new JTextField(15);
        contentPane.add(initialMemoryTextField);

        clearButton = new JButton("Clear");
        contentPane.add(clearButton);
        clearButton.addActionListener(this);

        displayAllButton = new JButton("Display All");
        contentPane.add(displayAllButton);
        displayAllButton.addActionListener(this);

        JLabel phoneNumLabel = new JLabel("Phone No:");
        contentPane.add(phoneNumLabel);

        JLabel durationLabel = new JLabel("Duration:");
        contentPane.add(durationLabel);

        JLabel downloadLabel = new JLabel("Download:");
        contentPane.add(downloadLabel);

        JLabel dispNumLabel = new JLabel("Display Number:");
        contentPane.add(dispNumLabel);

        phoneNumberTextField = new JTextField(15);
        contentPane.add(phoneNumberTextField);

        durationTextField = new JTextField(15);
        contentPane.add(durationTextField);

        downloadSizeTextField = new JTextField(15);
        contentPane.add(downloadSizeTextField);

        displayNumberTextField = new JTextField(15);
        contentPane.add(displayNumberTextField);

        makeCallButton = new JButton("Make A Call");
        contentPane.add(makeCallButton);
        makeCallButton.addActionListener(this);

        downloadMusicButton = new JButton("Download Music");
        contentPane.add(downloadMusicButton);
        downloadMusicButton.addActionListener(this);

        frame.pack();
        frame.setVisible(true);
    }

    /**
     * The main method allows the program to be run without BlueJ.
     */ 
    public static void main(String[] args)
    {
        GadgetShop calculator = new GadgetShop();
    }

    /**
     * Find which button triggered the event and call the appropriate method.
     */
    public void actionPerformed(ActionEvent event)
    {
        String command = event.getActionCommand();
        if (command.equals("Add Mobile")) {
            addMobile();
        }
        if (command.equals("Add MP3")) {
            addMp3();
        }
        if (command.equals("Display All")) {
            displayAll();
        }
        if (command.equals("Make A Call")) {
            makeCall();
        }
        if (command.equals("Download Music")) {
            downloadMusic();
        }
        if (command.equals("Clear")) {
            clear();
        }
    }

    public String getModel()
    {
        String model
           = modelTextField.getText();
        return model;
    }

    public String getSize()
    {
        String size
           = sizeTextField.getText();
        return size;
    }

    public String getNumber()
    {
        String phoneNumber
           = phoneNumberTextField.getText();
        return phoneNumber;
    }

    public int getWeight()
    {
        int weight
           = Integer.parseInt(weightTextField.getText());
        return weight;
    }

    public double getPrice()
    {
        double price
           = Double.parseDouble(priceTextField.getText());
        return price;
    }

    public int getCredit()
    {
        int credit
           = Integer.parseInt(initialCreditTextField.getText());
        return credit;
    }

    public int getMemory()
    {
        int memory
           = Integer.parseInt(initialMemoryTextField.getText());
        return memory;
    }

    public int getDuration()
    {
        int duration
           = Integer.parseInt(durationTextField.getText());
        return duration;
    }

    public int getDownloadSize()
    {
        int downloadSize
           = Integer.parseInt(downloadSizeTextField.getText());
        return downloadSize;
    }

    public int numberOfGadgets()
    {
        return gadgets.size();
    }

Ниже приведен метод, который я использовал для получения правильного номера дисплея

    public int getDisplayNumber()
    {
        int displayNumber = -1;

        try {
            displayNumber
              = Integer.parseInt(displayNumberTextField.getText());
            if(displayNumber < 0) {
                JOptionPane.showMessageDialog(frame, 
                   "Please enter a positive number");
            }
            else if(displayNumber > numberOfGadgets()) {
                JOptionPane.showMessageDialog(frame, 
                   "Please enter a number in the correct range");
            }
        }
        catch(NumberFormatException exception) {
        }
        return displayNumber;
    }
    public void addMobile()
    {
        Mobile mobile = new Mobile(getCredit(), getModel(), getSize(), getWeight(), getPrice());
        gadgets.add(mobile);
    }

    public void addMp3()
    {
        MP3 mp3 = new MP3(getMemory(), getModel(), getSize(), getWeight(), getPrice());
        gadgets.add(mp3);
    }

    public void displayAll()
    {
        int displayNumber = 0;
        for(Gadget gadget : gadgets) {
            System.out.println((displayNumber++)+(": "));
            gadget.print();
            System.out.println();   // empty line between items
        }
    }

Ниже приведены методы, которые яраньше звонил и скачивал музыку.

    public void makeCall()
    {
        int displayNumber = getDisplayNumber();
        Mobile mobile = (Mobile) gadgets.get(displayNumber);
        Mobile mobCall = new Mobile(makeCall());
    }

    public void downloadMusic()
    {
        int displayNumber = getDisplayNumber();
        MP3 mp3 = (MP3) gadgets.get(displayNumber);
        MP3().downloadMusic();
    }

    public void clear()
    {
        modelTextField.setText("");
        sizeTextField.setText("");
        phoneNumberTextField.setText("");
        weightTextField.setText("");
        priceTextField.setText("");
        initialCreditTextField.setText("");
        initialMemoryTextField.setText("");
        durationTextField.setText("");
        downloadSizeTextField.setText("");
        displayNumberTextField.setText("");
    }
}

Ниже мой Мобильный подкласс

public class Mobile extends Gadget
{
    // instance variables - replace the example below with your own
    private int credit;

    /**
     * Constructor for objects of class Mobile
     */
    public Mobile(int myCredit, String theModel, String theSize, int theWeight, double thePrice)
    {
        // initialise instance variables
        super(theModel, theSize, theWeight, thePrice);
        credit = myCredit;
    }

    /**
     * This is an accessor method that allows the user to view the balance of credit remaining in the mobile phone.
     */
    public int getCredit()
    {
        return credit;
    }

    /**
     * This is a mutator method that allows the user to top up the credit on their mobile phone.
     */
    public void addCredit(int topUp)
    {
        if (topUp > 0) {
            credit = credit + topUp;
        }
        else {
            System.out.println("Please enter an amount greater than 0.");
        }
    }

    /**
     * This is a mutator method that allows the user to enter the phone number that they'd like to call and the duration of that call in minutes.
     */
    public void makeCall(String number, int minutes)
    {
        if (credit >= minutes) {
            System.out.println("You called this number: " + number + " for the duration of: " + minutes + " minute/s.");
            credit = credit - minutes;
            System.out.println(" ");
            System.out.println("You now have " + credit + " minutes of calling credit remaining in your balance.");
        }
        else {
            System.out.println("Sorry, but you have an insufficient amount of credit to make this call.");
        }
    }

    /**
     * This output method displays certain specifications of the mobile device such as the: Model, size, weight and price. The amount of credit remaining in the mobile is also displayed.
     */
    public void print()
    {
        super.print();
        System.out.println("You have " + credit + " minutes of credit remaining.");
    }
}

Ниже Гаджет Суперкласс

public class Gadget
{
    // instance variables
    private String model;
    private String size;
    private int weight;
    private double price;


    /**
     * Constructor for objects of class Gadget
     */
    public Gadget(String theModel, String theSize, int theWeight, double thePrice)
    {
        // initialised instance variables
        model = theModel;
        size = theSize;
        weight = theWeight;
        price = thePrice;
    }

    /**
     * This is an accessor method that returns the model number of the gadget.
     */
    public String getModel()
    {
        return model;
    }

    /**
     * This is an accessor method that returns the size of the gadget.
     */
    public String getSize()
    {
        return size;
    }

    /**
     * This is an accessor method that returns the weight of the gadget.
     */
    public int getWeight()
    {
        return weight;
    }

    /**
     * This is an accessor method that returns the price of the gadget.
     */
    public double getPrice()
    {
        return price;
    }

    /**
     * This is an output method that displays the model, size, weight and price of an object to the user.
     */
    public void print()
    {
        System.out.println("Model: " + model);
        System.out.println("Size: " + size);
        System.out.println("Weight: " + weight);
        System.out.println("Price: " + price);
    }
}

Я бы очень хотелценим всю помощь, которую я могу получить.Спасибо.

...