我正在使用BlueJ,我正在尝试从另一个类调用一个方法。更具体一点,我想完成以下内容。
按下载音乐按钮时,如果为显示屏编号输入了合适的值:
这是构建GUI的gadgetshop类,以及我想调用downloadMusic方法的地方。该按钮的方法称为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;
}
}
这是MP3类
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);
}
}
答案 0 :(得分:0)
“其他类”(带按钮)必须具有您要调用的方法的类的实例。您可以在MP3
的构造函数中创建GadgetShop
的实例,并将其存储为实例变量。然后在你的按钮监听器调用
mp3Instance.downloadMusic("music", 42);