これは本当に初心者の質問だと思いますが、私のJavaブックや他の場所ではここで答えが見つかりません。JComboBoxからオブジェクトを返します
私はさまざまな種類のワインを登録できるSwingを使用してGUIを構築しようとしています。私はいくつかの文字列と整数(名前、年など)とカントリー、ディストリクトのようなオブジェクトの束で構成するために、私のワインクラス(ワインのスーパークラスと3つのサブクラス:赤、白とバラがあります)家など。
私はJPanelからワインオブジェクトを作成しました。これは名前のためにで構成されています。コンボボックスには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 ;
}}
ここでここで
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!");
}
}
フォームにユーザーを送信しActionListener
は、私の国のクラスです。
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;
}
}
私の質問は:私は私の国の名前を選択すると、コンボボックスString
String
というだけでなく、オブジェクトを返すにはどのようにすればいいですか?String name
という変数でワインオブジェクトを作成できるように、countryName
d Country country
?
あなたはそこにスウェーデン語があることを理解できますか?
ソースコード内の空白行が空白で1行だけ必要です。 '{'の前または '}'の前の空白行も通常は冗長です。 –