0

I am using BlueJ and i am trying to call a method from another class. To be more specific i am trying to complete the following.

When the download music button is pressed, if a suitable value has been entered for the display number:

  • The display number is used to get the gadget, cast as MP3, from the array list.
  • The method to download music in the MP3 class is called with the download size entered.

Here is the gadgetshop class that builds the GUI and the place where i want to call the downloadMusic method. the method for the button is called downloadMusic.

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

public class GadgetShop implements ActionListener
{
//Array List 
private ArrayList<Gadget>gadgets;


public void actionPerformed(ActionEvent event)
{

    if (command.equals("Download Music"))
    {
        downloadMusic();
    }
}  

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

public void displayAll()
{
    for(Gadget gadget : gadgets)
    {
        gadget.print();
        System.out.println();
    }
}


public void downloadMusic()
{
}

public int getDisplay()
{
    int gadgetDisplay = 0;
    try
    {
        gadgetDisplay = Integer.parseInt(displayText.getText());

    if (gadgetDisplay<= 0)
    {
      JOptionPane.showMessageDialog
      (frame, "Please enter a positive amount");  
    }
    }
    catch(NumberFormatException exception)
    {
        JOptionPane.showMessageDialog
        (frame, "Please enter a positive amount");
    }
    return gadgetDisplay;
}

public String getDownload()
{
    String gadgetDownload;
    gadgetDownload = downloadText.getText();
    return gadgetDownload;
}
}

This is the MP3 class

public class MP3 extends Gadget
{

private int memory;

public MP3(int theWeight, double thePrice, String theModel, String theSize, int theMemory)
{
    super(theWeight,thePrice, theModel, theSize);
    memory = theMemory;
}

public void downloadMusic(String music, int MusicSize)
{
    if(MusicSize>memory)
    //if statement saying if size is greater than memory then display the follwing statemnt saying there is not enough memory
    {
        System.out.println("Not Enough Memory");
    }
    else
    // else statement opposite to the above statement saying if music size is less than or equal to the memory display the following statement
    {
        memory = memory - MusicSize;
        System.out.println("Download Successfull. "+ "\nMusic Name: "+ music + "\nMemory Left: " + memory);
    }
}
4

1 回答 1

0

其他类”(带有按钮)必须具有您要调用的方法的类的实例。MP3您可以在构造函数中创建一个实例GadgetShop并将其存储为实例变量。然后在你的按钮监听器调用中

mp3Instance.downloadMusic("music", 42);
于 2013-04-17T11:44:38.820 回答