我想这是一个真正的新手问题,但我无法在这里找到任何答案,在我的java书或其他地方。从JComboBox返回对象
我想用Swing构建一个GUI,我可以注册不同种类的酒。我想要我的葡萄酒类(将有一个葡萄酒超级类和三个子类:红色,白色和玫瑰)包含一些字符串和整数(名称,年份等)和一堆对象,如国家,地区,房子和更多。
我创建了葡萄酒对象从一个JPanel现在由JTextArea
的名称,并为国家JComboBox
的,我用一个for循环,从一个储存在一个对象国收集名称变量填充我的组合框数组列表。
这是我玫瑰酒的形式,其他人看起来也一样。
class RoseWineForm extends JPanel {
private JTextField wineName = new JTextField(15);
private JComboBox countryBox = new JComboBox();
public RoseWineForm() {
JPanel line1 = new JPanel();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
line1.add(new JLabel("Namn: "));
line1.add(wineName);
add(line1);
JPanel line2 = new JPanel();
line2.add(new JLabel("Ursprungsland"));
line2.add(countryBox);
for(Country c : listOfCountries) {
countryBox.addItem(c.getCountryName());
}
add(line2);
}
public String getName() {
return wineName.getText();
}
public Country getCountry() {
return ;
}}
这里是将用户的形式ActionListener
class NewWineListener implements ActionListener {
public void actionPerformed (ActionEvent a) {
try {
JComboBox wineColor = (JComboBox) a.getSource();
if (wineColor.getSelectedIndex() == 0) {
RedWineForm red = new RedWineForm();
int answer = JOptionPane.showConfirmDialog(TestVin.this, red, "Nytt rött vin",
JOptionPane.OK_CANCEL_OPTION);
} else if (wineColor.getSelectedIndex() == 1) {
WhiteWineForm white = new WhiteWineForm();
int answer = JOptionPane.showConfirmDialog(TestVin.this, white, "Nytt vitt vin",
JOptionPane.OK_CANCEL_OPTION);
} else {
RoseWineForm rose = new RoseWineForm();
int answer = JOptionPane.showConfirmDialog(TestVin.this, rose, "Nytt rosé vin",
JOptionPane.OK_CANCEL_OPTION);
}
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(TestVin.this, "Fel inmatning!");
}
}
这里是我的祖国类:
public class Country {
private String countryName;
public Country(String countryName) {
this.countryName = countryName;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String newCountryName) {
if (newCountryName == null || newCountryName.trim().isEmpty()) {
System.out.println("You have to set a name.");
} else {
countryName = newCountryName;
}}
public String toString() {
return countryName;
}
}
我的问题是:当我选择在这个国家的名字我的组合框如何返回对象,而不仅仅是名为countryName
的String
,以便我可以使用变量String name
创建我的酒对象d Country country
?
希望你能理解那里有一些瑞典人。
源代码中的单个空白空白行是所有* *所需的。 '{'之后或'}'之前的空行通常也是多余的。 –