diff --git a/megamek/src/megamek/client/ui/swing/ClientGUI.java b/megamek/src/megamek/client/ui/swing/ClientGUI.java index a03ec3907ac..b3894b7028b 100644 --- a/megamek/src/megamek/client/ui/swing/ClientGUI.java +++ b/megamek/src/megamek/client/ui/swing/ClientGUI.java @@ -3023,7 +3023,7 @@ public Optional getDisplayedWeapon() { } public Optional getDisplayedAmmo() { - return Optional.ofNullable(unitDisplay.wPan.getSelectedAmmo()); + return unitDisplay.wPan.getSelectedAmmo(); } @Override diff --git a/megamek/src/megamek/client/ui/swing/unitDisplay/WeaponPanel.java b/megamek/src/megamek/client/ui/swing/unitDisplay/WeaponPanel.java index a4244c3639f..e62be0e6659 100644 --- a/megamek/src/megamek/client/ui/swing/unitDisplay/WeaponPanel.java +++ b/megamek/src/megamek/client/ui/swing/unitDisplay/WeaponPanel.java @@ -30,11 +30,7 @@ import java.awt.event.ActionListener; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.List; -import java.util.Objects; +import java.util.*; import javax.swing.*; import javax.swing.event.ListSelectionEvent; @@ -1348,16 +1344,16 @@ public WeaponMounted getSelectedWeapon() { } /** - * - * @return the AmmoMounted currently selected by the ammo selector combo box, - * not the linked ammo per se. + * @return the AmmoMounted currently selected by the ammo selector combo box, if any. + * The returned AmmoMounted may or may not be the ammo that is linked to the weapon. */ - public AmmoMounted getSelectedAmmo() { + public Optional getSelectedAmmo() { int selected = m_chAmmo.getSelectedIndex(); - if (selected == -1 || vAmmo == null) { - return null; + if ((selected == -1) || (vAmmo == null) || (selected >= vAmmo.size())) { + return Optional.empty(); + } else { + return Optional.of(vAmmo.get(selected)); } - return vAmmo.get(m_chAmmo.getSelectedIndex()); } /** @@ -1948,8 +1944,7 @@ private void displaySelected() { // Update the range display to account for the selected ammo, or the loaded ammo // if none is selected - int curDisplayed = m_chAmmo.getSelectedIndex(); - AmmoMounted mAmmo = (curDisplayed != -1 && vAmmo != null) ? vAmmo.get(curDisplayed) : mounted.getLinkedAmmo(); + AmmoMounted mAmmo = getSelectedAmmo().orElse(mounted.getLinkedAmmo()); if (mAmmo != null) { updateRangeDisplayForAmmo(mAmmo); } @@ -2073,6 +2068,7 @@ private void displaySelected() { vAmmo.add(mountedAmmo); m_chAmmo.addItem(formatAmmo(mountedAmmo)); + int curDisplayed = m_chAmmo.getSelectedIndex(); if (curDisplayed != -1) { nCur = curDisplayed; } else if ((mounted.getLinked() != null) &&