0

データベースで製品を作成できるプロジェクトに取り組んでいます。編集可能なコンボ ボックスを備えたフォームが含まれているため、新製品の既存のメーカーを選択するか、製品と共に作成する新しいメーカーの名前を入力できます。

コンボ ボックスには、Manufacturer オブジェクトのコレクションが取り込まれます (これらは toString() を実装しているため、意味のあるものを表示します)。

コンボボックスからの出力を処理するためのロジックは、現在次のように実装されています。

Object mfr = mfctrCombo.getSelectedItem ();
Product newPrd = new Product ();

// If the mfr is a string then we need to create a new Manufacturer
if (mfr instanceof String) {
    Manufacturer newMfr = new Manufacturer ();
    newMfr.setName ((String) mfr);
    // Logic for persisting the new Manufacturer goes here
    newPrd.setManufacturer (newMfr);
} else if (mfr instanceof Manufacturer) {
    newPrd.setManufacturer ((Manufacturer) mfr);
}
// Logic for persisting the new Product goes here

これは機能しますが、mfr オブジェクトをキャストする必要はないように思えます。if ブロックの開始時に instanceof チェックを行っているため、ブロック内のオブジェクトの型が事実上わかっています。ブロックの開始時にチェックを行った後、ブロック内でキャストを行う必要は本当にありますか? 必須ではないように思えます。

私はJavaを初めて使用しますが、コンボボックスで行っていることはベストプラクティスではないことはかなり確信していますが、それは具体的に期限が設定された大学のプロジェクトのためであり、この目的のために、別の質問のためにコンボ ボックスに入力するより良い方法について議論したいと思います。

4

4 に答える 4

0

instanceofJava 7を使用している場合、キャストなしの解決策があると思います:

ComboBoxModel<Manufacturer> model = new DefaultComboBoxModel<>();
// Initialize model with existing manufacturers model.addElement(...)
JComboBox<Manufacturer> mfctrCombo = new JComboBox<>(model);

// ...

int selectedIndex = mfctrCombo.getSelectedIndex();
Product newPrd = new Product ();

if (selectedIndex == -1) {
    // The user provided a string then we need to create a new Manufacturer    
    Manufacturer newMfr = new Manufacturer ();
    newMfr.setName (mfctrCombo.getSelectedItem().toString());
    // Logic for persisting the new Manufacturer goes here
    newPrd.setManufacturer (newMfr);
} else {
    ComboBoxModel<Manufacturer> model = mfctrCombo.getModel();
    newPrd.setManufacturer (model.getElementAt(selectedIndex);
}

toString()さらに、 GUI にテキストを表示するために依存する必要はありません(toString()そのように使用することを意図したものではありません。国際化の場合には問題になります) 。代わりに、質問JComboBoxの設定ラベルと値

于 2013-08-24T23:59:05.167 に答える