我正在为小工具商店创建一个GUI,用于存储小工具(例如手机和MP3播放器)的详细信息,但我不知道如何将这些详细信息的值作为类型的新对象存储到其中。小工具类型的ArrayList。
我做了很多次试验和错误,但是不能确定我是否真正在进步。
import java.util.ArrayList;
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 JButton addMobileButton;
private JFrame frame;
private ArrayList<Gadget> gadgets;
/**
* The GUI is created in the constructor.
*/
public GadgetShop()
{
// initialise instance variables
ArrayList<Gadget> gadgets = new ArrayList<Gadget>();
frame = new JFrame("The Gadget Shop");
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
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);
initialCreditTextField = new JTextField(15);
contentPane.add(initialCreditTextField);
addMobileButton = new JButton("Add Mobile");
contentPane.add(addMobileButton);
addMobileButton.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();
}
}
下面是对象详细信息的getMethods
public String getModel()
{
String model
= modelTextField.getText();
return model;
}
public String getSize()
{
String size
= sizeTextField.getText();
return size;
}
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;
}
下面是我的setMethod,用于将Mobile类型的对象存储到我认为是错误的Gadget ArrayList中
public void addMobile()
{
String mobile =
getModel(); //Is this how I call the get Methods??
getPrice();
getWeight();
getSize();
getCredit();
gadgets = new Mobile();
gadgets.add(mobile); //I get an error with the .add part
}
}
我期望出现错误,因为我不确定我是否首先正确地创建了ArrayList。