La manière la plus efficace pour éduquer vos colons est de construire une école et d’assigner une unité experte comme enseignant. L’enseignant transformera alors un colon libre en un expert du même type. Les enseignants peuvent aussi améliorer les petits délinquants en serfs, et les serfs en colons libres.
Certaines compétences peuvent aussi être apprises des indigènes, en envoyant un colon libre ou un serf vivre dans un campement indigène pendant un tour. Et certaines compétences peuvent aussi être apprises par l’expérience, en mettant un colon libre au travail sur une case de la colonie. Les colons libres travaillant dans les champs et les forêts autour de vos colonies accumulent jusqu’à 200 points d’expérience, ce qui leur donne quatre pourcent de chances d’être améliorés.
+colopedia.concepts.education.description=La manière la plus efficace pour éduquer vos colons est de construire une école et d’assigner une unité experte comme enseignant. L’enseignant transformera alors un colon libre en un expert du même type. Les enseignants peuvent aussi améliorer les petits délinquants en serfs, et les serfs en colons libres.
Certaines compétences peuvent aussi être apprises des indigènes, en envoyant un colon libre ou un serf vivre dans une agglomération indigène pendant un tour. Et certaines compétences peuvent aussi être apprises par l’expérience, en mettant un colon libre au travail sur une case de la colonie. Les colons libres travaillant dans les champs et les forêts autour de vos colonies accumulent jusqu’à 200 points d’expérience, ce qui leur donne quatre pourcent de chances d’être améliorés.
colopedia.concepts.efficiency.name=Efficacité colopedia.concepts.efficiency.description=L'efficacité de vos colonies dépend de leur soutien à l'idée d'indépendance. Si 50 % des colons soutiennent la cause des rebelles, la colonie reçoit un bonus de production de + 1. Dès que 100 % des colons deviennent des rebelles, la prime à la production passe à + 2.
En revanche, si le nombre des royalistes dépasse la limite de mauvais gouvernement, la colonie encourt une peine de production de -1. Si le nombre des royalistes dépasse la limite de très mauvais gouvernement, la pénalité de production passe à -2. Ces deux limites dépendent du niveau de difficulté et peuvent être vérifiées dans le rapport sur le niveau de difficulté.
Afin d'augmenter l'efficacité d'une colonie, vous devez réduire sa population ou produire davantage de cloches de la liberté.
colopedia.concepts.fortification.name=Fortification @@ -2564,10 +2576,10 @@ colopedia.nationType.aggression=Agressivité colopedia.nationType.settlementNumber.average=Moyen colopedia.nationType.settlementNumber.high=Important colopedia.nationType.settlementNumber.low=Faible -colopedia.nationType.settlementNumber=Nombre de lieux habités : +colopedia.nationType.settlementNumber=Nombre d’agglomérations : colopedia.nationType.regions=Régions habitées : colopedia.nationType.skills=Compétences enseignées : -colopedia.nationType.typeOfSettlements=Type de lieux habités : +colopedia.nationType.typeOfSettlements=Type d’agglomération : colopedia.nationType.units=Unités de départ : colopedia.terrain.colonistProduction=Production de colons colopedia.terrain.colonyCenterTile=Case centrale de colonie @@ -2590,7 +2602,7 @@ colopedia.unit.offensivePower=Potentiel offensif : colopedia.unit.price=Prix en Europe : colopedia.unit.productionBonus={{plural:%number%|one=Modificateur|other=Modificateurs}} de production : colopedia.unit.requirements=Exigences : -colopedia.unit.school=Établissement de formation : +colopedia.unit.school=Peut former en : colopedia.unit.skill=Compétence : report.labour.allColonists=Tous les colons report.labour.amateursWorking=amateurs @@ -2615,40 +2627,60 @@ report.labour.unitTotal.tooltip=%unit% ou devenant %unit% report.labour.workingAs=Emploi report.labour.workingAsOther=autre report.colony.arriving.description=%colony%: nouveau %unit% {{plural:%turns%|one=au prochain tour|other=dans %turns% tours}} +report.colony.arriving.summary.description=Le nombre moyen de tours avant qu’un nouveau colon arrive dans les colonies de ce continent report.colony.birth.description=Nombre de tours avant qu'un nouveau colon arrive ou soit affamé report.colony.explore.description=Nombre de carreaux à Découvrir autour de la colonie report.colony.explore.header=E report.colony.exploring.description=%colony% aurait intérêt à explorer {{plural:%amount%|one=une case|other=%amount% cases}} +report.colony.exploring.summary.description=Nombre total de cases de colonie qui bénéficieront de l’exploration pour ce continent. report.colony.grow.description=Nombre d'unités que la colonie peut développer sans nuire à sa production report.colony.grow.header=+ report.colony.growing.description=%colony% peut croître de {{plural:%amount%|one=une unité|other=%amount% unités}} sans nuire à sa production +report.colony.growing.summary.description=Le nombre total de colons qui peuvent rejoindre les colonies de ce continent sans nuire à la production report.colony.improve.description=Unités qui pourraient améliorer la production. report.colony.improve.header=Améliorer -report.colony.improving.description=%colony%: Pour produire %amount% de plus de %goods%, remplacez %oldUnit% par %unit% -report.colony.wanting.description=%colony%: Pour produire %amount% de plus de %goods%, ajoutez %unit% +report.colony.improving.description=%colony% à %location% : Pour produire %amount% de plus de %goods%, remplacez %oldUnit% par %unit% +report.colony.improving.summary.description=Unités (type et nombre) qui peuvent être bénéfiques aux colonies de ce continent report.colony.making.blocking.description=%colony%: %amount% %goods% nécessaires pour %buildable% {{plural:%turns%|one=au prochain tour|other=dans %turns% tours}} report.colony.making.constructing.description=%colony%: %buildable% terminé {{plural:%turns%|one=au prochain tour|other=dans %turns% tours}} report.colony.making.description=Ce que cette colonie fait report.colony.making.educating.description=%colony%: %teacher% diplômé {{plural:%turns%|one=au prochain tour|other=dans %turns% tours}} +report.colony.making.educationVacancy.description=%colony% : {{plural:%number%|one=une place d’étudiant est vacante|other=%number% places d’étudiant sont vacantes}} +report.colony.making.educating.summary.description=Unités (type et nombre) des écoles de ce continent en instance de diplômation report.colony.making.header=Fabrication report.colony.making.noconstruction.description=%colony%: Pas de construction en cours report.colony.making.noteach.description=%colony%: %teacher% n'a pas d'étudiant +report.colony.making.summary.description=Le déficit de %goods% par tour est dû aux exigences de construction non satisfaites sur ce continent report.colony.name.description=La liste des colonies report.colony.name.header=Colonie -report.colony.plow.description=Nombre de cases de colonie qui bénéficieront du Labourage -report.colony.plow.header=P -report.colony.plowing.description=%colony% aurait intérêt à labourer {{plural:%amount%|one=une case|other=%amount% cases}} -report.colony.production.description=%colony%: production nette de %goods% = %amount% -report.colony.production.export.description=%colony%: la production nette de %goods% est de %amount% (exporté au-dessus de %export%) +report.colony.name.summary.description=La région de ce continent contenant le plus de ces colonies +report.colony.production.description=%colony% : %amount% de %goods% sont produits +report.colony.production.export.description=%colony% : %amount% de %goods% sont produits (exporté au-dessus de %export%) report.colony.production.header=Production net de %goods% -report.colony.production.high.description=%colony%: production nette de %goods% = %amount%, totale {{plural:%turns%|one=le prochain tour|other=dans %turns% tours}} -report.colony.production.low.description=%colony%: production nette de %goods% = %amount%, disparue {{plural:%turns%|one=le prochain tour|other=dans %turns% tours}} -report.colony.production.waste.description=%colony%: production nette de %goods% = %amount%, l'entrepôt va déborder, %waste% sera perdu -report.colony.road.description=Nombre de cases de colonie qui bénéficieraient d'une construction de route -report.colony.road.header=R -report.colony.roadBuilding.description=%colony% aurait intérêt à construire {{plural:%amount%|one=une route|other=%amount% routes}} +report.colony.production.high.description=%colony% : %amount% de %goods% sont produits, sera plein {{plural:%turns%|one=le prochain tour|other=dans %turns% tours}} +report.colony.production.low.description=%colony% : %amount% de %goods% consommés, sera vide {{plural:%turns%|one=le prochain tour|other=dans %turns% tours}} +report.colony.production.maxConsumption.description=%colony% : %amount% de %goods% sont consommés (peut en consommer %more% de plus) +report.colony.production.maxProduction.description=%colony% : %amount% de %goods% sont produits (%more% de plus pourraient l’être) +report.colony.production.summary.description=La quantité de marchandises produite ou consommée +report.colony.production.waste.description=%colony% : %amount% de %goods% sont produits, l’entrepôt va déborder, %waste% seront perdus +report.colony.tile.clearForest.description=%colony% aurait intérêt à nettoyer {{plural:%amount%|one=une case|other=%amount% cases}} +report.colony.tile.clearForest.specific.description=%colony% aurait intérêt à nettoyer %location% +report.colony.tile.clearForest.header=C +report.colony.tile.clearForest.header.description=Nombre de cases de colonie qu’il serait intéressant de nettoyer. +report.colony.tile.clearForest.summary.description=Nombre total de cases de colonie qui auraient intérêt à être nettoyées sur ce continent. +report.colony.tile.plow.description=%colony% aurait intérêt à labourer {{plural:%amount%|one=une case|other=%amount% cases}} +report.colony.tile.plow.specific.description=%colony% aurait intérêt à labourer %location% +report.colony.tile.plow.header=P +report.colony.tile.plow.header.description=Nombre de cases de colonie qui auraient intérêt à être labourées. +report.colony.tile.plow.summary.description=Nombre total de cases de colonie qui auraient intérêt à être labourées sur ce continent. +report.colony.tile.road.description=%colony% aurait intérêt à construire {{plural:%amount%|one=une route|other=%amount% routes}} +report.colony.tile.road.specific.description=%colony% aurait intérêt à construire une route à %location% +report.colony.tile.road.header=R +report.colony.tile.road.header.description=Nombre de cases de colonie qui auraient intérêt à construire une route. +report.colony.tile.road.summary.description=Nombre total de cases de colonie qui auraient intérêt à construire une route sur ce continent. report.colony.shrinking.description=%colony% doit être réduite de {{plural:%amount%|one=une unité|other=%amount% unités}} pour améliorer sa production report.colony.starving.description=%colony%: famine {{plural:%turns%|one=au prochain tour|other=dans %turns% tours}} +report.colony.wanting.description=%colony% à %location% : Pour produire %amount% de plus de %goods%, ajoutez %unit% report.continentalCongress.available=Disponible report.continentalCongress.elected=Élu : %turn% report.continentalCongress.none=(aucun) @@ -2670,51 +2702,52 @@ report.foreignAffair.sonsOfLiberty=Fils de la Liberté report.foreignAffair.stance=Relations report.highScores.colonies=Nombre de colonies : report.highScores.difficulty=Difficulté : -report.highScores.governor=Gouverneur %name% de %nation% +report.highScores.governor=Gouverneur %name% de {{tag:country|%nation%}} report.highScores.independence=Indépendance déclarée : report.highScores.nation=Nation : -report.highScores.nationType=Avantage national : -report.highScores.president=Président %name% de %nation% +report.highScores.nationType=Atout national : +report.highScores.president=Président %name% de {{tag:country|%nation%}} report.highScores.retired=Abandon : report.highScores.score=Pointage : report.highScores.turn=Année : report.highScores.units=Nombre d’unités : report.indian.chieftain=Nom du chef : report.indian.mostHated=Le plus détesté -report.indian.noKnownSettlements=Aucun lieu connu. -report.indian.numberOfSettlements=Lieux connus : +report.indian.noKnownSettlements=Aucune agglomération connue. +report.indian.numberOfSettlements=Agglomérations connues : report.indian.tension=Tension report.indian.tradeInterests=Intérêts commerciaux report.indian.tribeTension=Tension Tribale : -report.indian.typeOfSettlements=Type de lieu : +report.indian.typeOfSettlements=Type d’agglomération : report.labour.details.name=Détails du rapport de travail report.production.selectGoods=Sélectionner les biens report.production.update=Mettre à jour report.requirements.badAssignment=%colony% a un %expert% qui travaille actuellement comme %expertWork%, alors qu’un %nonExpert% travaille comme %nonExpertWork%. La production serait plus importante si les colons échangeaient leurs emplois. report.requirements.canTrainExperts={{plural:2|%unit%}} peuvent être formées à -report.requirements.clearTile=%type% vers %direction% de %colony% serait intéressant pour le défrichage. -report.requirements.exploreTile=%type% vers %direction% de %colony% serait intéressant pour l'exploration. +report.requirements.exploreTile=%location% serait intéressant à explorer. report.requirements.met=Toutes les conditions sont réunies. report.requirements.missingGoods=%colony% fabrique des %goods%, mais elle a besoin de plus de %input%. report.requirements.misusedExperts=Il y a des {{plural:2|%unit%}} qui ne travaillent pas comme %work% à report.requirements.noExpert=%colony% fabrique des %goods%, mais elle n’a pas de %unit%. -report.requirements.plowCenter=%colony% aurait intérêt à labourer sa case. -report.requirements.plowTile=%type% vers %direction% de %colony% aurait intérêt à être labouré -report.requirements.roadTile=%type%vers %direction% de %colony% aurait intérêt à construire une route. +report.requirements.tile.clearForest=%location% aurait intérêt à être nettoyé. +report.requirements.tile.plow=%location% aurait intérêt à être labouré. +report.requirements.tile.road=%location% aurait intérêt à construire une route. report.requirements.severalExperts=Plusieurs {{plural:2|%unit%}} sont présentes à report.requirements.surplus=Un surplus de %goods% est produit à report.trade.afterTaxes=Solde après taxes report.trade.beforeTaxes=Solde avant taxes report.trade.cargoUnits=Unités en transit -report.trade.hasCustomHouse=* Cette colonie a une douane ; ces marchandises sont exportées. +report.trade.export=Exporter %goods% au-delà de %amount% +report.trade.hasCustomHouse=* Cette colonie a une douane et peut exporter des marchandises. report.trade.totalDelta=Total de la production report.trade.totalUnits=Total des unités report.trade.unitsSold=Nb acheté/vendu report.turn.filter=Ne pas afficher ce type de message (%type%) report.turn.ignore=Ignorer ce message (Colonie : %colony% ; marchandises : %goods%) -report.turn.playerNation=%nation% de %player% +report.turn.playerNation={{ucfirst:{{tag:country|%nation%}}}} de %player% aboutPanel.copyright=Copyright © 2002-2015 L’équipe FreeCol aboutPanel.legalDisclaimer=FreeCol est un logiciel libre ; vous pouvez le redistribuer et/ou le modifier au titre des clauses de la Licence Publique Générale GNU, telle qu’elle est publiée par la Free Software Foundation dans sa version 2, ou dans une version ultérieure. +aboutPanel.manual=Téléchargement du Manuel de FreeCol aboutPanel.officialSite=Site officiel : aboutPanel.sfProject=Projet SourceForge : aboutPanel.version=Version : @@ -2737,7 +2770,7 @@ colonyPanel.buildQueue=Créer la playlist colonyPanel.colonyUnits=Unités de la colonie colonyPanel.inPort=Au port colonyPanel.outsideColony=Hors de la colonie -colonyPanel.producing=Production en cours : +colonyPanel.producing=production en cours : colonyPanel.reducePopulation=Si vous réduisez la population à une valeur inférieure à %number%, %colony% ne pourra plus construire de %buildable%. colonyPanel.setGoods=Ensemble de biens colonyPanel.traceWork=Trace de travail @@ -2752,8 +2785,8 @@ confirmDeclarationDialog.areYouSure.no=Peut-être plus tard confirmDeclarationDialog.areYouSure.text=Permettez-nous de nous affranchir de la tyrannie injuste de %monarch% et déclarer l’indépendance de nos colonies de la couronne ! confirmDeclarationDialog.areYouSure.yes=Vivre libre ou mourir ! confirmDeclarationDialog.createFlag=et nos ennemis trembleront à la vue de notre bannière rebelle. -confirmDeclarationDialog.defaultCountry=États-Unis de %nation% -confirmDeclarationDialog.defaultNation=%nation% libre +confirmDeclarationDialog.defaultCountry=États-Unis {{tag:plur|%nation%}} +confirmDeclarationDialog.defaultNation={{ucfirst:{{tag:country|%nation%}}}} libre confirmDeclarationDialog.enterCountry=Désormais, notre pays doit être connu comme confirmDeclarationDialog.enterNation=et chaque citoyen de notre glorieuse nation doit être fier d’être connu comme flag.background.FESSES=Coupé @@ -2804,19 +2837,19 @@ negotiationDialog.add=Ajouter negotiationDialog.cancel=Annuler negotiationDialog.clear=Nettoyer negotiationDialog.contact.tutorial=Vous rencontrez d’autres Européens. Ils seront en compétition avec vous pour les terres et les richesses, et peuvent même partir en guerre contre vous. Mais une fois que Jan de Witt a rejoint le Congrès continental, vous pourrez commercer avec eux. -negotiationDialog.demand=Le %nation% exige de %otherNation% +negotiationDialog.demand={{ucfirst:{{tag:country|%nation%}}}} exige de {{tag:country|%otherNation%}} negotiationDialog.exchange=en échange de negotiationDialog.goldAvailable=(%amount% or disponible) -negotiationDialog.offer=Le %nation% offre à %otherNation% +negotiationDialog.offer={{ucfirst:{{tag:country|%nation%}}}} offre à {{tag:country|%otherNation%}} negotiationDialog.send=Envoyer negotiationDialog.title.contact=Rencontre des autres européens negotiationDialog.title.diplomatic=Négociation diplomatique negotiationDialog.title.trade=Négociation commerciale negotiationDialog.title.tribute=Demande de tribut -editSettlementDialog.removeSettlement=Supprimer le lieu habité -editSettlementDialog.removeSettlement.text=Voulez-vous supprimer ce lieu habité ? -emigrationDialog.chooseImmigrant=Choisissez l'unité que vous voulez voir émigrer d’Europe. -endTurnDialog.areYouSure={{plural:%number%|one=L'unité suivante attend|other=Les unités suivantes attentent}} toujours les ordres, ou {{plural:%number%|one=a été commandée|other=ont été commandées}} à attendre. Êtes-vous sûr de vouloir terminer le tour maintenant ? +editSettlementDialog.removeSettlement=Supprimer l’agglomération +editSettlementDialog.removeSettlement.text=Voulez-vous supprimer cette agglomération ? +emigrationDialog.chooseImmigrant=Choisissez l’unité que vous voulez voir émigrer d’Europe. +endTurnDialog.areYouSure={{plural:%number%|one=L’unité suivante attend|other=Les unités suivantes attendent}} toujours les ordres, ou {{plural:%number%|one=a|other=ont}} reçu l’ordre d’attendre. Êtes-vous sûr de vouloir terminer le tour maintenant ? endTurnDialog.name=Fin du tour errorPanel.showLogFile=Afficher le fichier journal europePanel.leaveColonists=Faire voile sur %newWorld% en laissant les colons sur le quai ? @@ -2825,16 +2858,16 @@ europePanel.transaction.price=Prix :\t%gold% europePanel.transaction.purchase=Acheter %amount% %goods% @%gold% europePanel.transaction.sale=Vendre %amount% %goods% @%gold% europePanel.transaction.tax=-%tax% % :\t%gold% -findSettlementPanel.displayAll=Trouver tous les campements -findSettlementPanel.displayOnlyEuropean=Trouver uniquement les campements européens -findSettlementPanel.displayOnlyNatives=Trouver uniquement les campements indigènes -findSettlementPanel.name=Trouver un campement -firstContactDialog.meeting.natives=Rencontre avec les indigènes... -firstContactDialog.meeting.natives.tutorial=Vous avez rencontré des indigènes. Envoyez vos éclaireurs à leurs campements afin d’en savoir plus sur eux, et vos domestiques contractuels et vos colons libres pour apprendre de leur part. Envoyez vos navires et vos convois de charriot à leurs campements si vous voulez commercer avec eux. -firstContactDialog.meeting.AZTEC=La nation aztèque... -firstContactDialog.meeting.INCA=L’empire inca... -firstContactDialog.welcomeOffer.text=Les %nation% vous accueillent. Nous sommes une glorieuse nation de %camps% %settlementType%. Pour célébrer notre amitié, nous vous offrons généreusement en cadeau la terre que vous occupez actuellement. Acceptez-vous notre traité et de demeurer avec nous en paix fraternelle ? -firstContactDialog.welcomeSimple.text=Les %nation% vous accueillent. Nous sommes une glorieuse nation de %camps% %settlementType%. Acceptez-vous notre traité et de demeurer avec nous en paix fraternelle ? +findSettlementPanel.displayAll=Trouver toutes les agglomérations +findSettlementPanel.displayOnlyEuropean=Trouver uniquement les agglomérations européennes +findSettlementPanel.displayOnlyNatives=Trouver uniquement les agglomérations indigènes +findSettlementPanel.name=Trouver une agglomération +firstContactDialog.meeting.natives=Rencontre avec les indigènes +firstContactDialog.meeting.natives.tutorial=Vous avez rencontré des indigènes. Envoyez vos éclaireurs à leurs agglomérations afin d’en savoir plus sur eux, et vos domestiques contractuels et vos colons libres pour apprendre de leur part. Envoyez vos navires et vos convois de chariots à leurs campements si vous voulez commercer avec eux. +firstContactDialog.meeting.aztec=La nation aztèque +firstContactDialog.meeting.inca=L’empire inca +firstContactDialog.welcomeOffer.text=Les {{tag:people|%nation%}} vous accueillent. Nous sommes une glorieuse nation de %camps% %settlementType%. Pour célébrer notre amitié, nous vous offrons généreusement en cadeau la terre que vous occupez actuellement. Acceptez-vous notre traité et de demeurer avec nous en paix fraternelle ? +firstContactDialog.welcomeSimple.text=Les {{tag:people|%nation%}} vous accueillent. Nous sommes une glorieuse nation de %camps% %settlementType%. Acceptez-vous notre traité et de demeurer avec nous en paix fraternelle ? abandonColony.no=Annuler abandonColony.text=Devons-nous vraiment abandonner cette colonie ? abandonColony.yes=Abandonner @@ -2848,12 +2881,12 @@ stopServer.no=Annuler stopServer.text=Un serveur fonctionne déjà sur le port indiqué. stopServer.yes=Arrêter le serveur freeColProgressBar.turnsToComplete=(Tours : %number%) -indianSettlementPanel.indianCapital=Capitale des %nation% -indianSettlementPanel=Campement %nation% -indianSettlementPanel.learnableSkill=La compétence suivante peut être apprise dans ce lieu : -indianSettlementPanel.highlyWanted=Ce lieu est très intéressé par le commerce de : -indianSettlementPanel.otherWanted=Les autres marchandises pouvant êtres vendues dans ce lieu sont : -indianSettlementPanel.mostHated=La nation la plus haïe de cette implantation: +indianSettlementPanel.indianCapital=Capitale des {{tag:people|%nation%}} +indianSettlementPanel=Agglomération {{tag:fem|%nation%}} +indianSettlementPanel.learnableSkill=La compétence suivante peut être apprise dans cette agglomération : +indianSettlementPanel.highlyWanted=Cette agglomération est très intéressée par le commerce de : +indianSettlementPanel.otherWanted=Les autres marchandises pouvant êtres vendues dans cette agglomération sont : +indianSettlementPanel.mostHated=La nation la plus haïe de cette agglomération : infoPanel.defenseBonus=%bonus%% de défense infoPanel.endTurn=Presser [Entrée] pour finir le tour. infoPanel.movementCost=%cost% mouvement @@ -2875,12 +2908,13 @@ freecol.map.Australia=Australie freecol.map.Caribbean_basin=Bassin des Caraïbes mapSizeDialog.mapSize=Sélectionner la taille de la carte modifierFormat.unknown=??? +modifierFormat.scopeMethod.isIndian.name=indigènes monarchDialog.default=Un message de la Couronne newPanel.editDifficulty=Modifier la difficulté newPanel.getServerList=Récupérer la liste des serveurs newPanel.joinMultiPlayerGame=Rejoindre une partie multijoueur newPanel.newGamePanel=Paramétrer une nouvelle partie -newPanel.nationalAdvantages=Avantages nationaux +newPanel.nationalAdvantages=Atouts nationaux newPanel.publicServer=Serveur public newPanel.showDifficulty=Afficher la difficulté newPanel.singlePlayerGame=Jeu solitaire @@ -2925,7 +2959,7 @@ serverListPanel.gameState.1=En fonction serverListPanel.gameState.2=Terminé serverListPanel.players=Joueurs startGamePanel.iAmReady=Prêt -info.noEuropeans=La condition de la victoire de vaincre tous les autres Européens est déjà remplie. Activer une autre nation européenne ou ajouter des conditions de victoire supplémentaires. +info.noEuropeans=La condition de victoire de vaincre tous les autres Européens est déjà remplie. Activez une autre nation européenne ou ajoutez des conditions de victoire supplémentaires. memoryManager.freeMemory=Libre memoryManager.maxMemory=Max memoryManager.totalMemory=Total @@ -2934,7 +2968,7 @@ tilePanel.label=%label% (%x%, %y%) tilePanel.movementCost=Coût de mouvement : tilePanel.owner=Propriétaire : tilePanel.region=Région : -tilePanel.settlement=Campement : +tilePanel.settlement=Agglomération : tradeRouteInputPanel.addStop=Ajouter un nouvel arrêt tradeRouteInputPanel.allColonies=Toutes les colonies tradeRouteInputPanel.destinationLabel=Destination @@ -2963,7 +2997,7 @@ warehouseDialog.lowLevel.shortDescription=M’alerter quand les réserves baisse warehouseDialog.name=Entrepôt workProductionPanel.zeroThreshold=Aucune production négative nameCache.base.colony=Colonie -nameCache.base.settlement=Campement +nameCache.base.settlement=Agglomération nameCache.base.ship=Navire nameCache.base.tradeRoute=Nouvelle route commerciale nameCache.lostCityRumour.cityName.0=Aira @@ -2979,7 +3013,7 @@ nameCache.mercenaries.2=Charles-Alexandre, margrave de Brandebourg-Ansbach nameCache.mercenaries.3=Charles I, duc de Brunswick-Wolfenbüttel nameCache.season.default=Saison %number% nameCache.season.0=Printemps -nameCache.season.1=L'automne +nameCache.season.1=Automne model.nation.english.region.land.1=Virginie model.nation.english.region.land.3=Pennsylvanie model.nation.english.region.land.4=Terre-Neuve @@ -2994,6 +3028,8 @@ model.nation.danish.region.land.1=Indes occidentales danoises model.nation.danish.region.land.2=Groenland model.nation.portuguese.region.land.2=Brésil model.nation.swedish.settlementName.1=Finlande +model.nation.apache.settlementName.0=Mescaléro +model.nation.sioux.settlementName.0=Tétonwan model.nation.tupi.settlementName.46=Tijuca model.nation.tupi.settlementName.47=Tukan model.nation.tupi.settlementName.48=Tupinambá @@ -3016,7 +3052,7 @@ prompt.selectOwner=Sélectionner le propriétaire prompt.selectRole=Sélectionner le rôle prompt.selectTurnsToSkip=Sélectionner les tours à sauter prompt.selectUnitType=Sélectionner le type d’unité -prompt.stepRNG=Étape de Générateur aléatoire de nombre (%value%) +prompt.stepRNG=Pas du générateur de nombres aléatoires (%value%) prompt.selectGold=Sélectionner le montant d’or installer.FreeCol.description=L’application FreeCol et les fichiers de données. installer.FreeColLanguage.autodetect=Détecter automatiquement au lancement du jeu @@ -3034,7 +3070,7 @@ installer.SoundEffects.description=Les effets sonores du jeu. installer.SoundEffects=Effets sonores installer.SourceCode.description=Le code source utilisé pour cette distribution. Ces fichiers sont destinés aux développeurs et n’ajoutent aucune nouvelle fonctionnalité au jeu. installer.SourceCode=Code source -installer.UserFiles.freecol=Le dossier de l’application FreeCol (seulement les installations pour un seul utilisateur) +installer.UserFiles.freecol=Le dossier de l’application FreeCol (pour une installation mono-utilisateur) installer.UserFiles.home=Le dossier de base de l’utilisateur installer.UserFiles.other=Définissez un dossier personnalisé installer.UserFiles=Choisissez l’emplacement des paramètres personnalisés et des parties sauvegardées : diff --git a/data/strings/FreeColMessages_gl.properties b/data/strings/FreeColMessages_gl.properties index 8df03e861..96244c06f 100644 --- a/data/strings/FreeColMessages_gl.properties +++ b/data/strings/FreeColMessages_gl.properties @@ -197,8 +197,9 @@ cli.no-memory-check=saltar a comprobación da memoria cli.no-sound=executar o FreeCol sen son cli.private=iniciar un servidor privado (non publicado no servidor meta) cli.seed=proporcionar un GRAN para o xerador de números pseudo-aleatorios -cli.server-name=especificar un NOME personalizado para o servidor +# Fuzzy cli.server=iniciar un servidor autónomo no porto especificado +cli.server-name=especificar un NOME personalizado para o servidor cli.splash=mostrar unha imaxe de pantalla do FICHEIRO mentres se carga o xogo cli.tc=cargar a conversión total co NOME dado cli.timeout=número de segundos que o servidor agarda por unha resposta á pregunta @@ -262,7 +263,6 @@ colopediaAction.goods.name=Produtos colopediaAction.nations.name=Nacións colopediaAction.nationTypes.name=Vantaxes nacionais colopediaAction.resources.name=Bonificacións por recursos -colopediaAction.skills.name=Habilidades colopediaAction.terrain.name=Tipos de terreo colopediaAction.units.name=Unidades colopediaAction.name=%object% (Colopedia) @@ -1305,6 +1305,7 @@ model.improvement.road.description=Camiño model.improvement.road.name=Camiño model.improvement.road.occupationString=R model.limit.independence.coastalColonies.name=Límite de colonia costeira +# Fuzzy model.limit.independence.coastalColonies.description=Necesitas, polo menos, %limit% colonias costeiras para poder declarar a independencia. model.limit.independence.rebels.name=Límite de rebeldes model.limit.independence.rebels.description=Polo menos, o %limit%% dos teus colonos debe apoiar a independencia. @@ -1640,6 +1641,7 @@ model.colony.badGovernment=O goberno de %colony% é ineficiente. Hai penalizaci model.colony.goodGovernment=A eficiencia do goberno mellorou! O asentamento rebelde en %colony% agora iguala ou supera o %number% por cento. model.colony.governmentImproved1=O goberno de %colony% mellorou, pero aínda é moi ineficiente. Aínda hai penalizacións á produción. model.colony.governmentImproved2=O goberno de %colony% mellorou. Xa non hai penalizacións á produción. +# Fuzzy model.colony.insufficientProduction=%outputAmount% máis de %outputType% poderían ser producidos por %colony%, se só tivésemos %inputAmount% máis de %inputType%. model.colony.lostGoodGovernment=A eficiencia do goberno diminuíu! O asentamento rebelde en %colony% xa non iguala ou supera o %number% por cento. A colonia xa non consigue bonificacións de produción. model.colony.lostVeryGoodGovernment=A eficiencia do goberno diminuíu! O asentamento rebelde en %colony% xa non iguala ou supera o %number% por cento. Perdéronse algunhas bonificacións de produción. @@ -1657,21 +1659,29 @@ model.direction.SW.name=suroeste model.direction.W.name=oeste model.direction.NW.name=noroeste model.historyEventType.abandonColony.description=Abandonaches a colonia de %colony%. +# Fuzzy model.historyEventType.cityOfGold.description=Os %nation% descubriron %city%, unha das sete cidades de ouro, e mais un tesouro de %treasure% de ouro. +# Fuzzy model.historyEventType.colonyConquered.description=A túa colonia %colony% é conquistada polos %nation%. +# Fuzzy model.historyEventType.colonyDestroyed.description=A túa colonia %colony% é destruída polos %nation%. # Fuzzy model.historyEventType.conquerColony.description=Atréveste a aceptar as nosas xenerosas condicións e evitas os pagamentos? Esta duplicidade segará a amarga recompensa do noso descontento. # Fuzzy model.historyEventType.declareIndependence.description=Destruíches o asentamento %settlement% dos %nation%. +# Fuzzy model.historyEventType.destroyNation.description=Os %nation% destrúen os %nativeNation%. model.historyEventType.discoverNewWorld.description=Descubriches o Novo Mundo. +# Fuzzy model.historyEventType.discoverRegion.description=Os %nation% descubriron %region%. model.historyEventType.foundColony.description=Estableciches a colonia de %colony%. model.historyEventType.foundingFather.description=%father% únese ao congreso continental. model.historyEventType.independence.description=Conseguiches a independencia da Coroa. +# Fuzzy model.historyEventType.meetNation.description=Coñeciches os %nation%. +# Fuzzy model.historyEventType.nationDestroyed.description=Os %nation% xa non están presentes no Novo Mundo. +# Fuzzy model.historyEventType.spanishSuccession.description=Os %loserNation% ceden o conxunto de todas as súas colonias que teñen no Novo Mundo aos %nation%. model.indianSettlement.mostHatedNone=Ningún model.indianSettlement.mostHatedUnknown=Descoñecida @@ -1722,8 +1732,10 @@ model.messageType.warehouseCapacity.name=Capacidade do almacén model.messageType.warning.name=Avisos model.monarch.action.addToRef.text=A Coroa engadiu %number% {{plural:%number%|%unit%}} á forza expedicionaria real. Os líderes coloniais expresan preocupación. model.monarch.action.addToRef.no=Feito +# Fuzzy model.monarch.action.declarePeace.text=Aceptamos de boa gana un tratado de paz cos %nation%. model.monarch.action.declarePeace.no=Feito +# Fuzzy model.monarch.action.declareWar.text=A insolencia dos %nation% obríganos a declarar a guerra contra eles! model.monarch.action.declareWar.no=Feito # Fuzzy @@ -1775,6 +1787,7 @@ model.noClaimReason.worked.description=Xa hai outro asentamento usando estas ter model.player.forces=Forzas de %nation% model.player.independentMarket=Europa model.player.startGame=Despois de meses no mar, finalmente chegaches á costa dun continente descoñecido. Navega {{tag:%direction%|west=ao oeste|east=ao leste|default=cara ao vento}} a fin de descubrir o Novo Mundo e reclamar a Coroa. +# Fuzzy model.player.waitingFor=Agardando por: %nation% model.regionType.coast.name=Litoral model.regionType.coast.unknown=Rexión costeira descoñecida @@ -1829,9 +1842,9 @@ model.unit.underRepair=Reparación (%turns%) model.unit.unitState.active=- model.unit.unitState.fortified=F model.unit.unitState.fortifying=F -model.unit.unitState.improving=# model.unit.unitState.inColony=B model.unit.unitState.sentry=V +# Fuzzy model.unit.unitState.skipped=S model.unit.unitState.toAmerica=G model.unit.unitState.toEurope=G @@ -1872,6 +1885,7 @@ model.colony.warehouseSoonFull=O teu almacén de %colony% superará a súa capac model.colony.warehouseWaste=O teu almacén de %colony% superou a súa capacidade de %goods%. Desbotáronse %waste% unidades. model.colony.workersEvicted=En %colony%, os teus colonos non poden seguir traballando en %location% debido á presenza de %enemyUnit%. model.colonyTile.resourceExhausted=Recurso %resource% esgotado en %colony% +# Fuzzy model.game.spanishSuccession=Súa Excelencia, a Guerra de Sucesión Española acabou en Europa. No Tratado de Utrecht, os %loserNation% foi forzado a ceder todas as colonias do Novo Mundo aos %nation%! model.indianSettlement.mission.denounced=O teu misioneiro en %settlement% foi denunciado e executado! model.indianSettlement.mission.destroyed=O teu misioneiro en %settlement% morreu na destrución do asentamento. @@ -1881,6 +1895,7 @@ model.player.autoRecruit=Os disturbios relixiosos en %europe% provocan a emigrac model.player.colonyGoodsParty.harbour=Os teus colonos de %colony% desbotaron %amount% unidades de %goods% no porto en protesta polas taxas de impostos da Coroa! model.player.colonyGoodsParty.horses=Os teus colonos de %colony% liberaron %amount% cabalos en protesta contra os impostos inxustos da Coroa! model.player.colonyGoodsParty.landLocked=Os teus colonos de %colony% queimaron %amount% unidades de %goods% no mercado local en protesta polas taxas de impostos da Coroa! +# Fuzzy model.player.dead.european=Súa Excelencia, os %nation% declararon unha retirada incondicional dos asuntos do Novo Mundo! model.player.dead.native=Súa Excelencia, os %nation% foron destruídos. model.player.disaster.bankruptcy.start=Non pagaches polo mantemento de todas as construcións. Hanse aplicar penalizacións de produción. @@ -1892,12 +1907,16 @@ model.player.foundingFatherJoinedCongress=%foundingFather% uniuse ao congreso!\n model.player.interventionForceArrives=Chega a forza de intervención prometida! model.player.soLDecrease=Diminuíron ata o %newSoL% por cento os membros dos Fillos da Liberdade nas túas colonias! model.player.soLIncrease=O número de membros dos Fillos da Liberdade nas túas colonias aumentou un %newSoL% por cento! +# Fuzzy model.player.stance.alliance.declared=Súa Excelencia, os %nation% teñen unha alianza connosco! model.player.stance.alliance.others=Súa Excelencia, o %attacker% ten unha alianza con %defender%. +# Fuzzy model.player.stance.ceaseFire.declared=Súa Excelencia, os %nation% aceptaron un alto o fogo connosco! model.player.stance.ceaseFire.others=Súa Excelencia, o %attacker% aceptou un alto o fogo con %defender%. +# Fuzzy model.player.stance.peace.declared=Súa Excelencia, os %nation% están en paz connosco! model.player.stance.peace.others=Súa Excelencia, o %attacker% está en paz con %defender%. +# Fuzzy model.player.stance.war.declared=Malas novas, súa Excelencia, os %nation% declaráronnos a guerra! model.player.stance.war.others=Súa Excelencia, o %attacker% declarou a guerra con %defender%. combat.automaticDefence=O teu %unit% en %colony% tomou as armas para defender a colonia! @@ -1913,6 +1932,7 @@ combat.enemyShipEvaded=%enemyUnit% %enemyNation% librouse dun ataque de %unit%. combat.enemyShipSunk=%unit% afundiu aos %enemyUnit% %enemyNation%! combat.equipmentCaptured=Coidado, os guerreiros %nation% adquiriron %equipment%! combat.goodsStolen=%enemyUnit% %enemyNation% rouba %amount% de %goods% a %colony%! +# Fuzzy combat.indianPlunder=%enemyUnit% %enemyNation% saquea %amount% de %colony%. combat.indianRaid=Os nosos espías informan de que os %nation% invadiron a colonia %colonyNation% de %colony%. combat.indianSurprise=Os %nation% fixeron un ataque sorpresa en %colony%, que alarmou os nosos colonos. Os xefes dos %nation% rexeitan calquera implicación. @@ -1969,6 +1989,7 @@ main.javaVersion=Recoméndase a versión %minVersion% do Java para executar o Fr main.memory=Debes asignar máis de %memory% bytes de memoria para o JVM.\n Reinicia o FreeCol con: java -Xmx%minMemory%M -jar FreeCol.jar main.userDir.fail=O FreeCol non pode atopar os directorios axeitados para gardar os datos de usuario. O programa pode continuar, pero posiblemente encontrarás algún erro. client.baseData=Non se puido atopar o directorio de datos de base %dir%.\n O FreeCol non puido atopar os ficheiros de datos.\n Asegúrate de que están presentes.\n Se o FreeCol está buscando nun directorio incorrecto, entón\n executa o xogo cun parámetro na liña de comandos:\n --freecol-dataNajúčinnejší spôsob ako vzdelávať Vašich kolonistov je postaviť základnú školu a priradiť nejakého experta/majstra ako učiteľa. Učiteľ potom vyučí slobodného kolonistu svojmu remeslu. Učitelia sú schopný zmeniť kriminálnika na sluhu a sluhu na slobodného kolonistu.
Niektoré zručnosti sa dajú naučiť aj od domorodcov a to tak, že k nim do osady pošlete žiť slobodného kolonistu alebo sluhu. Niektoré zručnosti sa dajú naučiť aj vďaka skúsenostiam. Slobodný kolonista, ktorý pracuje na určitom políčku v kolónii získava za svoju prácu skúsenosti čo mu dáva šancu na dosiahnutie špecializácie.
colopedia.concepts.efficiency.name=Účinnosť colopedia.concepts.efficiency.description=Efektívnosť Vašich kolónií závisí od ich podpory myšlienky o nezávislosti. Ak 50% kolonistov podporuje nezávislosť, kolónii sa udelí výrobný bonus +1. Akonáhle sa podpora zvýši na 100%, kolónii sa udelí výrobný bonus +2.
Na druhej strane ak počet feudalistov presiahne stanovený limit pre zlú vládu, kolóniu zasiahne zníženie výroby na -1. Ak počet feudalistov presiahne limit per veľmi zlú vládu, zníženie výroby sa zvýši na -2. Tieto dva limity závisia od úrovne obtiažnosti a môžete si ich skontrolovať kliknutím na hlásenie úrovne obtiažnosti.
V záujme zvýšenia efektívnosti kolónie musíte znížiť jej populáciu alebo zvýšiť výrobu Zvonov slobody.
+colopedia.concepts.fortification.name=Opevnenie +colopedia.concepts.fortification.description=Jednotky sa môžu na políčku opevniť (vybudovaním dočasných zákopov a prekážok), aby tým zvýšili svoju obranyschopnosť. Plne sa opevniť trvá jeden ťah. Opevnenie taktiež chráni pred prepadnutím a opevnené delostrelectvo už nie je považované za "nechránené" aj keď útok poškodí opevnenie. Opevnenie poskytuje obranný bonus len v prípade neprítomnosti iných zvýhodňujúcich obranných vlastností, preto opevnenie na horách alebo v kolónii s pevnosťou alebo veľkou pevnosťou nepridá žiadny obranný bonus. colopedia.concepts.independence.name=Nezávislosť colopedia.concepts.independence.description=
Hru začínate ako prieskumník s niekoľkými jednotkami k dispozícii. Kráľ od Vás očakáva, že v Novom svete založíte kolóniu a budete domov nosiť poklady a exotický tovar. Vy však máte iné plány: založiť nezávislý národ.
Na vyhlásenie nezávislosti potrebujete presvedčiť aspoň 50% populácie Vašich kolónií. To sa dá dosiahnuť výrobou takzvaných zvonov slobody, ktoré zároveň zvyšujú efektívnosť Vašich kolónií.
Určite si uvedomujete, že kráľa to nenechá chladným. Po vyhlásení nezávislosti musíte bojovať a zničiť Kráľovské expedičné sily (KES). Ak KES budú ovládať všetky Vaše prímorské kolónie, alebo najmenej 90% populácie, Vaša snaha o nezávislosť skončí neúspechom.
colopedia.concepts.interventionForce.name=Intervenčné sily @@ -2300,10 +2481,8 @@ colopedia.nationType.skills=Naučené zručnosti: colopedia.nationType.typeOfSettlements=Druh osád: colopedia.nationType.units=Počiatočné jednotky: colopedia.terrain.colonyCenterTile=Políčko centra kolónie -# Fuzzy colopedia.terrain.defenseBonus=Obranný bonus colopedia.terrain.description=Popis -# Fuzzy colopedia.terrain.movementCost=Cena presunu colopedia.terrain.resource=Možný zdroj colopedia.terrain.terrainImage=Obrázok terénu @@ -2320,7 +2499,7 @@ colopedia.unit.offensivePower=Útočná sila: colopedia.unit.price=Cena v Európe: colopedia.unit.productionBonus=Výrobná/é {{plural:%number%|one=úprava|other=úpravy}}: colopedia.unit.requirements=Požiadavky: -colopedia.unit.school=Požadovaná škola na výcvik: +colopedia.unit.school=Môže sa vyučiť v: colopedia.unit.skill=Úroveň zručností: report.labour.allColonists=Všetci kolonisti report.labour.amateursWorking=amatéri @@ -2352,11 +2531,9 @@ report.colony.exploring.description=kolónii %colony% by prospelo preskúmať {{ report.colony.grow.description=Počet jednotiek, ktoré môže kolónia vychovať bez toho, aby sa znížila výroba report.colony.grow.header=+ report.colony.growing.description=%colony% môže vychovať {{plural:%amount%|one=jednu jednotku||two=dve jednotky|three=tri jednotky|four=štyri jednotky|other=%amount% jednotiek}} bez toho, aby sa znížila výroba -# Fuzzy -report.colony.improve.description=Jednotky, ktoré by mohli zvýšiť výrobu s ohľadom na jednotky, ktoré už prácu vykonávajú +report.colony.improve.description=Jednotky, ktoré môžu zvýšiť výrobu. report.colony.improve.header=Vylepšiť -report.colony.improving.description=%colony%: Aby ste vyrábali o %amount% ks viac tovaru %goods%, vymeňte jednotku %oldUnit% za jednotku %unit% -report.colony.wanting.description=%colony%: Na vyrobenie o %amount% ks viac tovaru %goods%, pridajte jednotku %unit% +report.colony.improving.description=%colony% %location%: Aby ste vyrábali o %amount% ks viac tovaru %goods%, vymeňte jednotku %oldUnit% za jednotku %unit% report.colony.making.blocking.description=%colony%: %amount% ks tovaru %goods% bude treba na %buildable% {{plural:%turns%|one=na ďalší ťah|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} report.colony.making.constructing.description=%colony%: %buildable% budova dokončená {{plural:%turns%|one=na ďalší ťah|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} report.colony.making.description=Čo táto kolónia práve vytvára @@ -2366,22 +2543,24 @@ report.colony.making.noconstruction.description=%colony%: žiadne prebiehajúce report.colony.making.noteach.description=%colony%: učiteľ %teacher% nemá študenta report.colony.name.description=Zoznam kolónií report.colony.name.header=Kolónia -report.colony.plow.description=Počet políčok kolónie, ktoré by profitovali keby boli poorané -report.colony.plow.header=P -report.colony.plowing.description=kolónii %colony% by prospelo poorať {{plural:%amount%|one=jedno políčko|two=dve políčka|three=tri políčka|four=štyri políčka|other=%amount% políčok}} -report.colony.production.description=%colony%: čistá výroba tovaru %goods% = %amount% -report.colony.production.export.description=%colony%: čistá výroba tovaru %goods% je %amount% (exportovať nad %export%) +report.colony.production.description=%colony%: Vyrába sa %amount% ks tovaru %goods% +report.colony.production.export.description=%colony%: Vyrába sa %amount% ks tovaru %goods% (exportovať nad %export%) report.colony.production.header=Čistá výroba tovaru %goods% -report.colony.production.high.description=%colony%: čistá výroba tovaru %goods% = %amount%, plná {{plural:%turns%|one=ďalším ťahom|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} -report.colony.production.low.description=%colony%: čistá výroba tovaru %goods% = %amount%, zmizne {{plural:%turns%|one=ďaľším ťahom|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} -report.colony.production.waste.description=%colony%: čistá výroba tovaru %goods% = %amount%, sklad bude preplnený, %waste% ks bude vyhodených -report.colony.road.description=Počet políčok kolónie, ktoré by profitovali z postavenej cesty -report.colony.road.header=R -report.colony.roadBuilding.description=kolónii %colony% by prospelo postaviť {{plural:%amount%|one=cestu|two=dve cesty|three=tri cesty|four=štyri cesty|other=%amount% ciest}} +report.colony.production.high.description=%colony%: Vyrába sa %amount% ks tovaru %goods%, zaplnenie {{plural:%turns%|one=ďalším ťahom|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} +report.colony.production.low.description=%colony%: Spotrebúva sa %amount% ks tovaru %goods%, spotrebuje sa {{plural:%turns%|one=v ďaľšom ťahu|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} +report.colony.production.summary.description=Množstvo tovarov, ktoré sú vytvorené alebo spotrebované +report.colony.production.waste.description=%colony%: Vyrába sa %amount% ks tovaru %goods% , sklad bude preplnený, %waste% ks bude vyhodených +report.colony.tile.clearForest.header.description=Počet políčok kolónie, ktoré by profitovali z výrubu. +report.colony.tile.clearForest.summary.description=Celkový počet políčok kolónie na tomto kontinente, ktoré by profitovali z výrubu. +report.colony.tile.plow.description=kolónii %colony% by prospelo poorať {{plural:%amount%|one=jedno políčko|two=dve políčka|three=tri políčka|four=štyri políčka|other=%amount% políčok}} +report.colony.tile.road.header=R +report.colony.tile.road.header.description=Počet políčok kolónie, ktoré by profitovali z postavenej cesty. +report.colony.tile.road.summary.description=Celkový počet políčok kolónie na tomto kontinente, ktoré by profitovali z postavenej cesty. report.colony.shrinking.description=Kolónia %colony% musí byť zmenšená o{{plural:%amount%|one=jednu jednotku|two=dve jednotky|three=tri jednotky|four=štyri jednotky|other=%amount% jednotiek}} pre zvýšenie výroby report.colony.starving.description=%colony%: hladomor {{plural:%turns%|one=na ďalší ťah|two=za dva ťahy|three=za tri ťahy|four=za štyri ťahy|other=za %turns% ťahov}} -# Fuzzy -report.continentalCongress.elected=Zvolení: +report.colony.wanting.description=%colony% %location%: Na vyrobenie o %amount% kusov tovaru %goods% naviac pridajte jednotku %unit% +report.continentalCongress.available=Dostupný +report.continentalCongress.elected=Zvolený: %turn% report.continentalCongress.none=(žiadny) report.continentalCongress.recruiting=Nábor report.education.students=Potenciálny študenti @@ -2418,42 +2597,42 @@ report.indian.tension=Napätie report.indian.tradeInterests=Obchodné záujmy report.indian.tribeTension=Domorodé napätie: report.indian.typeOfSettlements=Druh osád: +report.labour.details.name=Podrobnosti Správy o zamestnanosti report.production.selectGoods=Výber tovaru report.production.update=Aktualizovať report.requirements.badAssignment=V kolónii %colony% pracuje %expert% ako %expertWork%, kým %nonExpert% pracuje ako %nonExpertWork%. Keby si títo kolonisti vymenili prácu, výroba by sa zvýšila. report.requirements.canTrainExperts={{plural:2 jedotky|%unit%}} sa môžu vytrénovať v -report.requirements.clearTile=%type% smerom na %direction% od kolónie %colony% bude profitovať z vyrúbania. -report.requirements.exploreTile=%type% smerom na %direction% od kolónie %colony% bude profitovať z prieskumu. +report.requirements.exploreTile=%location% by profitoval z prieskumu. report.requirements.met=Všetky požiadavky sú splnené. report.requirements.missingGoods=%colony% vyrába %goods%, ale potrebuje viac %input%. report.requirements.misusedExperts={{plural:2 jednotky|%unit%}} nepracujú ako %work% v kolónii report.requirements.noExpert=%colony% vyrába %goods%, ale nevyrába %unit%. -report.requirements.plowCenter=Kolónia %colony% by profitovala z poorania políčok. -report.requirements.plowTile=%type% smerom na %direction% od kolónie %colony% bude profitovať z poorania. -report.requirements.roadTile=%type% smerom na %direction% od kolónie %colony% bude profitovať z výstavby ciest. +report.requirements.tile.clearForest=%location% by mal prospech z výrubu. +report.requirements.tile.road=%location% by mal prospech zo stavby cesty. report.requirements.severalExperts={{plural:2 jednotky|%unit%}} sú prítomné v report.requirements.surplus=Vyrobil sa prebytok tovaru %goods% v report.trade.afterTaxes=Príjem po zdanení report.trade.beforeTaxes=Príjem pred zdanením report.trade.cargoUnits=Jednotiek v náklade -report.trade.hasCustomHouse=* Táto kolónia má vlastný dom, tento tovar je exportovaný. +report.trade.export=Vyvážať %goods% nad %amount% +report.trade.hasCustomHouse=* Táto kolónia má colnicu, a môže vyvážať tovar. report.trade.totalDelta=Výroba celkom report.trade.totalUnits=Jednotiek celkom report.trade.unitsSold=Kúpené alebo predané jednotky report.turn.filter=Nezobrazovať tento druh správ (%type%) report.turn.ignore=Ignorovať túto správu (Kolónia: %colony%, Tovar: %goods%) -report.turn.playerNation=%player% %nation% -# Fuzzy -aboutPanel.copyright=Copyright © 2002-2014 The FreeCol Team +report.turn.playerNation=%player% {{tag:country|%nation%}} +aboutPanel.copyright=Copyright © 2002-2015 FreeCol Team aboutPanel.legalDisclaimer=FreeCol je softvér zadarmo: môžete ho šíri a upravovať podľa všeobecných užívateľských podmienok publikovaných Free Software Foundation verzie 2 a viac. +aboutPanel.manual=Manuálne stiahnutie FreeCol aboutPanel.officialSite=Oficiálna stránka: aboutPanel.sfProject=SourceForge projekt: aboutPanel.version=Verzia: buildingToolTip.breeding=Potrebujete najmenej %number% {{plural:%number%|%goods%}} na chov %goods%. buildQueuePanel.buildings=Budovy buildQueuePanel.buildQueue=Stavebné poradie -# Fuzzy -buildQueuePanel.buyBuilding=Kúpiť budovu +buildQueuePanel.buyBuilding=Kúpiť %buildable% +buildQueuePanel.coastalOnly=Pobrežná kolónia buildQueuePanel.compactView=Kompaktné zobrazenie buildQueuePanel.currentlyBuilding=Budova: %buildable% buildQueuePanel.populationTooSmall=Populácia: %number% @@ -2464,12 +2643,14 @@ captureGoodsDialog.title=Korisť cargoPanel.cargoAndSpace=Náklad na %name% (%space% {{plural:%space%|one=miesto|other=miesta|default=miesto}}ostáva) chatPanel.message=Správa chooseFoundingFatherDialog.title=Nominovať Otca zakladateľa +colonyPanel.buildQueue=Stavebné poradie colonyPanel.colonyUnits=Jednotky kolónie colonyPanel.inPort=V prístave colonyPanel.outsideColony=Mimo kolónie -colonyPanel.producing=Vyrába: +colonyPanel.producing=vyrába: colonyPanel.reducePopulation=Ak znížite populáciu pod %number%, %colony% nebude môcť vybudovať %buildable%. colonyPanel.unitChange=Pri vstupe do kolónie sa Vaša jednotka %oldType% stala jednotkou %newType%. +colonyPanel.warehouse=Skladisko colonyPanel.bonusLabel=Bonus: %number%%extra% colonyPanel.populationLabel=Populácia: %number% colonyPanel.rebelLabel=Rebeli: %number% @@ -2479,8 +2660,8 @@ confirmDeclarationDialog.areYouSure.no=Možno neskôr confirmDeclarationDialog.areYouSure.text=Vzdajme sa nespravodlivej tyranie kráľa %monarch% a vyhlásme nezávislosť našich kolónii od kráľovstva. confirmDeclarationDialog.areYouSure.yes=Sloboda alebo smrť! confirmDeclarationDialog.createFlag=a naši nepriatelia sa budú triasť pri pohľade na náš nezlomný banner. -confirmDeclarationDialog.defaultCountry=Spojené štáty %nation% -confirmDeclarationDialog.defaultNation=Slobodný %nation% +confirmDeclarationDialog.defaultCountry=Spojené štáty {{tag:country|%nation%}} +confirmDeclarationDialog.defaultNation=Slobodný {{tag:country|%nation%}} confirmDeclarationDialog.enterCountry=Odteraz bude naša krajina známa ako confirmDeclarationDialog.enterNation=a každý občan nášho slávneho národa bude hrdý na to, že je známy ako flag.background.FESSES=Delené @@ -2525,14 +2706,16 @@ flag.unionShape.TRIANGLE=Trojuholník flag.unionShape.label=Union Shape constructionPanel.clickToBuild=Klikni na stavenisko pre výber stavby budovy alebo vytvorenie jednotky. constructionPanel.turnsToComplete=(Ťahov na dokončenie: %number%) +difficultyDialog.name=Obtiažnosť negotiationDialog.accept=Súhlasiť negotiationDialog.add=Pridať negotiationDialog.cancel=Zrušiť negotiationDialog.clear=Vyčistiť negotiationDialog.contact.tutorial=Stretáte kolegov Európanov. Budú s Vami súťažiť o pôdu a bohatstvo a možno Vám aj vyhlásia vojnu. Ale potom ako sa Jan de Witt pripojil ku Kontinentálnemu kongresu môžete s nimi obchodovať. -negotiationDialog.demand=%nation% požaduje od %otherNation% +negotiationDialog.demand={{tag:country|%nation%}} požaduje od {{tag:country|%otherNation%}} negotiationDialog.exchange=výmenou za -negotiationDialog.offer=%nation% za %otherNation% +negotiationDialog.goldAvailable=(%amount% zlata k dispozícii) +negotiationDialog.offer={{tag:country|%nation%}} ponúka {{tag:country|%otherNation%}} negotiationDialog.send=Poslať negotiationDialog.title.contact=Stretnutie kolegov Európanov negotiationDialog.title.diplomatic=Diplomatické vyjednávanie @@ -2554,10 +2737,10 @@ findSettlementPanel.displayAll=Nájsť všetky osady findSettlementPanel.displayOnlyEuropean=Nájsť iba európske osady findSettlementPanel.displayOnlyNatives=Nájsť iba pôvodné osady findSettlementPanel.name=Nájsť osadu -firstContactDialog.meeting.natives=Stretnutie s domorodcami... +firstContactDialog.meeting.natives=Stretnutie s domorodcami firstContactDialog.meeting.natives.tutorial=Stretli ste sa s domorodcami. Pošlite do ich osád svojich prieskumníkov, aby ste sa o nich dozvedeli viac a sluhov a slobodných kolonistov, aby ste sa od nich učili. Pošlite do ich osád svoje vozy a lode ak si s nimi prajete obchodovať. -firstContactDialog.meeting.AZTEC=Národ Aztékov... -firstContactDialog.meeting.INCA=Ríša Inkov... +firstContactDialog.meeting.aztec=Národ Aztékov +firstContactDialog.meeting.inca=Ríša Inkov firstContactDialog.welcomeOffer.text=Víta Vás národ %nation%. Náš slávny národ sa skladá z %camps% %settlementType%. Na oslavu nášho priateľstva Vám veľkoryso darujeme pozemok na ktorom sa práve nachádzate. Chcete s nami žiť v mieri ako bratia? firstContactDialog.welcomeSimple.text=Víta Vás národ %nation%. Náš slávny národ sa skladá z %camps% %settlementType%. Chcete s nami žiť v mieri ako bratia? abandonColony.no=Zrušiť @@ -2579,11 +2762,15 @@ indianSettlementPanel.learnableSkill=V tejto osade sa dá naučiť nasledovná z indianSettlementPanel.highlyWanted=Táto osada sa veľmi zaujíma o obchodovanie s: indianSettlementPanel.otherWanted=Ostatný tovar s ktorým sa dá obchodovať v tejto osade je: indianSettlementPanel.mostHated=V tejto osade najviac nenávidia národ: +infoPanel.defenseBonus=Obrana %bonus%% infoPanel.endTurn=Na ukončenie ťahu stlačte enter. +infoPanel.movementCost=Presun %cost% infoPanel.moves=Ťahy: +informationPanel.display=Zobraziť %object% loadingSavegameDialog.port=Brána: loadingSavegameDialog.privateMultiplayer=Súkromná hra pre viacerých hráčov loadingSavegameDialog.publicMultiplayer=Verejná hra pre viacerých hráčov +loadingSavegameDialog.serverName=Meno servera: loadingSavegameDialog.singlePlayer=Hra jedného hráča loadingSavegameDialog.name=Nahrávanie uloženej hry mapEditorTransformPanel.chooseResource=Vybrať zdroj @@ -2595,6 +2782,8 @@ freecol.map.America_large=Amerika (veľká) freecol.map.Australia=Austrália freecol.map.Caribbean_basin=Karibská oblasť mapSizeDialog.mapSize=Zvoliť veľkosť mapy +modifierFormat.unknown=??? +modifierFormat.scopeMethod.isIndian.name=domorodci monarchDialog.default=Správa z kráľovstva newPanel.editDifficulty=Upraviť obtiažnosť newPanel.getServerList=Získať zoznam serverov @@ -2619,6 +2808,7 @@ quickActionMenu.clearSpeciality=Vymazať špecialitu quickActionMenu.experience=Skúsenosti ako %job% : quickActionMenu.leaveTown=Opustiť mesto quickActionMenu.loadOnTo=Naložiť na %unit% +quickActionMenu.profit=Európske čisté imanie: %amount% quickActionMenu.teaching=Výučba %unit% quickActionMenu.upgrade=Pravdepodobnosť zvýšenia úrovne: rebelToolTip.100percent=Ťahov na dosiahnutie 100% @@ -2626,6 +2816,8 @@ rebelToolTip.50percent=Ťahov na dosiahnutie 50% rebelToolTip.changeLess=Odobrať kolonistov na zlepšenie bonusu rebelToolTip.changeMore=Pridať kolonistov k aktuálnemu bonusu rebelToolTip.nextMember=Ťahov na zvýšenie počtu rebelov +rebelToolTip.rebelLabel=Rebeli: %number% +rebelToolTip.royalistLabel=Rojalisti: %number% recruitPanel.clickOn=Kliknite na jednu z osôb pre rekrutovanie. Budete musieť zaplatiť %money% zlata za jeho prechod. On sám bude schopný zaplatiť za svoj prechod za %number% ťahy/ov. riverStyleDialog.text=Štýl rieky selectAmountDialog.text=Prosím, zadajte presné množstvo tovaru na prenos: @@ -2645,7 +2837,9 @@ info.noEuropeans=Podmienka poraziť všetkých ostatných Európanov už bola sp memoryManager.freeMemory=Voľná memoryManager.maxMemory=Max memoryManager.totalMemory=Celkom +tilePanel.defenseBonus=Obranný bonus: tilePanel.label=%label% (%x%, %y%) +tilePanel.movementCost=Cena presunu: tilePanel.owner=Vlastník: tilePanel.region=Oblasť: tilePanel.settlement=Osada: @@ -2675,16 +2869,39 @@ warehouseDialog.exportLevel.shortDescription=Nič neexportovať pod touto úrov warehouseDialog.highLevel.shortDescription=Upozorniť ma, keď zásoby presiahnu toto percento kapacity. warehouseDialog.lowLevel.shortDescription=Upozorniť ma, keď zásoby klesnú pod toto percento kapacity. warehouseDialog.name=Sklad -# Fuzzy -workProductionPanel.zeroThreshold=Žiadny +workProductionPanel.zeroThreshold=Žiadny záporná výroba nameCache.base.colony=Kolónia nameCache.base.settlement=Osada nameCache.base.ship=Loď nameCache.base.tradeRoute=Nová obchodná cesta +nameCache.lostCityRumour.cityName.0=Aira +nameCache.lostCityRumour.cityName.1=Anhuib +nameCache.lostCityRumour.cityName.2=Ansalli +nameCache.lostCityRumour.cityName.3=Ansesseli +nameCache.lostCityRumour.cityName.4=Ansodi +nameCache.lostCityRumour.cityName.5=Ansolli +nameCache.lostCityRumour.cityName.6=Con nameCache.mercenaries.0=Frederik II, kieža z Hesse-Kassel nameCache.mercenaries.1=Frederick Augustus, princ z Anhalt-Zerbst nameCache.mercenaries.2=Charles Alexander, gróf z Brandenburg-Ansbach nameCache.mercenaries.3=Charles I, vojvoda z Brunswick-Wolfenbüttel +nameCache.season.default=Ročné obdobie %number% +nameCache.season.0=Jar +nameCache.season.1=Jeseň +error.disasterAvoided=Katastrofa %disaster% sa vyhla kolónii %colony% +error.notAIColony=%colony% nie je kolónia UI +info.rgb=Hodnota RGB: %red%,%green%,%blue% +prompt.selectDisaster=Vyberte katastrofu +prompt.selectGoodsAmount=Vyberte množstvo tovaru +prompt.selectGoodsType=Vyberte druh tovaru +prompt.selectImmigration=Vyberte množstvo prisťahovalcov +prompt.selectLostCityRumour=Vyberte povesti o Stratenom meste +prompt.selectOwner=Vyberte vlastníka +prompt.selectRole=Vyberte úlohu +prompt.selectTurnsToSkip=Vyberte počet ťahov na preskočenie +prompt.selectUnitType=Vyberte typ jednotky +prompt.stepRNG=Krok generátora náhodných čísel (%value%) +prompt.selectGold=Vyberte množstvo zlata installer.FreeCol.description=FreeCol aplikácia a dátové súbory. installer.FreeColLanguage.autodetect=Autodetekcia pri spustení hry installer.FreeColLanguage.description=Toto nastavenie môžete zmeniť neskôr v hre pomocou menu Nastavenia. diff --git a/data/strings/FreeColMessages_sv_SE.properties b/data/strings/FreeColMessages_sv_SE.properties index 9a46f1bf5..975901ee8 100644 --- a/data/strings/FreeColMessages_sv_SE.properties +++ b/data/strings/FreeColMessages_sv_SE.properties @@ -1,6 +1,7 @@ # Messages for Swedish (svenska) # Exported from translatewiki.net # Author: Boivie +# Author: BroderTuck # Author: Cohan # Author: Harald Khan # Author: Jenniesarina @@ -52,6 +53,7 @@ all=Alla and=och browse=Bläddra cancel=Avbryt +client=Klient close=Stäng color=Färg connect=Anslut @@ -112,6 +114,7 @@ colopedia=Colopedia difficulty=Svårighetsgrad docks=Kajer dumpCargo=Dumpa lasten +finalResult=Slutresultat fortify=Befäst gold=Guld goldAmount=%amount% guld @@ -188,6 +191,7 @@ cli.default-locale=ange förvald locale (SPRÅK[_LAND[_VARIANT]]) cli.difficulty=ställ in SVÅRIGHETSNIVÅN cli.font=Ange förvalstypsnitt cli.freecol-data=ange i vilken KATALOG FreeCol lagrar data (har en underkatalog som heter 'base') +cli.full-screen=kör FreeCol i helskärmsläge cli.help=visa denna hjälpskärm cli.load-savegame=läs in angiven FIL med sparat spel cli.log-console=skriv logg i konsol utöver i fil @@ -200,14 +204,14 @@ cli.no-memory-check=hoppa över minneskontroll cli.no-sound=kör FreeCol utan ljud cli.private=starta en privat server (som ej publiceras på metaservern) cli.seed=tillhandahåller ett FRÖ till den pseudo-slumpmässiga nummergeneratorn -cli.server-name=ange ett anpassat NAMN för servern +# Fuzzy cli.server=starta en självständig server på angiven port +cli.server-name=ange ett anpassat NAMN för servern cli.splash=visa en uppstartsskärm med bildFIL när spelet läses in cli.tc=läs in den totala omvandlingen med angivet NAMN cli.timeout=antalet sekunder som servern väntar på ett svar på en fråga cli.version=visa versionnummer och avsluta -# Fuzzy -cli.windowed=kör FreeCol i fönsterläge istället för i helskärmsläge +cli.windowed=kör FreeCol i fönsterläge, med valfria MÅTT menuBar.colopedia=Colopedia menuBar.game=Spel menuBar.orders=Order @@ -224,6 +228,8 @@ menuBar.debug.addLiberty=Lägg till frihet till varje koloni menuBar.debug.compareMaps.checkComplete=Kontrollen genomförd. Kartan i sync. menuBar.debug.compareMaps.problem=Möjligt problem upptäckt. Vänligen läs informationen som skrivits till standard output. menuBar.debug.compareMaps=Kontrollera kartans synkronisering +menuBar.debug.displayAIMissions=Visa AI-uppdrag +menuBar.debug.displayAdditionalAIMissionInfo=Visa ytterligare information om AI-uppdrag menuBar.debug.displayErrorMessage=Visa felmeddelande menuBar.debug.displayEuropeStatus=Visa Europa-status menuBar.debug.displayMonarchPanel=Visa monarkpanel @@ -262,7 +268,6 @@ colopediaAction.goods.name=Varor colopediaAction.nations.name=Nationer colopediaAction.nationTypes.name=Nationella fördelar colopediaAction.resources.name=Bonusresurser -colopediaAction.skills.name=Yrkesmän colopediaAction.terrain.name=Terrängtyp colopediaAction.units.name=Trupper colopediaAction.name=%object% (Colopedia) @@ -321,8 +326,7 @@ renameAction.name=Döp om reportCargoAction.name=Fraktgodsrapport reportColonyAction.name=Kolonirådgivare reportCongressAction.name=Kontinentala regeringen -# Fuzzy -reportEducationAction.name=Utbildning +reportEducationAction.name=Utbildningsrapport reportExplorationAction.name=Utforskningsrapport reportForeignAction.name=Utrikesrådgivare reportHighScoresAction.name=Högsta poäng @@ -489,6 +493,8 @@ model.option.initialImmigration.name=Inledande immigrationsmål model.option.initialImmigration.shortDescription=Antal kross som produceras innan de första europeiska utvandrarna dyker upp. model.option.peaceProbability.name=Sannolikhet för fred model.option.peaceProbability.shortDescription=Chans i procent per runda att freden fortsätter med en arg AI. +model.option.equipEuropeanRecruits.name=Utrusta europeiska rekryter +model.option.equipEuropeanRecruits.shortDescription=Nyutbildade eller rekryterade enheter i Europa är utrustade enligt deras standardroll. gameOptions.colony.name=Kolonialternativ gameOptions.colony.shortDescription=Innehåller alternativ som berör hur en koloni fungerar. model.option.customIgnoreBoycott.name=Tullhus ignorerar bojkott @@ -497,9 +503,11 @@ model.option.expertsHaveConnections.name=Specialister har kontakter model.option.expertsHaveConnections.shortDescription=Specialister kan utnyttja sitt kontaktnät för att tillhandahålla minimala mängder av resurser för produktion i fabriker. model.option.saveProductionOverflow.name=Spara produktionsöverflöd model.option.saveProductionOverflow.shortDescription=Spara överflöd av hammare, klockor och kors. +model.option.clearHammersOnConstructionSwitch.name=Nollställ hammare vid byggnationsbyte +model.option.clearHammersOnConstructionSwitch.shortDescription=Nollställ antalet hammare om byggnationen ändras. model.option.allowStudentSelection.name=Tillåt val av student model.option.allowStudentSelection.shortDescription=Tillåter att studenter utses manuellt snarare än automatiskt -model.option.enableUpkeep.name=Byggnader kräver underhåll +model.option.enableUpkeep.name=Byggnader kräver underhåll (EXPERIMENTELLT) model.option.enableUpkeep.shortDescription=Betala för underhåll av byggnader eller produktionen blir lidande. model.option.naturalDisasters.name=Naturkatastrofer model.option.naturalDisasters.shortDescription=Sannolikheten för naturkatastrofer per omgång. @@ -524,8 +532,7 @@ model.option.lastYear.shortDescription=Det sista året i spelet. model.option.lastColonialYear.name=Sista koloniala spelåret model.option.lastColonialYear.shortDescription=Sista spelåret för en kolonial spelare. gameOptions.prices.name=Prisalternativ -# Fuzzy -gameOptions.prices.shortDescription=Initala prisomfånget för olika varor. +gameOptions.prices.shortDescription=Innehåller spelgenererade inställningar som styr startpriset för olika varor. model.option.food.minimumPrice.name=Ursprungliga minimipriser för livsmedel model.option.food.maximumPrice.name=Högsta startpris för livsmedel model.option.food.spread.name=Skillnaden mellan köp- och säljpris för livsmedel. @@ -588,6 +595,7 @@ model.option.landMass.shortDescription=Alternativ för att ange andelen landmass model.option.landGeneratorType.name=Landmasstyp (EXPERIMENTELL!) model.option.landGeneratorType.shortDescription=Alternativ för att välja typ av landgenerator som ska användas. model.option.landGeneratorType.classic.name=Klassisk +model.option.landGeneratorType.classic.shortDescription=En stor kontinent och några öar. model.option.landGeneratorType.continent.name=Kontinent model.option.landGeneratorType.continent.shortDescription=De mesta av landytan består av en enda kontinent. model.option.landGeneratorType.archipelago.name=Skärgård @@ -608,6 +616,8 @@ model.option.maximumLatitude.name=Högsta latitud model.option.maximumLatitude.shortDescription=Den sydligaste latituden. Ett positivt värde anger sydlig breddgrad. model.option.riverNumber.name=Antal floder model.option.riverNumber.shortDescription=Alternativ för att ange antal floder på genererade kartor. +model.option.riverNumber.verySmall.name=Mycket liten +model.option.riverNumber.verySmall.shortDescription=Mycket få floder model.option.mountainNumber.name=Antal berg model.option.mountainNumber.shortDescription=Alternativ för att ange antal berg på genererade kartor. model.option.rumourNumber.name=Antal rykten om Förlorade Städer @@ -635,6 +645,7 @@ model.option.importSettlements.shortDescription=Möjliggör import av inhemska b clientOptions.name=Inställningar clientOptions.shortDescription=Prioriterade klientalternativ clientOptions.personal.name=Personliga +clientOptions.personal.shortDescription=Spelarspecifika alternativ. model.option.playerName.name=Spelarens namn: clientOptions.gui.name=Visning clientOptions.gui.shortDescription=Innehåller inställningar för att justera spelets utseende. @@ -782,13 +793,17 @@ clientOptions.savegames.shortDescription=Sparade spel model.option.showSavegameSettings.name=Dialog för sparade spel: model.option.showSavegameSettings.shortDescription=Visa en dialog för att ställa in serveralternativ när man läser in ett sparat spel. clientOptions.savegames.showSavegameSettings.never.name=Aldrig +clientOptions.savegames.showSavegameSettings.never.shortDescription=Visa aldrig dialog för att ställa in serveralternativ clientOptions.savegames.showSavegameSettings.multiplayer.name=Multiplayer +clientOptions.savegames.showSavegameSettings.multiplayer.shortDescription=Visa endast dialog för att ställa in serveralternativ i flerspelarläge clientOptions.savegames.showSavegameSettings.always.name=Alltid -model.option.autosavePeriod.name=Automatspara var x drag: +clientOptions.savegames.showSavegameSettings.always.shortDescription=Visa alltid dialog för att ställa in serveralternativ +model.option.autosavePeriod.name=Automatspara var x drag model.option.autosavePeriod.shortDescription=Den frekvens med vilken spelet automatiskt sparas, där 0 stänger av den automatiska sparningen. -model.option.autosaveValidity.name=Radera automatiskt sparade filer efter x dagar: -model.option.autosaveDelete.name=Ta bort automatiskt sparade spel: -model.option.autosaveDelete.shortDescription=Ta bort automatiskt sparade spel när ett nytt spel påbörjas. +model.option.autosaveValidity.name=Radera automatiskt sparade filer efter x dagar +model.option.autosaveValidity.shortDescription=Tid i dagar som automatiskt sparad fil är giltig efter skapelsen. Sätt till 0 för att inte sätta någon gräns. +model.option.autosaveDelete.name=Ta bort automatiskt sparade spel +model.option.autosaveDelete.shortDescription=Ta bort gamla automatiskt sparade spel när ett nytt spel påbörjas. clientOptions.warehouse.name=Varulagerinställningar clientOptions.warehouse.shortDescription=Ändra standardinställningen för varulager och tullhus. model.option.customStock.name=Standardlagerhållning i tullhus @@ -816,16 +831,28 @@ model.option.showEndTurnDialog.name=Dialog vid sista omgången model.option.indianDemandResponse.name=Svar på krav från indianer # Fuzzy model.option.indianDemandResponse.shortDescription=När de infödda frågar efter eller begär varor, så acceptera alltid, avvisa alltid eller begär instruktioner. +clientOptions.other.indianDemandResponse.ask.name=Fråga +clientOptions.other.indianDemandResponse.ask.shortDescription=Fråga vad du vill göra clientOptions.other.indianDemandResponse.accept.name=Acceptera +clientOptions.other.indianDemandResponse.accept.shortDescription=Acceptera alla krav från infödingar +clientOptions.other.indianDemandResponse.reject.name=Avslå +clientOptions.other.indianDemandResponse.reject.shortDescription=Avvisa alla krav från infödingar model.option.unloadOverflowResponse.name=Lasta av överflöd -model.option.unloadOverflowResponse.shortDescription=Vad som skall göras när ett förråd blir överfyllda vid urlastning. +model.option.unloadOverflowResponse.shortDescription=Vad som skall göras när ett förråd blir överfyllt vid urlastning. clientOptions.other.unloadOverflowResponse.ask.name=Fråga +clientOptions.other.unloadOverflowResponse.ask.shortDescription=Fråga vad du vill göra clientOptions.other.unloadOverflowResponse.never.name=Aldrig +clientOptions.other.unloadOverflowResponse.never.shortDescription=Lasta aldrig av varor som skulle svämma över ett lager +clientOptions.other.unloadOverflowResponse.always.name=Alltid +clientOptions.other.unloadOverflowResponse.always.shortDescription=Lasta alltid av varor även om det svämmar över ett lager clientOptions.mods.name=Ändringar clientOptions.mods.shortDescription=Alternativ för att aktivera spelmodifikationer. -# Fuzzy -model.ability.alwaysOfferedPeace.name=Européerna erbjuder alltid fred +model.ability.addTaxToBells.name=Lägg till skatt till klockor +model.ability.addTaxToBells.shortDescription=Skattesatsen fungerar som en bonus till klockproduktion +model.ability.alwaysOfferedPeace.name=Alltid erbjuden fred +model.ability.alwaysOfferedPeace.shortDescrption=Européiska nationer är alltid beredda att erbjuda fred model.ability.ambushBonus.name=Bakhållsbonus +model.ability.ambushBonus.shortDescription=Bakhållsbonus när enheter attackeras i det fria. model.ability.ambushPenalty.name=Bakhållsavdrag model.ability.ambushPenalty.shortDescription=Denna nation får avdrag för bakhåll model.ability.autoProduction.name=Automatisk produktion @@ -841,23 +868,27 @@ model.ability.bornInColony.name=Född i kolonierna # Fuzzy model.ability.bornInIndianSettlement.name=Född i inhemska bosättningar model.ability.build.name=Bygg -# Fuzzy -model.ability.build.shortDescription=Möjligheten att bygga enheter, utrustning eller byggnader. -# Fuzzy -model.ability.buildCustomHouse.name=Förmåga att bygga tullhus -# Fuzzy -model.ability.buildFactory.name=Förmåga att bygga fabriker +model.ability.build.shortDescription=Möjligheten att bygga enheter, utrustning eller byggnader, ibland av en viss typ +model.ability.buildCustomHouse.name=Bygga tullhus +model.ability.buildCustomHouse.shortDescription=Förmåga att bygga tullhus +model.ability.buildFactory.name=Bygga fabriker +model.ability.buildFactory.shortDescription=Förmåga att bygga fabriker model.ability.canBeCaptured.name=Kan fångas +model.ability.canBeCaptured.shortDescription=Enheter som kan fångas model.ability.canBeEquipped.name=Kan utrustas +model.ability.canBeEquipped.shortDescription=Enheter som kan utrustas model.ability.canRecruitUnit.name=Rekrytera enheter model.ability.canRecruitUnit.shortDescription=Denna nation har förmågan att rekrytera enheter. model.ability.captureEquipment.name=Kan ta över utrustning +model.ability.captureEquipment.shortDescription=Förmågan att fånga utrustning model.ability.captureGoods.name=Erövra varor model.ability.captureGoods.shortDescription=Denna trupp kan erövra varor. model.ability.captureUnits.name=Kan fånga enheter +model.ability.captureUnits.shortDescription=Förmågan att fånga enheter i strid model.ability.carryGoods.name=Frakta varor model.ability.carryGoods.shortDescription=Denna trupp kan frakta varor. model.ability.carryTreasure.name=Kan bära skatter +model.ability.carryTreasure.shortDescription=Den här enheten kan bära skatter model.ability.carryUnits.name=Frakta trupper model.ability.carryUnits.shortDescription=Denna trupp kan frakta andra trupper. # Fuzzy @@ -866,24 +897,26 @@ model.ability.demoteOnAllEquipLost.name=Degraderas efter nederlag model.ability.disposeOnAllEquipLost.name=Kan inte fångas # Fuzzy model.ability.disposeOnCombatLoss.name=Kan inte fångas +model.ability.disposeOnCombatLoss.shortDescription=Denna enhet förstörs om den förlorar en strid model.ability.electFoundingFather.name=Välj statsbildare model.ability.electFoundingFather.shortDescription=Denna nation kan välja statsbildare model.ability.evadeAttack.name=Undvik angrepp model.ability.evadeAttack.shortDescription=Denna enhet har möjligheten att undvika angrepp. model.ability.export.name=Exportera varor -# Fuzzy -model.ability.export.shortDescription=Kan exportera varor direkt till Europa. +model.ability.export.shortDescription=Kan exportera varor direkt till Europa model.ability.foundColony.name=Grunda koloni -# Fuzzy -model.ability.foundColony.shortDescription=Denna trupp kan grunda en ny koloni. +model.ability.foundColony.shortDescription=Denna trupp kan grunda en ny koloni model.ability.foundInLostCity.name=Hittad i förlorade städer model.ability.foundsColonies.name=Grundar kolonier model.ability.foundsColonies.shortDescription=Denna nation har förmågan att grunda nya kolonier. -# Fuzzy model.ability.hasPort.name=Tillgång till havet -# Fuzzy model.ability.hasPort.shortDescription=Denna plats står i direkt eller indirekt förbindelse med havet model.ability.ignoreEuropeanWars.name=Ignorera europeiska krig +model.ability.ignoreEuropeanWars.shortDescription=Krigsförklaringar i Europa påverkar inte längre denna nation +model.ability.improveTerain.name=Förbättra terräng +model.ability.improveTerain.shortDescription=Den här enheten kan förbättra terräng +model.ability.inciteNatives.name=Hetsa infödda +model.ability.inciteNatives.shortDescription=Denna enhet kan hetsa infödda nationer mot en fiendenation model.ability.independenceDeclared.name=Oavhängighetsförklaring # Fuzzy model.ability.independenceDeclared.shortDescription=Denna stat har utropat sin oavhängighet @@ -898,12 +931,12 @@ model.ability.native.name=Indian model.ability.native.shortDescription=Indian model.ability.navalUnit.name=Sjötrupp model.ability.navalUnit.shortDescription=Denna enhet är en marin enhet. -# Fuzzy -model.ability.person.name=Är en person -# Fuzzy -model.ability.pillageUnprotectedColony.name=Kan plundra kolonier som är utan försvar -# Fuzzy -model.ability.piracy.name=Är en piratenhet +model.ability.person.name=Person +model.ability.person.shortDescription=Denna enhet är en person +model.ability.pillageUnprotectedColony.name=Plundring +model.ability.pillageUnprotectedColony.shortDescription=Kan plundra kolonier som är utan försvar +model.ability.piracy.name=Sjöröveri +model.ability.piracy.shortDescription=Detta är en piratenhet # Fuzzy model.ability.plunderNatives.name=Bonus för indianskatter # Fuzzy @@ -912,15 +945,23 @@ model.ability.repairUnits.name=Reparations enheter # Fuzzy model.ability.repairUnits.shortDescription=Kan reparera vissa typer av skadade enheter. model.ability.royalExpeditionaryForce.name=Kungliga expeditionskåren -# Fuzzy -model.ability.royalExpeditionaryForce.shortDescription=Denna nation är en kunglig expeditionskår -# Fuzzy -model.ability.selectRecruit.name=Möjlighet att välja rekryter -# Fuzzy -model.ability.supportUnit.name=Är en stödenhet +model.ability.royalExpeditionaryForce.shortDescription=Denna nation har en kunglig expeditionskår +model.ability.rumoursAlwaysPositive.name=Rykten alltid positiva +model.ability.rumoursAlwaysPositive.shortDescription=Att undersöka rykten har alltid ett positivt resultat +model.ability.seeAllColonies.name=Se alla kolonier +model.ability.seeAllColonies.shortDescription=Kan se alla utländska kolonier +model.ability.selectRecruit.name=Välj rekryter +model.ability.selectRecruit.shortDescription=Möjlighet att välja rekryter +model.ability.speakWithChief.name=Tala med hövding +model.ability.speakWithChief.shortDescription=Denna enhet kan tala med hövdingen i en indianby +model.ability.spyOnColony.name=Spionera på kolonin +model.ability.spyOnColony.shortDescription=Denna enhet kan spionera på utländska kolonier +model.ability.supportUnit.name=Stödenhet +model.ability.supportUnit.shortDescription=Denna enhet finns i stödtrupper model.ability.teach.name=Lär ut färdigheter -# Fuzzy -model.ability.teach.shortDescription=Expertenheter kan undervisa andra sina färdigheter. +model.ability.teach.shortDescription=Expertenheter kan lära ut sina färdigheter +model.ability.tradeWithForeignColonies.name=Handel med utländska kolonier +model.ability.tradeWithForeignColonies.shortDescription=Möjlighet att handla med utländska kolonier # Fuzzy model.ability.undead.name=Hämndläge # Fuzzy @@ -942,10 +983,13 @@ model.modifier.nativeAlarmModifier.name=Indianorosfördel model.modifier.nativeAlarmModifier.shortDescription=Denna nation skapar mindre oro bland indianerna model.modifier.nativeConvertBonus.name=Bonus för indiankonvertiter model.modifier.nativeConvertBonus.shortDescription=Denna nation konverterar fler indianer +model.modifier.offence.name=Attackbonus model.modifier.offenceAgainst.name=Brott mot model.modifier.offenceAgainst.shortDescription=Förbättrar chansen till seger när du attackerar. model.modifier.religiousUnrestBonus.name=Fördel vad gäller missnöje i trosuppfattningsfrågor model.modifier.religiousUnrestBonus.shortDescription=Denna nation orsakar mer missnöje i trosuppfattningsfrågor +model.modifier.tileTypeChangeProduction.name=Timmeravkastning +model.modifier.tileTypeChangeProduction.shortDescription=Ökar mängden virke som produceras när skog avverkas. model.modifier.tradeBonus.name=Handelsfördel model.modifier.tradeBonus.shortDescription=Denna nation drar fördelar av handel model.modifier.warehouseStorage.description=Varulager @@ -1024,8 +1068,7 @@ model.building.schoolhouse.description=En koloni med en befolkning på minst 4 k model.building.shipyard.name=Skeppsvarv model.building.shipyard.description=Skeppsvarvet gör så att kolonisterna kan producera fisk på havsrutor i närheten av kolonin, reparera skepp och också så att de kan bygga nya skepp. \n\nOm du bygger ett skeppsvarv kan kolonin bygga nya skepp. model.building.stables.name=Stallar -# Fuzzy -model.building.stables.description=Förbättrar kapaciteten för hästavel +model.building.stables.description=Stallet förbättrar kapaciteten för hästavel genom att minska flockarnas storlek. model.building.stockade.name=Pålverk model.building.stockade.description=Pålverket, vilket kan byggas senare när kolonins befolkning uppnått 3, skyddar kolonisterna från anfall. Pålverket kan uppgraderas till en skans, vilken ger bättre skydd och kan bombardera kaparfartyg och fienders sjötrupper på närliggade havsrutor. Skansen kan ersättas av en fästning senare när befolkningen uppnått 8. \n\nOm du bygger ett pålverk ökar det försvaret med 100%. model.building.textileMill.name=Textilfabrik @@ -1091,8 +1134,7 @@ model.foundingFather.peterStuyvesant.description=Möjliggör byggandet av tullhu model.foundingFather.peterStuyvesant.text=Utsågs till generalguvernör för Nya Holland som, efter den brittiska invasion han var oförmögen att hindra, blev New York. model.foundingFather.peterStuyvesant.birthAndDeath=1592-1672 model.foundingFather.janDeWitt.name=Jan de Witt -# Fuzzy -model.foundingFather.janDeWitt.description=Möjliggör handel med främmande kolonier. +model.foundingFather.janDeWitt.description=Möjliggör handel med främmande kolonier, och mer information om rivaliserande kolonier visas. model.foundingFather.janDeWitt.text=De Witt var en stor holländsk statsman. Han representerade handelsmännen och uppmuntrade industri och handel. Han underhandlade och slöt flera viktiga avtal som ledde till slutet av kriget mellan Holland och England. model.foundingFather.janDeWitt.birthAndDeath=1625-1672 model.foundingFather.ferdinandMagellan.name=Ferdinand Magellan @@ -1282,7 +1324,7 @@ model.improvement.road.description=Väg model.improvement.road.name=Väg model.improvement.road.occupationString=V model.limit.independence.coastalColonies.name=Gränsen för den kustnära kolonin -model.limit.independence.coastalColonies.description=Du behöver minst %limit% kustnära kolonierna för att förklara självständighet. +model.limit.independence.coastalColonies.description=Du behöver minst %limit% kustnära {{plural:%limit%|one=koloni|other=kolonier}} för att kunna förklara självständighet. model.limit.independence.rebels.name=Rebellgräns model.limit.independence.rebels.description=Minst %limit%% av dina kolonister måste stödja sjävständighet. model.limit.independence.year.name=Årsgräns @@ -1430,6 +1472,13 @@ model.role.scout.name=Spejare model.role.scout.noequipment=inga hästar model.role.soldier.name=Soldat model.role.soldier.noequipment=inga musköter +model.role.change.dragoon=Utrusta som dragon +model.role.change.pioneer=Utrusta med verktyg +model.role.change.scout=Utrusta som scout +model.role.change.default.soldier=Beväpna +model.role.change.dragoon.default=Ta bort all utrustning +model.role.change.pioneer.default=Ta bort verktyg +model.role.change.pioneer.soldier=Beväpna model.settlement.aztec.capital.name=Aztekstad model.settlement.aztec.name=Aztekstad model.settlement.aztec.plural=städer @@ -1470,8 +1519,7 @@ model.tile.marsh.description=Kärr är en sort våtmark med gräs, vass säv och model.tile.mixedForest.name=Blandskog model.tile.mixedForest.description=Blandskog som återfinns på tempererade latituder kan producera spannmål, timmer, pälsar och lite bomull. Om skogen huggs ner blir de till slätt. model.tile.mountains.name=Berg -# Fuzzy -model.tile.mountains.description=Berg sträcker sig över den omgivande terrängen inom ett begränsat område. Berg är vanligen brantare än kullar. De är svåra att färdas genom och kolonier kan inte grundas i dem. Men de är användbara för gruvdrift och både järnmalm och silver kan brytas i dem. +model.tile.mountains.description=Berg sträcker sig över den omgivande terrängen inom ett begränsat område. Berg är vanligen brantare än kullar. De är svåra att färdas genom och kolonier kan inte grundas i dem. De erbjuder en hög försvarsbonus, men denna kan inte förstärkas ytterligare genom fortifikation. De är användbara för gruvdrift och både järnmalm och silver kan brytas i dem. model.tile.ocean.name=Hav model.tile.ocean.description=Hav är stora saltvattenytor med gott fiske. Mängden fisk ökar med närheten till land och i synnerhet flodmynningar. model.tile.plains.name=Slätt @@ -1533,7 +1581,7 @@ model.unit.masterFurTrader.description=En pälshandlare gör pälskappor av päl model.unit.masterGunsmith.name={{plural:%number%|one=Mästervapensmed|other=Mästervapensmedar|default=Mästervapensmed}} model.unit.masterGunsmith.description=En vapensmed framställer musköter av redskap. model.unit.masterSugarPlanter.name={{plural:%number%|one=Professionell sockerodlare|other=Professionella sockerodlare|default=Professionell sockerodlare}} -model.unit.masterSugarPlanter.description=Sockerodlaren odllar sockerrör. +model.unit.masterSugarPlanter.description=Sockerodlaren odlar sockerrör. model.unit.masterTobaccoPlanter.name={{plural:%number%|one=Mästartobaksodlare|other=Mästartobaksodlare|default=Mästartobaksodlare}} model.unit.masterTobaccoPlanter.description=Tobaksodlaren odlar tobak. model.unit.masterTobacconist.name={{plural:%number%|one=Mästartobakshandlare|other=Mästartobakshandlare|default=Mästartobakshandlare}} @@ -1562,8 +1610,7 @@ model.unit.artillery.name={{plural:%number%|one=Artilleripjäs|other=Artilleripj model.unit.artillery.description=Artilleri är bra på att anfalla och försvara kolonier, men är mycket sårbart på öppen mark. model.unit.damagedArtillery.name={{plural:%number%|one=Skadat artilleri|other=Skadade artillerier|default=Skadat artilleri}} model.unit.damagedArtillery.description=Skadat artilleri är som artilleri på alla sätt men svagare. -# Fuzzy -model.unit.treasureTrain.name=Värdetransport +model.unit.treasureTrain.name={{plural:%number%|one=Värdetransport|other=Värdetransporter|default=Värdetransport}} model.unit.treasureTrain.description=En värdetransports enda syfte är att transportera guld som hittats i ruinerna av en förlorad stad eller plundrats från en indianbosättning. Om du flyttar den in i en av dina kolonier så kommer Kronan att erbjuda sig att transportera den till Europa för en "rimlig kostnad". Om du har en galeon så kan du transportera den till Europa själv. model.unit.wagonTrain.name={{plural:%number%|one=Konvoj|other=Konvojer|default=Konvoj}} model.unit.wagonTrain.description=Konvojen kan frakta upp till 200 enheter varor över land. Du kan använda den för att handla med andra spelare eller för att flytta varor mellan dina egna kolonier. @@ -1580,16 +1627,14 @@ model.unit.undead.description=De vandöda är den flygande holländarens besätt # Fuzzy model.unit.colonialRegular.dragoon=Kolonialt kavalleri model.unit.colonialRegular.soldier=Kontinentalarmé -# Fuzzy -model.unit.hardyPioneer.pioneer=Hårdför pionjär -# Fuzzy -model.unit.jesuitMissionary.missionary=Jesuitmissionär +model.unit.hardyPioneer.pioneer={{plural:%number%|one=Hårdför pionjär|other=Hårdföra pionjärer|default=Hårdför pionjär}} +model.unit.jesuitMissionary.missionary={{plural:%number%|one=Jesuitmissionär|other=Jesuitmissionärer|default=Jesuitmissionär}} model.unit.kingsRegular.cavalry=Kavalleri model.unit.kingsRegular.infantry=Infanteri model.unit.seasonedScout.scout={{plural:%number%|one=Erfaren spejare|other=Erfarna spejare|default=Erfaren spejare}} -# Fuzzy -model.unit.veteranSoldier.dragoon=Veterandragon +model.unit.veteranSoldier.dragoon={{plural:%number%|one=Veterandragon|other=Veterandragoner|default=Veterandragoner}} model.unit.veteranSoldier.soldier={{plural:%number%|one=Veteransoldat|other=Veteransoldater|default=Veteransoldat}} +model.unit.colonialRegular.workingAs=Soldat model.unit.elderStatesman.workingAs=Statsman model.unit.expertFarmer.workingAs=Bonde model.unit.expertFisherman.workingAs=Fiskare @@ -1619,7 +1664,7 @@ model.building.locationLabel=I %location% model.colony.badGovernment=Ledarskapet i %colony% är odugligt. Produktionen i kolonin är reducerad. model.colony.governmentImproved1=Ledarskapet i %colony% har förbättrats men har fortfarande brister. Produktionen i kolonin är fortfarande reducerad. model.colony.governmentImproved2=Ledarskapet i %colony% är inte längre odugligt. Produktionen i kolonin är inte längre reducerad. -model.colony.insufficientProduction=%outputAmount% mer %outputType% kan produceras i %colony%, om vi bara hade %inputAmount% mer överskott av %inputType%. +model.colony.insufficientProduction=%outputAmount% mer %outputType% skulle kunna produceras i %colony%, om vi bara hade %consumptionDeficit% mer. model.colony.minimumColonySize=Tack vare %object% så kan inte befolkningen minskas mer model.colony.stance.alliance=%nation% är glada att se en pålitlig allierad som dig. model.colony.stance.ceaseFire=%nation% blänger på dig, och förbereder uppenbarligen sitt försvar. @@ -1630,13 +1675,13 @@ model.colony.unbuildable=%colony% kan inte bygga %object% just nu. %object% har model.colony.veryBadGovernment=Ledarskapet i %colony% är odugligt. Produktionen i kolonin är starkt reducerad. model.colonyTile.claim=(kräv %direction%) model.diplomaticTrade.receive.contact=Broderliga hälsningar från den ärorika %nation% nationen. -model.diplomaticTrade.receive.diplomatic=Låt oss förhandla med %nation%. +model.diplomaticTrade.receive.diplomatic=Låt oss förhandla med {{tag:country|%nation%}}. model.diplomaticTrade.receive.trade=Låt oss överväga %nation% handelserbjudande. -model.diplomaticTrade.receive.tribute=%nation% kräver en tribut av oss! +model.diplomaticTrade.receive.tribute={{tag:country|%nation%}} kräver en tribut av oss! model.diplomaticTrade.send.contact=Vi har stött på medlemmar i den %nation% nationen. -model.diplomaticTrade.send.diplomatic=Låt oss överväga vår diplomatiska situation med %nation%. -model.diplomaticTrade.send.trade=Låt oss föreslå en handel med %nation% på %settlement%. -model.diplomaticTrade.send.tribute=Vi kräver tribut av %nation% vid %settlement%. +model.diplomaticTrade.send.diplomatic=Låt oss överväga vår diplomatiska situation med {{tag:country|%nation%}}. +model.diplomaticTrade.send.trade=Låt oss föreslå en handel med {{tag:country|%nation%}} på %settlement%. +model.diplomaticTrade.send.tribute=Vi kräver tribut av {{tag:country|%nation%}} vid %settlement%. model.direction.N.name=norr model.direction.NE.name=nordöst model.direction.E.name=öst @@ -1646,22 +1691,25 @@ model.direction.SW.name=sydväst model.direction.W.name=väst model.direction.NW.name=nordväst model.historyEventType.abandonColony.description=Du ger upp kolonin %colony%. -model.historyEventType.cityOfGold.description=%nation% upptäcker %city%, en utav de sju "Städerna av guld", och en skatt bestående av %treasure% guld. -model.historyEventType.colonyConquered.description=Din koloni %colony% har erövrats av %nation%. -model.historyEventType.colonyDestroyed.description=Din koloni %colony% är förstörd av %nation%. -# Fuzzy -model.historyEventType.declareIndependence.description=Du förstör %nation%s bosättning %settlement%. -model.historyEventType.destroyNation.description=%nation% förstör %nativeNation%. +model.historyEventType.ceaseFire.description=Fredsavtal med {{tag:country|%nation%}}. +model.historyEventType.cityOfGold.description={{tag:country|%nation%}} upptäcker %city%, en utav de sju "Städerna av guld", och en skatt bestående av %treasure% guld. +model.historyEventType.colonyConquered.description=Din koloni %colony% har erövrats av {{tag:country|%nation%}}. +model.historyEventType.colonyDestroyed.description=Din koloni %colony% är förstörd av {{tag:country|%nation%}}. +model.historyEventType.conquerColony.description=Du erövrar {{tag:country|%nation%}}s koloni %colony%. +model.historyEventType.declareIndependence.description=Du utropar oavhängighet från kronan. +model.historyEventType.declareWar.description=Krig har förklarats med {{tag:country|%nation%}}. +model.historyEventType.destroyNation.description={{tag:country|%nation%}} förstör %nativeNation%. +model.historyEventType.destroySettlement.description=Du förstör %nation%s bosättning %settlement%. model.historyEventType.discoverNewWorld.description=Du utforskar den nya världen. -model.historyEventType.discoverRegion.description=%nation% upptäcker %region%. -model.historyEventType.formAlliance.description=Alliansen framförhandlad med %nation%. +model.historyEventType.discoverRegion.description={{tag:country|%nation%}} upptäcker %region%. +model.historyEventType.formAlliance.description=Alliansen framförhandlad med {{tag:country|%nation%}}. model.historyEventType.foundColony.description=Du grundar kolonin %colony%. model.historyEventType.foundingFather.description=%father% går med i den kontinentala kongressen. model.historyEventType.independence.description=Du uppnår oavhängighet från kronan. -model.historyEventType.makePeace.description=Fredsavtal med %nation%. -model.historyEventType.meetNation.description=Du möter %nation%. -model.historyEventType.nationDestroyed.description=!%nation% finns inte längre i Nya världen. -model.historyEventType.spanishSuccession.description=%loserNation% avstår alla sina kolonier i den nya världen till %nation%. +model.historyEventType.makePeace.description=Fredsavtal med {{tag:country|%nation%}}. +model.historyEventType.meetNation.description=Du möter nationen %nation%. +model.historyEventType.nationDestroyed.description=Den %nation% nationen finns inte längre i Nya världen. +model.historyEventType.spanishSuccession.description={{tag:country|%loserNation%}} avstår alla sina kolonier i den nya världen till {{tag:country|%nation%}}. model.indianSettlement.mostHatedNone=Inga model.indianSettlement.mostHatedUnknown=Okänd model.indianSettlement.nameUnknown=Okänd @@ -1729,8 +1777,7 @@ model.advantages.selectable.name=Valbar model.advantages.selectable.shortDescription=Nationella fördelar är valbara och behöver inte vara unika. model.nationState.aiOnly.name=Endast AI model.nationState.available.name=tillgänglig -# Fuzzy -model.nationState.available.shortDescription=Du erövrar %nation%s koloni %colony%. +model.nationState.available.shortDescription=Du kan spela som denna nation model.nationState.notAvailable.name=ej tillgänglig model.noClaimReason.europeans.description=Detta markområde har tagits i anspråk av en annan Europeisk nation. model.noClaimReason.natives.description=Detta markområde har tagits i anspråk av en infödingsstam. @@ -1742,8 +1789,8 @@ model.noClaimReason.water.description=Vi gör inte anspråk på vattnen. model.noClaimReason.worked.description=En annan bosättning använder redan detta landområde. model.player.forces=%nation%s styrkor model.player.independentMarket=Europa -model.player.startGame=Efter flera månader till sjöss anländer du slutligen till kusten av en okänd kontinent. Segla {{tag:%direction%|west=westward|east=eastward|default=into the wind}} för att upptäcka den Nya Världen och hävda Kronans överhöghet över den. -model.player.waitingFor=Väntar på: %nation% +model.player.startGame=Efter flera månader till sjöss anländer du slutligen till kusten av en okänd kontinent. Segla {{tag:%direction%|west=västerut|east=österut|default=dit vindarna bär}} för att upptäcka den Nya Världen och hävda Kronans överhöghet över den. +model.player.waitingFor=Väntar på: {{tag:country|%nation%}} model.regionType.coast.name=Kust model.regionType.coast.unknown=Okänd kustregion model.regionType.desert.name=Öken @@ -1782,7 +1829,7 @@ model.tradeItem.gold.name=Guld model.tradeItem.gold.description=totalt %amount% guld model.tradeItem.goods.name=Varor model.tradeItem.incite.name=Förklara krig mot -model.tradeItem.incite.description=krig mot %nation% +model.tradeItem.incite.description=krig mot {{tag:country|%nation%}} model.tradeItem.stance.name=Hållning model.tradeItem.unit.name=Trupp model.tradeRoute.invalidStop=Stop %name% är ogiltigt. @@ -1800,10 +1847,9 @@ model.unit.underRepair=Reparation(%turns%) model.unit.unitState.active=- model.unit.unitState.fortified=F model.unit.unitState.fortifying=F -model.unit.unitState.improving=# model.unit.unitState.inColony=B model.unit.unitState.sentry=S -model.unit.unitState.skipped=W +model.unit.unitState.skipped=X model.unit.unitState.toAmerica=G model.unit.unitState.toEurope=G model.noAddReason.alreadyPresent.description=Finns redan på denna plats. @@ -1834,11 +1880,13 @@ model.colony.warehouseOverfull=Ditt varulager i %colony% innehåller nu så myck model.colony.warehouseSoonFull=Ditt varulager i %colony% kommer efter nästa drag att innehålla så mycket %goods% som kan lagras där. %amount% enheter av %goods% kommer att gå förlorade. model.colony.warehouseWaste=Ditt varulager i %colony% innehåller redan så mycket %goods% som kan lagras där. %waste% enheter gick förlorade. model.colonyTile.resourceExhausted=Resursen %resource% är slut i %colony%. +# Fuzzy model.game.spanishSuccession=Ers excellens, det spanska tronföljdskriget har tagit slut i Europa. Under Utrechtfördragets statuter tvingades %loserNation% att överlämna alla kolonier i Nya Världen till %nation%! model.indianSettlement.mission.denounced=Din missionär i %settlement% har avrättats! model.player.colonyGoodsParty.harbour=Kolonisterna i %colony% har kastat %amount% enheter av %goods% i hamnen som protest mot den orättfärdiga beskattningen från Kronan! model.player.colonyGoodsParty.horses=Dina kolonister i %colony% har frigivit %amount% hästar i protest mot den orättfärdiga skatten från kronan! model.player.colonyGoodsParty.landLocked=Kolonisterna i %colony% har bränt %amount% enheter av %goods% på marknadsplatsen som protest mot den orättfärdiga beskattningen från Kronan! +# Fuzzy model.player.dead.european=Ers Excellens, %nation% har deklarerat att de fullständigt drar sig tillbaka från Nya Världen! model.player.dead.native=Ers excellens, %nation% har tillintetgjorts. model.player.disaster.bankruptcy.start=Du kunde inte betala för underhåll av alla byggnader. Omfattande sanktioner mot produktion tillämpas. @@ -1849,12 +1897,16 @@ model.player.foundingFatherJoinedCongress=%foundingFather% ingår nu i regeringe model.player.interventionForceArrives=Den utlovade insatsstyrkan anländer! model.player.soLDecrease=Medlemsskap i Frihetens söner i dina kolonier har fallit till %newSoL% procent! model.player.soLIncrease=Medlemsskap i Frihetens söner i dina kolonier har stigit till %newSoL% procent! +# Fuzzy model.player.stance.alliance.declared=Ers nåd, %nation% är nu våra allierade! model.player.stance.alliance.others=Ers nåd, %attacker% och %defender% har ingått en allians. +# Fuzzy model.player.stance.ceaseFire.declared=Ers nåd, %nation% har gått med på vapenstillestånd! model.player.stance.ceaseFire.others=Ers nåd, %attacker% har ingått vapenstillestånd med %defender%. +# Fuzzy model.player.stance.peace.declared=Ers nåd, det råder fred mellan oss och %nation%! model.player.stance.peace.others=Ers nåd, det råder nu fred mellan %attacker% och %defender%. +# Fuzzy model.player.stance.war.declared=Dåliga nyheter, ers nåd, %nation% har förklarat krig mot oss! model.player.stance.war.others=Ers nåd, %attacker% har förklarat krig mot %defender%. combat.automaticDefence=Din %unit% i %colony% har tagit till vapen för att försvara kolonin! @@ -1870,7 +1922,7 @@ combat.enemyShipEvaded=%enemyNation%s %enemyUnit% har klarat sig undan en attack combat.enemyShipSunk=%unit% har sänkt %enemyNation%s %enemyUnit%! combat.equipmentCaptured=Tag er i akt, %nation%s krigare har skaffat sig %equipment%! combat.goodsStolen=%enemyNation%s %enemyUnit% stjäl %amount% %goods% i %colony%! -combat.indianPlunder=%colony% plundras på %amount% av %enemyNation%s %enemyUnit%. +combat.indianPlunder=%enemyNation%s %enemyUnit% plundras på %amount% guld från %colony%. combat.indianTreasure=Du plundrar %settlement% på %amount% guld. combat.nativeCapitalBurned=Du har bränt %nation%s huvudstad %name% till marken, och %nation% kapitulerar inför din makt! combat.newConvertFromAttack=En skrämd %unit% från %nation% ansluter sig till dig! @@ -1923,13 +1975,14 @@ main.defaultPlayerName=Spelarnamn main.javaVersion=Java version %minVersion% eller nyare rekommenderas för att köra FreeCol (%version% detected, använd --no-java-check för att hoppa över denna kontroll). main.memory=Du måste tilldela mer än %memory% byte minne till JVM. Starta om FreeCol med: java -Xmx%minMemory%M -jar FreeCol.jar main.userDir.fail=FreeCol kan inte hitta lämpliga kataloger att spara användardata i. Fortsätter, men räkna med problem. -client.choicePlayer=Välj en spelare: +client.choicePlayer=Välj en nation: +client.debugConnect=Du kan inte ansluta till ett existerande spel i felsökningsläge. metaServer.couldNotConnect=Kunde tyvärr inte ansluta till meta-servern. Försök senare. metaServer.communicationError=Fel uppstod vid kommunikation med meta-servern. Försök senare. abandonEducation.action.studying=studerar abandonEducation.action.teaching=undervisar -abandonEducation.no=Nej, fortsätt utbildningen -abandonEducation.yes=Ja, lämna kolonin +abandonEducation.no=Fortsätt utbildningen +abandonEducation.yes=Överge utbildning armedUnitSettlement.attack=Attackera armedUnitSettlement.tribute=Kräv tribut boycottedGoods.dumpGoods=Dumpa varor @@ -1938,9 +1991,10 @@ buy.moreGold=Begär lägre pris buy.takeOffer=Antag erbjudandet buy.text=%nation% skulle vilja sälja %goods% till dig för %gold% guld: clearTradeRoute.text=Din %unit% är tilldelad handelsrutt %route%. Att ange en destination kommer att ta den från handelsrutten. Är du säker att du vill göra detta? -confirmHostile.alliance=Du kan inte anfalla en allierad nation! Vill du verkligen bryta din allians med %nation% och förklara krig? +confirmHostile.alliance=Du kan inte anfalla en allierad nation! Vill du verkligen bryta din allians med {{tag:country|%nation%}} och förklara krig? +# Fuzzy confirmHostile.ceaseFire=Du har undertecknat en vapenvila med %nation%. Vill du verkligen anfalla? -confirmHostile.peace=Du har fred med %nation%. Vill du verkligen förklara krig mot dem? +confirmHostile.peace=Du har fred med {{tag:country|%nation%}}. Vill du verkligen förklara krig mot dem? danger.high=mycket bättre beväpnade än oss danger.low=är inget hot mot oss danger.normal=kan visa sig vara ett hot @@ -1999,8 +2053,8 @@ defeated.text=Du har blivit besegrad! Skulle du vilja: defeated.yes=Stanna kvar och se hur det går defeatedSinglePlayer.text=Du har blivit besegrad!\n\nDet är nu den mörka nattens tid, när kyrkogårdar gäspar och själva helvetet andas ut sin smitta över denna jord, nu skulle jag kunna dricka hett blod! och göra sådana bittra dåd som skulle få dagen att skaka om den såg dem. defeatedSinglePlayer.yes=Aktivera hämndläge -diplomacy.offerAccepted=%nation% har godtagit ditt generösa erbjudande. -diplomacy.offerRejected=%nation% har avslagit ditt generösa erbjudande. +diplomacy.offerAccepted={{tag:country|%nation%}} har godtagit ditt generösa erbjudande. +diplomacy.offerRejected={{tag:country|%nation%}} har avslagit ditt generösa erbjudande. disbandUnit.text=Är du säker på att du vill demobilisera denna trupp? disbandUnit.yes=Demobilisera disembark.text=Var hälsad sjöman, vill du lämna skeppet? @@ -2042,8 +2096,8 @@ move.noAccessContact=Ers Excellens, vi måste först upprätta kontakt med %nati move.noAccessGoods=%nation% kommer inte att byteshandla med en tom %unit%. move.noAccessSettlement=%nation% låter inte våra trupper av typ %unit% komma in i deras bosättning. move.noAccessSkill=Vår trupp av typen %unit% kan inte lära sig något av urinvånarna. -move.noAccessTrade=Vi har inte befogenhet att handla med andra europeiska nationer som%nation%. -move.noAccessWar=Vi kan inte handla med%nation% medan vi är i krig med dem. +move.noAccessTrade=Vi har inte befogenhet att handla med andra europeiska nationer som {{tag:country|%nation%}}. +move.noAccessWar=Vi kan inte handla med {{tag:country|%nation%}} medan vi är i krig med dem. move.noAccessWater=Vår trupp av typen %unit% måste landstiga innan den kan gå in i bosättningen. move.noAttackWater=Vår %unit% måste landa innan den kan attackera. move.noTile=Vår %unit% finns inte på kartan! @@ -2060,8 +2114,7 @@ scoutSettlement.speakDie=Du har brutit stammens heliga tabu! Vi skall binda dig scoutSettlement.speakNothing=Vi är alltid glada att kunna välkomna resenärer från %nation%. scoutSettlement.speakTales=Vi är glada att kunna välkomna långväga resenärer. Kom, sitt med oss runt elden och låt oss berätta för dig om dessa trakter. sellProposition.text=Vill du sälja lite varor? -# Fuzzy -trade.noTrade=Handel avböjs. +trade.noTrade=Handel avböjd vid %settlement%. trade.noTradeGoods=Tyvärr, vi har inget behov av mer %goods% trade.noTradeHaggle=Vi börjar bli trötta på ditt ständiga köpslående. trade.noTradeHostile=Vi föraktar dig och dina varor. Försvinn! @@ -2082,17 +2135,18 @@ tradeRoute.unloadStopImport=Lossade %amount% %goods% och kasserade %more%. tradeRoute.unloadStopNoExport=Lossade inget %goods% med %more% mer sparat ombord. tradeRoute.wait=Har inget arbete att göra, väntar. traderoute.warehouseCapacity=Om du sätter i land din %unit% i %colony% så skulle varulagrets kapacitet överskridas. %amount% %goods% skulle gå förlorade. Vill du lasta ur varorna i alla fall? -# Fuzzy -twoTurnsPerYear=Från och med år %year% kommer det att vara två varv per år, i stället för ett!! +twoTurnsPerYear=Från och med år %year% kommer det att vara %amount% varv per år, i stället för ett! server.badColor=Ogiltig färg server.badNation=Ogiltig nation server.badNationType=Ogiltig typ av nation server.couldNotConnect=Kunde inte skapa anslutning till servern. +server.couldNotLogin=Kan inte logga in på servern. server.errorStartingGame=Ett fel uppstod när spelet skulle startas. server.fileNotFound=Kunde inte hitta filen med angivet filnamn. server.incompatibleVersions=Det sparade spel som du försöker läsa in är inkompatibelt med denna version av FreeCol. server.invalidPlayerNations=Varje spelare måste välja en unik nation innan spelet kan starta. server.maximumPlayers=Beklagar, maximalt antal spelare har redan anslutit sig till spelet. +# Fuzzy server.noRouteToServer=Servern kan inte öppnas för allmänheten. Du behöver justera dina brandväggsinställningar så att anslutningar tillåts på den port du angav. server.notAllReady=Alla spelare är inte klara att börja spela än! server.onlyAdminCanLaunch=Beklagar, enbart serverns administratör kan starta spelet. @@ -2113,6 +2167,11 @@ giveIndependence.otherAnnounce=%nation% har besegrat %ref% och blivit självstä giveIndependence.unitsAcquired=Följande Kungliga Expeditionskårsenheter har överlämnats till dina segrande styrkor: %units% indianSettlement.mission.enemyDenounce=en %enemy% missionär anklagade vår missionär i %settlement% för kätteri, men %nation% avslog yrkandet. indianSettlement.mission.noDenounce=%nation% avvisar alla anklagelser om kätteri, och avrättar din missonär som en falsk profet. +indianSettlement.mission.tension.angry=Missionären fångades, %nation% förkastar din nya religion. +indianSettlement.mission.tension.content=Mission grundades, %nation% närmar sig din nya religion med nyfikenhet. +indianSettlement.mission.tension.displeased=Mission grundades, %nation% är upprörda. +indianSettlement.mission.tension.happy=Mission grundades, %nation% närmar sig din nya religion med glädje. +indianSettlement.mission.tension.hateful=Missionären offrades, %nation% skrattar åt din nya religion. scoutSettlement.tributeAgree=Vi går med på att betala %amount% guld för att bevara freden, men försök inte med detta en gång till! scoutSettlement.tributeDisagree=Vi går inte med på era krav. Ge er av från våra marker! colopedia.birthAndDeath=Födelse och död @@ -2186,6 +2245,7 @@ colopedia.unit.offensivePower=Anfallsstyrka: colopedia.unit.price=Pris i Europa: colopedia.unit.productionBonus=Produktions{{plural:%number%|one=modifierare|other=modifierare}}: colopedia.unit.requirements=Förutsättningar: +# Fuzzy colopedia.unit.school=Skola behövs för att utbilda: colopedia.unit.skill=Specialkunskap: report.labour.allColonists=Alla kolonisatörer @@ -2219,8 +2279,6 @@ report.colony.making.noconstruction.description=%colony%: Inget är under konstr report.colony.making.noteach.description=%colony%: %teacher% saknar en student report.colony.name.description=Listan över kolonier report.colony.name.header=Koloni -report.colony.plow.header=P -report.colony.road.header=R report.continentalCongress.elected=Vald: %turn% report.continentalCongress.none=(ingen) report.continentalCongress.recruiting=Rekryterar @@ -2270,15 +2328,15 @@ report.requirements.surplus=Ett överskott av %goods% framställs i report.trade.afterTaxes=Inkomst efter skatt report.trade.beforeTaxes=Inkomst före skatt report.trade.cargoUnits=Enheter i last -report.trade.hasCustomHouse=* Denna koloni har ett tullhus; dessa varor exporteras. +report.trade.hasCustomHouse=* Denna koloni har ett tullhus; dessa varor kan exporteras. report.trade.totalDelta=Sammanlagd produktion report.trade.totalUnits=Totalt antal enheter report.trade.unitsSold=Antal köpta eller sålda enheter report.turn.filter=Visa inte denna typ av meddelanden (%type%) report.turn.ignore=Ignorera detta meddelande (Koloni: %colony%, Vara: %goods%) -report.turn.playerNation=%nation% för %player% # Fuzzy -aboutPanel.copyright=Copyright © 2002-2014 FreeCol-teamet +report.turn.playerNation=%nation% för %player% +aboutPanel.copyright=Copyright © 2002-2015 FreeCol-teamet aboutPanel.legalDisclaimer=FreeCol är fri mjukvara: du kan vidaredistribuera den och/eller modifiera den under vad som specifieras i GNU General Public License som denna publicerats av Free Software Foundation, antingen version 2 av licensen eller någon senare version. aboutPanel.officialSite=Officiell hemsida: aboutPanel.sfProject=SourceForge-projekt: @@ -2286,8 +2344,7 @@ aboutPanel.version=Version: buildingToolTip.breeding=Du behöver minst %number% {{plural:%number%|%goods%}} att föda upp %goods%. buildQueuePanel.buildings=Byggnader buildQueuePanel.buildQueue=Byggkö -# Fuzzy -buildQueuePanel.buyBuilding=Köp byggnad +buildQueuePanel.buyBuilding=Köp %buildable% buildQueuePanel.compactView=Kompakt visning buildQueuePanel.currentlyBuilding=Bygger: %buildable% buildQueuePanel.populationTooSmall=Befolkning %number% @@ -2295,13 +2352,13 @@ buildQueuePanel.requires=Kräver: %string% buildQueuePanel.showAll=Visa allt buildQueuePanel.units=Trupper captureGoodsDialog.title=Plundringslast -cargoPanel.cargoAndSpace=Fraktgods ombord på %name% (%space% {{plural:%space%|one=rymmer|other=rymmer|default=rymmer}} vänster) +cargoPanel.cargoAndSpace=Fraktgods ombord på %name% (%space% {{plural:%space%|one=plats|other=platser|default=platser}} kvar) chatPanel.message=Meddelande chooseFoundingFatherDialog.title=Nominera grundare colonyPanel.colonyUnits=Kolonienheter colonyPanel.inPort=I hamn colonyPanel.outsideColony=Utanför kolonin -colonyPanel.producing=Producerar: +colonyPanel.producing=producerar: colonyPanel.reducePopulation=Om du minskar befolkningen under %number%, kan inte %colony% längre bygga %buildable%. colonyPanel.unitChange=Vid ankomst till din koloni blev din %oldType% en %newType%. colonyPanel.warehouse=Lager @@ -2313,7 +2370,9 @@ colonyPanel.notBestTile=%unit% kan producera mer %goods% på %tile%. confirmDeclarationDialog.areYouSure.no=Kanske senare confirmDeclarationDialog.areYouSure.text=Låt oss kasta av oket av den tyranni som %monarch% utsätter oss för och förklara våra kolonier för oavhängiga från kronan! confirmDeclarationDialog.areYouSure.yes=Frihet eller döden! +# Fuzzy confirmDeclarationDialog.defaultCountry=%nation%s förenta stater +# Fuzzy confirmDeclarationDialog.defaultNation=Den fria nationen %nation% confirmDeclarationDialog.enterCountry=Hädanefter skall vårt land vara känt som confirmDeclarationDialog.enterNation=och varje medborgare i vårt ärorika land skall vara stolta över att kallas för @@ -2339,9 +2398,9 @@ negotiationDialog.add=Lägg till negotiationDialog.cancel=Avbryt negotiationDialog.clear=Rensa negotiationDialog.contact.tutorial=Du träffar på andra européer. De konkurrerar med dig om land och rikedomar, och kan mycket väl dra ut i krig mot dig. Men efter att Jan de Witt har anslutit sig till kolonialstyret så kan du handla med dem. -negotiationDialog.demand=%nation% kräver av %otherNation% +negotiationDialog.demand={{tag:country|%nation%}} kräver av {{tag:country|%otherNation%}} negotiationDialog.exchange=i utbyte mot -negotiationDialog.offer=%nation% erbjuder %otherNation% +negotiationDialog.offer={{tag:country|%nation%}} erbjuder {{tag:country|%otherNation%}} negotiationDialog.send=Skicka negotiationDialog.title.contact=Träffar andra européer negotiationDialog.title.diplomatic=Diplomatiska förhandlingar @@ -2363,10 +2422,10 @@ findSettlementPanel.displayAll=Hitta alla bosättningar findSettlementPanel.displayOnlyEuropean=Hitta endast Europeiska bosättningar findSettlementPanel.displayOnlyNatives=Hitta endast inhemska bosättningar findSettlementPanel.name=Hitta bosättning -firstContactDialog.meeting.natives=Träffar infödingarna... +firstContactDialog.meeting.natives=Träffar infödingarna firstContactDialog.meeting.natives.tutorial=Du träffar på indianer. Sänd dina spejare till deras bosättningar för att lära dig mer om dem, och dina kontraktarbetare och nybyggare för att lära sig mer av dem. Sänd dina skepp och konvojer till deras bosättningar om du önskar handla med dem. -firstContactDialog.meeting.AZTEC=Azteknationen... -firstContactDialog.meeting.INCA=Inkariket... +firstContactDialog.meeting.aztec=Azteknationen +firstContactDialog.meeting.inca=Inkariket firstContactDialog.welcomeOffer.text=%nation% välkomnar dig. Vi är en strålande nation på %camps% %settlementType%. För att fira vår vänskap erbjuder vi generöst det land du nu bor på som en gåva. Vill du acceptera vårt fördrag och leva i fred med oss som bröder? firstContactDialog.welcomeSimple.text=%nation% välkomar dig. Vi är en strålande nation på %camps% %settlementType%. Vill du leva i fred med oss som bröder? abandonColony.no=Avbryt @@ -2388,7 +2447,9 @@ indianSettlementPanel.learnableSkill=Följande specialkunskaper lärs ut i denna indianSettlementPanel.highlyWanted=Denna bosättning vill mycket gärna köpa: indianSettlementPanel.otherWanted=Andra varor som kan säljas vid denna bosättning är: indianSettlementPanel.mostHated=Den mest hatade nationen i denna bosättning: +infoPanel.defenseBonus=Försvar %bonus%% infoPanel.endTurn=Tryck på Enter för att avsluta draget. +infoPanel.movementCost=Förflyttning %cost% infoPanel.moves=Steg: loadingSavegameDialog.port=Port: loadingSavegameDialog.privateMultiplayer=Privat flerspelarspel @@ -2476,8 +2537,7 @@ warehouseDialog.exportLevel.shortDescription=Exportera inte något under denna n warehouseDialog.highLevel.shortDescription=Ge mig en varning när antalet i lager överskrider denna procentandel av kapaciteten warehouseDialog.lowLevel.shortDescription=Ge mig en varning när antalet i lager sjunker under denna procentandel av kapaciteten warehouseDialog.name=Varulager -# Fuzzy -workProductionPanel.zeroThreshold=Ingen +workProductionPanel.zeroThreshold=Ingen negativ produktion nameCache.base.colony=Koloni nameCache.base.settlement=Bosättning nameCache.base.ship=Fartyg diff --git a/data/strings/FreeColMessages_tl.properties b/data/strings/FreeColMessages_tl.properties index 73a956873..bc3c575e8 100644 --- a/data/strings/FreeColMessages_tl.properties +++ b/data/strings/FreeColMessages_tl.properties @@ -160,8 +160,9 @@ cli.no-memory-check=laktawan ang pagsusuri ng alaala cli.no-sound=patakbuhing walang tunog ang FreeCol cli.private=pagsimulain ang isang pansariling serbidor (hindi nakalathala sa tagapaghain ng meta) cli.seed=magbigay ng isang SEED para sa di-tunay na alin mang pagpiling tagalikha ng bilang -cli.server-name=tumukoy ng isang pinasadyang PANGALAN para sa serbidor +# Fuzzy cli.server=pagsimulain ang isang nakatatayo ng mag-isang serbidor sa ibabaw ng tinukoy na daungan +cli.server-name=tumukoy ng isang pinasadyang PANGALAN para sa serbidor cli.splash=ipakita ang ang isang talaksang may sumasaboy na larawan sa panooran habang ikinakarga ang laro cli.tc=ikarga ang kabuoan ng pagpapalit na may ibinigay na PANGALAN cli.timeout=bilang ng mga segundo na maghihintay ang tagapaghain ng sagot para sa isang tanong @@ -229,7 +230,6 @@ colopediaAction.goods.name=Mabuting mga dala-dalahin colopediaAction.nations.name=Mga Bansa colopediaAction.nationTypes.name=Pambansang mga Kapakinabangan colopediaAction.resources.name=Karagdagang mga Mapagkukunan -colopediaAction.skills.name=Mga kasanayan colopediaAction.terrain.name=Mga uri ng lupain colopediaAction.units.name=Mga yunit (bahagi) colopediaAction.name=%object% (Colopedia) @@ -1239,6 +1239,7 @@ model.improvement.road.description=Daan model.improvement.road.name=Daan model.improvement.road.occupationString=D model.limit.independence.coastalColonies.name=Hangganan ng Kolonyang Pangdalampasigan +# Fuzzy model.limit.independence.coastalColonies.description=Nangangailangan ka ng kahit na %limit% mga kolonyang pandalampasigan upang makapagpahayag ng kasarinlan. model.limit.independence.rebels.name=Hangganan ng Manghihimagsik model.limit.independence.rebels.description=Hindi dapat bababa sa %limit%% ng mga kolonista mo ang tatangkilik sa pagsasarili. @@ -1568,6 +1569,7 @@ model.colony.badGovernment=Kulang sa katalaban ang pamahalaan ng %colony%. Naaan model.colony.goodGovernment=Uminam na ang katalaban ng pamahalaan! Katumbas na o lumampas na sa %number% bahagdan ang damdaming mapanghimagsik sa loob ng %colony%. model.colony.governmentImproved1=Uminam na ang pamahalaan ng %colony%, ngunit kulang pa rin sa katalaban. Naaangkop pa rin ang\nmga pagmumulta sa produksyon. model.colony.governmentImproved2=Uminam na ang pamahalaan ng %colony%. Hindi na naaangkop ang mga pagmumulta sa produksyon. +# Fuzzy model.colony.insufficientProduction=%outputAmount% dagdag pang %outputType% ang magagawa sa %colony%, kung mayroon lamang tayong %inputAmount% dagdag pang %inputType% bilang pasobra. model.colony.lostGoodGovernment=Bumaba ang katalaban ng pamahalaan! Hindi na katumbas ng o lampas na sa %number% bahagdan ang damdaming mapanghimagsik sa loob ng %colony%. Hindi na nakakatamo ng anumang bonus sa produksyon ang kolonya. model.colony.lostVeryGoodGovernment=Bumaba ang katalaban ng pamahalaan! Hindi na katumbas o lumampas na sa %number% bahagdan ang damdaming mapanghimagsik sa loob ng %colony%. Nawala ang ilang mga bonus sa produksyon. @@ -1585,21 +1587,29 @@ model.direction.SW.name=timog-kanluran model.direction.W.name=kanluran model.direction.NW.name=hilaga-kanluran model.historyEventType.abandonColony.description=Iniwanan mo ang kolonya ng %colony%. +# Fuzzy model.historyEventType.cityOfGold.description=Natuklasan ng %nation% ang %city%, isa sa Pitong mga Lungsod ng Ginto, at isang kayamanan ng gintong %treasure%. +# Fuzzy model.historyEventType.colonyConquered.description=Sinakop ng %nation% ang iyong kolonyang %colony%. +# Fuzzy model.historyEventType.colonyDestroyed.description=Winasak ng %nation% ang iyong kolonyang %colony%. # Fuzzy model.historyEventType.conquerColony.description=Nangangahas kang tanggapin ang Aming may kagandahang loob na katakdaan subalit umiiwas din sa pagbabayad? Ang ganyang pagdadalawang-mukha ay magtatamo ng mapait na gantimpala ng Aming pagkayamot. # Fuzzy model.historyEventType.declareIndependence.description=Wawasakin mo ang isang maliit na pamayanang %settlement% ng %nation%. +# Fuzzy model.historyEventType.destroyNation.description=Wawasakin ng %nation% ang %nativeNation%. model.historyEventType.discoverNewWorld.description=Tuklasin mo ang Bagong Mundo. +# Fuzzy model.historyEventType.discoverRegion.description=Natuklasan ng %nation% ang %region%. model.historyEventType.foundColony.description=Inilunsad mo ang kolonya ng %colony%. model.historyEventType.foundingFather.description=Sumali si %father% sa Kongresong Kontinental. model.historyEventType.independence.description=Nakamit mo ang kasarinlan mula sa Korona. +# Fuzzy model.historyEventType.meetNation.description=Nakaharap mo ang %nation%. +# Fuzzy model.historyEventType.nationDestroyed.description=Wala na ngayong %nation% sa Bagong Mundo. +# Fuzzy model.historyEventType.spanishSuccession.description=Isinusuko ng %loserNation% sa %nation% ang lahat ng kanilang mga kolonyang nasa Bagong Mundo. model.indianSettlement.mostHatedNone=Wala model.indianSettlement.nameUnknown=Hindi alam @@ -1644,8 +1654,10 @@ model.messageType.warehouseCapacity.name=Sukat ng Mailululan sa Bahay-Imbakan model.messageType.warning.name=Mga babala model.monarch.action.addToRef.text=Ang Korona ay nagdagdag ng %number% {{plural:%number%|%unit%}} sa Royal na Puwersang Pang-ekspedisyon. Nagpahayag ng pangangamba ang mga pinunong pangkolonya. model.monarch.action.addToRef.no=Nagawa na +# Fuzzy model.monarch.action.declarePeace.text=May karikitan kaming sumasang-ayon sa isang kasunduang pangkapayapaan sa piling ng %nation%. model.monarch.action.declarePeace.no=Nagawa na +# Fuzzy model.monarch.action.declareWar.text=Ang kawalang-hiyaan ng %nation% ang pumupuwersa sa Amin na magpahayag ng digmaan sa kanila! model.monarch.action.declareWar.no=Nagawa na # Fuzzy @@ -1690,6 +1702,7 @@ model.noClaimReason.worked.description=Mayroon nang ibang maliit na pamayanan na model.player.forces=Mga Puwersa ng %nation% model.player.independentMarket=Europa model.player.startGame=Makalipas ang ilang mga buwan habang nasa dagat, narating mo na rin sa wakas ang sa may baybayin ng isang hindi nakikilalang kontinente. Maglayag {{tag:%direction%|west=pakanluran|east=pasilangan|default=pasagupa sa hangin}} upang matuklasan ang Bagong Mundo at angkinin ito para sa Korona. +# Fuzzy model.player.waitingFor=Hinihintay ang: %nation% model.regionType.coast.name=Dalampasigan model.regionType.coast.unknown=Hindi Nalalamang Rehiyon ng Dalampasigan @@ -1744,9 +1757,9 @@ model.unit.underRepair=Kinukumpuni (%turns% {{plural:%turns%|one=lumiliko sa|oth model.unit.unitState.active=- model.unit.unitState.fortified=P model.unit.unitState.fortifying=P -model.unit.unitState.improving=# model.unit.unitState.inColony=H model.unit.unitState.sentry=B +# Fuzzy model.unit.unitState.skipped=L model.unit.unitState.toAmerica=P model.unit.unitState.toEurope=P @@ -1783,12 +1796,14 @@ model.colony.warehouseOverfull=Umabot na sa kanyang kayang mailulang %goods% ang model.colony.warehouseSoonFull=Lalampas na sa kanyang kayang mailulang %goods% ang iyong bahay-imbakang nasa %colony% sa loob ng susunod na pagkakataon. Masasayang ang %amount% mga yunit ng %goods%. model.colony.warehouseWaste=Lumagpas na sa kanyang kayang mailulang %goods% ang iyong bahay-imbakang nasa %colony%. Nasayang ang %waste% mga yunit. model.colonyTile.resourceExhausted=Naubos na ang pangangailangang %resource% na nasa %colony% +# Fuzzy model.game.spanishSuccession=Aming Kamahalan, nagwakas na sa Europa ang Digmaan ng Kastilang Paghahalili. Sa Tratado ng Utrecht, ang %loserNation% ay napilitang isuko sa %nation% ang lahat ng mga kolonyang nasa Bagong Mundo! model.indianSettlement.mission.denounced=Pinaratangan ang iyong misyonero sa %settlement% at pinaslang! model.player.autoRecruit=Ang kaguluhang pangrelihiyon sa %europe% ay nag-udyok sa %unit% upang mandayuhan. model.player.colonyGoodsParty.harbour=Nagtapon sa daungan ang iyong mga kolonistang nasa %colony% ng %amount% ng mga yunit ng %goods% bilang pagtutol laban sa hindi patas na pagbubuwis ng Korona! model.player.colonyGoodsParty.horses=Nagpalaya ang mga kolonista mong nasa %colony% ng %amount% mga kabayo bilang pagtutol sa ganitong hindi patas na pagbubuwis mula sa Korona! model.player.colonyGoodsParty.landLocked=Nagsunog sa pook ng pamilihan ang iyong mga kolonistang nasa %colony% ng %amount% ng mga yunit ng %goods% bilang pagtutol laban sa hindi patas na pagbubuwis ng Korona! +# Fuzzy model.player.dead.european=Aming Kamahalaan, nagpahayag ang %nation% ng ganap na pag-alis mula sa mga usapin ng Bagong Mundo! model.player.dead.native=Aming kamahalan, nawasak na ang %nation%. model.player.disaster.bankruptcy.start=Nabigo ka sa pagbabayad para sa pangangalaga ng lahat ng mga gusali. Ilalapat ang matinding mga multa sa produksiyon. @@ -1800,12 +1815,16 @@ model.player.foundingFatherJoinedCongress=Nakilahok na sa kongreso si %foundingF model.player.interventionForceArrives=Dumating na ang ipinangakong Puwersang Pampamamagitan! model.player.soLDecrease=Bumaba na hanggang %newSoL% bahagdan ang kasapian sa Mga Anak na Lalaki ng Kalayaan na nasa mga kolonya mo! model.player.soLIncrease=Tumaas na hanggang %newSoL% bahagdan ang kasapian sa Mga Anak na Lalaki ng Kalayaan na nasa mga kolonya mo! +# Fuzzy model.player.stance.alliance.declared=Aming Kamahalan, umanib na sa atin ang %nation%! model.player.stance.alliance.others=Aming Kamahalan, umanib sa %attacker% ang %defender%. +# Fuzzy model.player.stance.ceaseFire.declared=Aming Kamahalan, pumayag ang %nation% na makipagtigil-putukan sa atin! model.player.stance.ceaseFire.others=Aming Kamahalan, pumayag ang %attacker% na makipagtigil-putukan sa %defender%. +# Fuzzy model.player.stance.peace.declared=Aming Kamahalan, nakipagkasundo sa atin ng kapayapaan ang %nation%! model.player.stance.peace.others=Aming Kamahalan, nakipagkasundo ang %attacker% ng kapayapaan sa %defender%. +# Fuzzy model.player.stance.war.declared=Masamang balita, Aming Kamahalan, nagpahayag ng digmaan laban sa atin ang %nation%! model.player.stance.war.others=Aming Kamahalan, nagpahayag ng digmaan ang %attacker% laban sa %defender%. combat.automaticDefence=Ang %unit% mo sa %colony% ay nagsigamit ng mga sandata upang maipagtanggol ang kolonya! @@ -1821,6 +1840,7 @@ combat.enemyShipEvaded=Nakaiwas ang %enemyUnit% ng %enemyNation% mula sa isang p combat.enemyShipSunk=Napalubog ng %unit% ang %enemyUnit% ng %enemyNation%! combat.equipmentCaptured=Mag-ingat, napasakamay ng mga matatapang ng %nation% ang %equipment%! combat.goodsStolen=Nagnakaw ng %amount% ng mga %goods% ang %enemyUnit% ng %enemyNation% mula sa %colony%! +# Fuzzy combat.indianPlunder=Nangulimbat ng %amount% ang %enemyUnit% ng %enemyNation% mula sa %colony%. combat.indianRaid=Nag-ulat ang aming mga espiya na nilusob ng %nation% ang kolonyang %colonyNation% ng %colony%. combat.indianSurprise=Nagsagawa ng hindi inaakalang paglusob ang %nation% doon sa %colony%, na nakapagpangamba sa aming mga kolonista. Ipinagkakaila ng pinuno ng %nation% ang pagiging kasangkot. @@ -1873,13 +1893,16 @@ error.couldNotLoad=Naganap ang isang kamalian habang sinusubok na ikarga ang lar # Fuzzy error.couldNotSave=Naganap ang isang kamalian habang sinasagip ang laro! main.defaultPlayerName=Pangalan ng Manlalaro +# Fuzzy client.choicePlayer=Pumili lamang po ng isang manlalaro: metaServer.couldNotConnect=Paumanhin, hindi makaugnay/makakunekta sa serbidor ng meta. Pakisubok na lang uli mamaya. metaServer.communicationError=Nagkaroon ng isang kamalian habang nakikipagtalastasan/nakikipag-ugnayan sa serbidor ng meta. Pakisubok muli mamaya. abandonEducation.action.studying=nag-aaral abandonEducation.action.teaching=nagtuturo +# Fuzzy abandonEducation.no=Huwag, ipagpatuloy ang edukasyon abandonEducation.text=Kapag nilisan ng %unit% mo ang %colony% pababayaan nito ang %action% sa loob ng %building%, nakatitiyak ka bang dapat itong umalis? +# Fuzzy abandonEducation.yes=Oo, umalis mula sa kolonya boycottedGoods.dumpGoods=Itambak ang mabubuting mga daladalahin boycottedGoods.text=Dahil binoykoteo (hindi tinangkilik) ng Korona ang %goods%, hindi mo maipagbibili ang mga ito sa %europe%. Nais mo bang bayaran ang mga utang mo (%amount% ng ginto), o ibig mong itapon ang mga ito sa daungan, na wawasak sa mga ito? @@ -1887,8 +1910,11 @@ buy.moreGold=Humiling ng mas mababa pang halaga buy.takeOffer=Tanggapin ang alok buy.text=Nais ipagbili ng %nation% ang kanilang %goods% bilang kapalit ng %gold%: clearTradeRoute.text=Ang %unit% mo ay itinalagang mangalakal sa rutang %route%. Ang pagtatakda ng destinasyon nito ay makapagtatanggal nito mula sa ruta ng kalakalan. Nakatitiyak ka bang ito ang nais mong gawin? +# Fuzzy confirmHostile.alliance=Hindi mo maaaring lusubin ang isang kakamping bansa! Talaga bang nais mong putulin ang iyong pakikipagtulungan sa %nation%. +# Fuzzy confirmHostile.ceaseFire=Lumagda ka ng isang tigil putukan na kasama ang %nation%. Talaga bang nais mong lumusob? +# Fuzzy confirmHostile.peace=Mapayapa ang pakikitungo mo sa %nation%. Talaga bang nais mong magpahayag ng digmaan? error.noSuchFile=Hindi umiiral ang tinukoy na talaksan o hindi isang pangkaraniwang talaksan. # Fuzzy @@ -1942,7 +1968,9 @@ defeated.text=Natalo ka na! Nais mo bang: defeated.yes=Manatili at magmatyag defeatedSinglePlayer.text=Nagapi ka na!\n\nNgayon ay kalaliman na ng gabi, Kung kailan humihikab na ang bakuran ng mga simbahan at naghihinga ang impiyerno ng mga paminsala sa mundong ito, makainom kaya ako ngayon ng mainit na dugo?! At makagawa ng ganyang mapait na kaabalahan, habang yumayanig ang araw upang tumanaw. defeatedSinglePlayer.yes=Ipasok ang Gawi ng Paghihiganti +# Fuzzy diplomacy.offerAccepted=Tinanggap ng %nation% ang iyong masaganang alok. +# Fuzzy diplomacy.offerRejected=Tinanggap ng %nation% ang masagana mong alok. disbandUnit.text=Nakatitiyak ka bang nais mong pagwatak-watakin ang yunit na ito? disbandUnit.yes=Pagwatak-watakin na @@ -1985,7 +2013,9 @@ move.noAccessContact=Kailangan muna nating magtatag ng ugnayan sa %nation%, Kama move.noAccessGoods=Ang %nation% ay hindi makikipagkalakal sa isang %unit% na walang laman. move.noAccessSettlement=Hindi pinapahintulutan ng %nation% ang ating %unit% na pumasok sa kanilang maliit na pamayanan. move.noAccessSkill=Hindi maaaring matuto mula sa mga katutubo ang ating %unit%. +# Fuzzy move.noAccessTrade=Wala tayong kapangyarihang makipagkalakal sa ibang mga nasyong Europeo na katulad ng %nation%. +# Fuzzy move.noAccessWar=Hindi tayo maaaring makipagkalakalan sa %nation% habang may digmaan. move.noAccessWater=Kailangan lumapag ng ating %unit% bago pumasok sa maliit na pamayanan. move.noAttackWater=Dapat na lumapag muna ang aming %unit% bago lumusob. @@ -2020,6 +2050,7 @@ server.invalidPlayerNations=Kinakailangang pumili muna ng isang bukod-tanging ba server.maximumPlayers=Paumanhin, naabot na ang pinakamataas na bilang ng mga manlalaro. server.missingUserName=Ang pangalan ng tagagamit ay nawawala mula sa hiling ng paglagda. server.missingVersion=Nawawala ang bersiyon ng FreeCol mula sa hiling na paglagda. +# Fuzzy server.noRouteToServer=Hindi maaaring ipakita sa madla/publiko ang serbidor. Dapat mong baguhin ang mga pagtatakda mong pang-"pader na pamigil ng pagkalat ng apoy" (''firewall'') upang pahintulutan ang mga ugnayan/konseksyon sa daungang tinukoy mo. server.notAllReady=Hindi pa nakahandang magsimula ng laro ang lahat ng mga manlalaro! server.onlyAdminCanLaunch=Paumanhin, tanging ang tagapangasiwa lamang ng serbidor ang makapaglulunsad ng laro. @@ -2112,6 +2143,7 @@ colopedia.unit.offensivePower=Lakas ng Pagsalakay: colopedia.unit.price=Halaga sa Europa: colopedia.unit.productionBonus={{plural:%number%|isa=tagapagbago|iba=mga tagapagbago}} ng produksyon: colopedia.unit.requirements=Mga kailangan: +# Fuzzy colopedia.unit.school=Kailangang paaralan upang makapagsanay: colopedia.unit.skill=Antas ng Kasanayan: report.labour.allColonists=Lahat ng mga Kolonista @@ -2149,8 +2181,6 @@ report.colony.improve.description=Mga yunit na makapagpapainam ng produksiyon na report.colony.improve.header=Painamin # Fuzzy report.colony.improving.description=%colony%: Upang makagawa ng %amount% pang mga %goods%Class
to extract from.
- * @return A value of the package version attribute.
+ * @return The JarURLConnection
.
*/
- private static String readVersion(Class c) throws IOException {
+ private static JarURLConnection getJarURLConnection(Class c) throws IOException {
String resourceName = "/" + c.getName().replace('.', '/') + ".class";
URL url = c.getResource(resourceName);
- Manifest mf = ((JarURLConnection)url.openConnection()).getManifest();
- return mf.getMainAttributes().getValue("Package-Version");
+ return (JarURLConnection)url.openConnection();
+ }
+
+ /**
+ * Extract the package version from the class.
+ *
+ * @param juc The JarURLConnection
to extract from.
+ * @return A value of the package version attribute.
+ */
+ private static String readVersion(JarURLConnection juc) throws IOException {
+ Manifest mf = juc.getManifest();
+ return (mf == null) ? null
+ : mf.getMainAttributes().getValue("Package-Version");
}
+ /**
+ * Get a stream for the default splash file.
+ *
+ * Note: Not bothering to check for nulls as this is called in try
+ * block that ignores all exceptions.
+ *
+ * @param juc The JarURLConnection
to extract from.
+ * @return A suitable InputStream
, or null on error.
+ */
+ private static InputStream getDefaultSplashStream(JarURLConnection juc) throws IOException {
+ JarFile jf = juc.getJarFile();
+ ZipEntry ze = jf.getEntry(SPLASH_DEFAULT);
+ return jf.getInputStream(ze);
+ }
+
/**
* Exit printing fatal error message.
*
@@ -517,6 +548,9 @@ public final class FreeCol {
options.addOption(OptionBuilder.withLongOpt("no-sound")
.withDescription(Messages.message("cli.no-sound"))
.create());
+ options.addOption(OptionBuilder.withLongOpt("no-splash")
+ .withDescription(Messages.message("cli.no-splash"))
+ .create());
options.addOption(OptionBuilder.withLongOpt("private")
.withDescription(Messages.message("cli.private"))
.create());
@@ -527,14 +561,17 @@ public final class FreeCol {
.create());
options.addOption(OptionBuilder.withLongOpt("server")
.withDescription(Messages.message("cli.server"))
- .withArgName(Messages.message("cli.arg.port"))
- .hasOptionalArg()
.create());
options.addOption(OptionBuilder.withLongOpt("server-name")
.withDescription(Messages.message("cli.server-name"))
.withArgName(Messages.message("cli.arg.name"))
.hasArg()
.create());
+ options.addOption(OptionBuilder.withLongOpt("server-port")
+ .withDescription(Messages.message("cli.server-port"))
+ .withArgName(Messages.message("cli.arg.port"))
+ .hasArg()
+ .create());
options.addOption(OptionBuilder.withLongOpt("splash")
.withDescription(Messages.message("cli.splash"))
.withArgName(Messages.message("cli.arg.file"))
@@ -722,29 +759,41 @@ public final class FreeCol {
if (line.hasOption("no-sound")) {
sound = false;
}
+ if (line.hasOption("no-splash")) {
+ splashStream = null;
+ }
if (line.hasOption("private")) {
publicServer = false;
}
if (line.hasOption("server")) {
- String arg = line.getOptionValue("server");
- if (!setServerPort(arg)) {
- fatal(StringTemplate.template("cli.error.serverPort")
- .addName("%string%", arg));
- }
standAloneServer = true;
}
if (line.hasOption("server-name")) {
serverName = line.getOptionValue("server-name");
}
+ if (line.hasOption("server-port")) {
+ String arg = line.getOptionValue("server-port");
+ if (!setServerPort(arg)) {
+ fatal(StringTemplate.template("cli.error.serverPort")
+ .addName("%string%", arg));
+ }
+ }
if (line.hasOption("seed")) {
FreeColSeed.setFreeColSeed(line.getOptionValue("seed"));
}
if (line.hasOption("splash")) {
- splashFilename = line.getOptionValue("splash");
+ String splash = line.getOptionValue("splash");
+ try {
+ FileInputStream fis = new FileInputStream(splash);
+ splashStream = fis;
+ } catch (FileNotFoundException fnfe) {
+ gripe(StringTemplate.template("cli.error.splash")
+ .addName("%name%", splash));
+ }
}
if (line.hasOption("tc")) {
@@ -876,14 +925,10 @@ public final class FreeCol {
* @return The type of advantages set, or null if none.
*/
private static Advantages selectAdvantages(String advantages) {
- for (Advantages a : Advantages.values()) {
- String msg = Messages.getName(a);
- if (msg.equals(advantages)) {
- setAdvantages(a);
- return a;
- }
- }
- return null;
+ Advantages adv = find(Advantages.values(),
+ a -> Messages.getName(a).equals(advantages), null);
+ if (adv != null) setAdvantages(adv);
+ return adv;
}
/**
@@ -901,11 +946,8 @@ public final class FreeCol {
* @return A list of advantage types.
*/
private static String getValidAdvantages() {
- String ret = "";
- for (Advantages a : Advantages.values()) {
- ret += "," + Messages.getName(a);
- }
- return ret.substring(1);
+ return Arrays.stream(Advantages.values())
+ .map(a -> Messages.getName(a)).collect(Collectors.joining(","));
}
/**
@@ -924,15 +966,10 @@ public final class FreeCol {
* @return The name of the selected difficulty, or null if none.
*/
public static String selectDifficulty(String arg) {
- for (String d : DIFFICULTIES) {
- String key = "model.difficulty." + d;
- String value = Messages.getName(key);
- if (value.equals(arg)) {
- setDifficulty(key);
- return key;
- }
- }
- return null;
+ String difficulty = find(map(DIFFICULTIES, d -> "model.difficulty."+d),
+ k -> Messages.getName(k).equals(arg), null);
+ if (difficulty != null) setDifficulty(difficulty);
+ return difficulty;
}
/**
@@ -960,13 +997,9 @@ public final class FreeCol {
* @return The valid difficulty levels, comma separated.
*/
public static String getValidDifficulties() {
- String s = "";
- for (String d : DIFFICULTIES) {
- String key = "model.difficulty." + d;
- String value = Messages.getName(key);
- s += "," + value;
- }
- return s.substring(1);
+ return Arrays.stream(DIFFICULTIES)
+ .map(d -> Messages.getName("model.difficulty." + d))
+ .collect(Collectors.joining(","));
}
/**
@@ -1312,7 +1345,7 @@ public final class FreeCol {
// savegame was specified on command line
}
final FreeColClient freeColClient
- = new FreeColClient(splashFilename, fontName, guiScale, headless);
+ = new FreeColClient(splashStream, fontName, guiScale, headless);
freeColClient.startClient(windowSize, userMsg, sound, introVideo,
savegame, spec);
}
@@ -1348,14 +1381,15 @@ public final class FreeCol {
try {
freeColServer = new FreeColServer(publicServer, false, spec,
serverPort, serverName);
- } catch (NoRouteToServerException nrtse) {
- fatal(Messages.message("server.noRouteToServer"));
- return;
} catch (Exception e) {
fatal(Messages.message("server.initialize")
+ ": " + e.getMessage());
return;
}
+ if (publicServer && freeColServer != null
+ && !freeColServer.getPublicServer()) {
+ gripe(Messages.message("server.noRouteToServer"));
+ }
}
String quit = FreeCol.SERVER_THREAD + "Quit Game";
diff --git a/src/net/sf/freecol/client/ClientOptions.java b/src/net/sf/freecol/client/ClientOptions.java
index 68b6af848..3b7e677aa 100644
--- a/src/net/sf/freecol/client/ClientOptions.java
+++ b/src/net/sf/freecol/client/ClientOptions.java
@@ -42,6 +42,7 @@ import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
+import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Unit;
@@ -131,7 +132,7 @@ public class ClientOptions extends OptionGroup {
/**
* Selected tiles always gets centered if this option is enabled (even if
- * the tile is {@link net.sf.freecol.client.gui.GUI#onScreen(Tile)}).
+ * the tile is on screen.
*
* @see net.sf.freecol.client.gui.GUI
*/
@@ -140,8 +141,7 @@ public class ClientOptions extends OptionGroup {
/**
* If this option is enabled, the display will recenter in order
- * to display the active unit if it is not
- * {@link net.sf.freecol.client.gui.GUI#onScreen(Tile)}).
+ * to display the active unit if it is not on screen.
*
* @see net.sf.freecol.client.gui.GUI
*/
@@ -430,67 +430,30 @@ public class ClientOptions extends OptionGroup {
= "clientOptions.mods.userMods";
- /**
- * Comparators for sorting colonies.
- */
+ // Comparators for sorting colonies.
+ /** Compare by ascending age. */
private static final ComparatorFreeColClient
. Creates the control
* objects.
*
- * @param splashFilename The name of the splash image.
+ * @param splashStream A stream to read the splash image from.
* @param fontName An optional override of the main font.
* @param scale The scale factor for gui elements.
* @param headless Run in headless mode.
*/
- public FreeColClient(final String splashFilename, final String fontName,
+ public FreeColClient(final InputStream splashStream, final String fontName,
final float scale, boolean headless) {
mapEditor = false;
this.headless = headless
@@ -161,7 +162,7 @@ public final class FreeColClient {
// Get the splash screen up early on to show activity.
gui = (this.headless) ? new GUI(this, scale)
: new SwingGUI(this, scale);
- gui.displaySplashScreen(splashFilename);
+ gui.displaySplashScreen(splashStream);
// Look for base data directory. Failure is fatal.
File baseDirectory = FreeColDirectories.getBaseDirectory();
@@ -215,8 +216,6 @@ public final class FreeColClient {
} catch (IOException e) {
fatal(Messages.message("client.classic") + "\n" + e.getMessage());
}
- actionManager = new ActionManager(this);
- actionManager.initializeActions(inGameController, connectController);
if (!this.headless) {
// Swing system and look-and-feel initialization.
@@ -226,6 +225,8 @@ public final class FreeColClient {
fatal(Messages.message("client.laf") + "\n" + e.getMessage());
}
}
+ actionManager = new ActionManager(this);
+ actionManager.initializeActions(inGameController, connectController);
}
/**
@@ -281,40 +282,26 @@ public final class FreeColClient {
// NewPanel to a call to the connect controller to start a game)
if (savedGame != null) {
soundController.playSound("sound.intro.general");
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- if (!connectController.startSavedGame(savedGame,
- userMsg)) {
- gui.showMainPanel(userMsg);
- }
+ SwingUtilities.invokeLater(() -> {
+ if (!connectController.startSavedGame(savedGame, userMsg)) {
+ gui.showMainPanel(userMsg);
}
});
} else if (spec != null) { // Debug or fast start
soundController.playSound("sound.intro.general");
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- if (!connectController.startSinglePlayerGame(spec,
- true)) {
- gui.showMainPanel(userMsg);
- }
+ SwingUtilities.invokeLater(() -> {
+ if (!connectController.startSinglePlayerGame(spec, true)) {
+ gui.showMainPanel(userMsg);
}
});
} else if (showOpeningVideo) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- gui.showOpeningVideo(userMsg);
- }
+ SwingUtilities.invokeLater(() -> {
+ gui.showOpeningVideo(userMsg);
});
} else {
soundController.playSound("sound.intro.general");
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- gui.showMainPanel(userMsg);
- }
+ SwingUtilities.invokeLater(() -> {
+ gui.showMainPanel(userMsg);
});
}
@@ -705,6 +692,19 @@ public final class FreeColClient {
&& player.equals(game.getCurrentPlayer());
}
+ /**
+ * Common utility routine to retrieve animation speed.
+ *
+ * @param player The Player
to be animated.
+ * @return The animation speed.
+ */
+ public int getAnimationSpeed(Player player) {
+ String key = (getMyPlayer() == player)
+ ? ClientOptions.MOVE_ANIMATION_SPEED
+ : ClientOptions.ENEMY_MOVE_ANIMATION_SPEED;
+ return getClientOptions().getInteger(key);
+ }
+
/**
* Get a list of the player colonies.
*
@@ -733,14 +733,17 @@ public final class FreeColClient {
*
* When the game is clear, show the new game panel.
*
- * Called from the New action, often from the button on the MainPanel.
+ * Called from the New action, often from the button on the MainPanel,
+ * and IGC.victory()
+ *
+ * @param prompt If true, prompt to confirm stopping the game.
*/
- public void newGame() {
+ public void newGame(boolean prompt) {
Specification specification = null;
if (getGame() != null) {
if (isMapEditor()) {
specification = getGame().getSpecification();
- } else if (gui.confirmStopGame()) {
+ } else if (!prompt || gui.confirmStopGame()) {
getConnectController().quitGame(true);
FreeColSeed.incrementFreeColSeed();
} else {
@@ -807,7 +810,7 @@ public final class FreeColClient {
if (validPeriod != 0L && autoSave != null
&& (flist = autoSave.list()) != null) {
for (String f : flist) {
- if (!f.endsWith(FreeCol.FREECOL_SAVE_EXTENSION)) continue;
+ if (!f.endsWith("." + FreeCol.FREECOL_SAVE_EXTENSION)) continue;
// delete files which are older than user option allows
File saveGameFile = new File(autoSave, f);
if (saveGameFile.lastModified() + validPeriod < timeNow) {
diff --git a/src/net/sf/freecol/client/control/ConnectController.java b/src/net/sf/freecol/client/control/ConnectController.java
index ed17fd833..4ee59d282 100644
--- a/src/net/sf/freecol/client/control/ConnectController.java
+++ b/src/net/sf/freecol/client/control/ConnectController.java
@@ -30,12 +30,15 @@ import java.util.logging.Logger;
import javax.swing.SwingUtilities;
import javax.xml.stream.XMLStreamException;
-import net.sf.freecol.FreeCol;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import net.sf.freecol.FreeCol;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.GUI;
-import net.sf.freecol.client.gui.panel.ChoiceItem;
-import net.sf.freecol.client.gui.panel.LoadingSavegameDialog;
+import net.sf.freecol.client.gui.LoadingSavegameInfo;
import net.sf.freecol.common.FreeColException;
import net.sf.freecol.common.ServerInfo;
import net.sf.freecol.common.debug.FreeColDebugger;
@@ -52,14 +55,10 @@ import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.common.networking.DOMMessage;
import net.sf.freecol.common.networking.LoginMessage;
-import net.sf.freecol.common.networking.NoRouteToServerException;
import net.sf.freecol.common.resources.ResourceManager;
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.FreeColServer.GameState;
-import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
-
/**
* The controller responsible for starting a server and connecting to it.
@@ -132,17 +131,20 @@ public final class ConnectController {
*/
private FreeColServer startServer(boolean publicServer,
boolean singlePlayer, Specification spec, int port) {
+ FreeColServer freeColServer;
try {
- return new FreeColServer(publicServer, singlePlayer, spec, port,
- null);
- } catch (NoRouteToServerException e) {
- gui.showErrorMessage("server.noRouteToServer");
- logger.log(Level.WARNING, "No route to server.", e);
+ freeColServer = new FreeColServer(publicServer, singlePlayer,
+ spec, port, null);
} catch (IOException e) {
+ freeColServer = null;
gui.showErrorMessage("server.initialize");
logger.log(Level.WARNING, "Could not start server.", e);
}
- return null;
+ if (publicServer && freeColServer != null
+ && !freeColServer.getPublicServer()) {
+ gui.showErrorMessage("server.noRouteToServer");
+ }
+ return freeColServer;
}
/**
@@ -296,7 +298,6 @@ public final class ConnectController {
}
freeColClient.setMyPlayer(player);
freeColClient.addSpecificationActions(game.getSpecification());
- freeColClient.updateActions();
logger.info("FreeColClient logged in as " + user
+ "/" + player.getId());
@@ -317,10 +318,10 @@ public final class ConnectController {
activeUnit.getOwner().setNextActiveUnit(activeUnit);
gui.setActiveUnit(activeUnit);
} else {
- gui.setSelectedTile(entryTile, false);
+ gui.setSelectedTile(entryTile);
}
} else {
- gui.setSelectedTile(entryTile, false);
+ gui.setSelectedTile(entryTile);
}
}
}
@@ -417,10 +418,13 @@ public final class ConnectController {
ListColony
to display.
+ * @param unit An optional Unit
to select.
+ */
+ private void colonyPanel(Colony colony, Unit unit) {
+ gui.showColonyPanel(colony, (unit.isCarrier()) ? unit : null);
}
/**
@@ -294,22 +312,29 @@ public final class InGameController implements NetworkConstants {
} else { // should not happen
player = freeColClient.getGame().getUnknownEnemy();
}
- return player.getNationName();
+ return player.getNationLabel();
}
/**
- * Updates the GUI after a unit moves.
+ * Update the GUI and the active unit with a fallback tile.
+ *
+ * @param tile An optional fallback Tile
to display if
+ * no active unit is found, useful when the last unit might have
+ * died.
*/
- private void updateControls() {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- freeColClient.updateActions();
- gui.updateMenuBar();
- }
- });
+ private void updateGUI(Tile tile) {
+ if (displayModelMessages(false, false)) {
+ ; // If messages are displayed they probably refer to the
+ // current unit, so do not update it.
+ } else if (updateActiveUnit(tile)) {
+ ; // setActiveUnit will update the menu bar
+ } else {
+ gui.updateMapControls();
+ gui.updateMenuBar();
+ }
}
+
// Server access routines called from multiple places.
/**
@@ -345,8 +370,7 @@ public final class InGameController implements NetworkConstants {
if (price < 0) { // not for sale
return false;
} else if (price > 0) { // for sale
- ClaimAction act = gui.getClaimChoice(tile, player, price,
- owner);
+ ClaimAction act = gui.getClaimChoice(tile, player, price, owner);
if (act == null) return false; // Cancelled
switch (act) {
case ACCEPT: // accepted price
@@ -370,17 +394,44 @@ public final class InGameController implements NetworkConstants {
* to null.
*
* @param unit The Unit
to clear the destination for.
- * @return True if the unit has no destination.
+ * @return True if the unit now has no destination or trade route.
*/
private boolean askClearGotoOrders(Unit unit) {
if (!askAssignTradeRoute(unit, null)) return false;
if (unit.getDestination() == null) return true;
- gui.clearGotoPath();
- return askSetDestination(unit, null);
+ if (askSetDestination(unit, null)) {
+ gui.clearGotoPath();
+ return true;
+ }
+ return false;
}
+ /**
+ * Embark onto a carrier.
+ *
+ * @param unit The Unit
to embark.
+ * @param carrier The carrier Unit
to board.
+ * @return True if boarding succeeded.
+ */
+ private boolean askEmbark(Unit unit, Unit carrier) {
+ ColonyWas colonyWas = (unit.getColony() != null)
+ ? new ColonyWas(unit.getColony()) : null;
+ EuropeWas europeWas = (unit.isInEurope())
+ ? new EuropeWas(unit.getOwner().getEurope()) : null;
+ UnitWas unitWas = new UnitWas(unit);
+ if (askServer().embark(unit, carrier, null)
+ && unit.getLocation() == carrier) {
+ sound("sound.event.loadCargo");
+ unitWas.fireChanges();
+ if (colonyWas != null) colonyWas.fireChanges();
+ if (europeWas != null) europeWas.fireChanges();
+ return true;
+ }
+ return false;
+ }
+
/**
* A unit in Europe emigrates.
*
@@ -396,14 +447,49 @@ public final class InGameController implements NetworkConstants {
|| !MigrationType.validMigrantSlot(slot)) return null;
EuropeWas europeWas = new EuropeWas(europe);
- Unit ret = null;
- if (askServer().emigrate(slot)) {
+ Unit newUnit = null;
+ if (askServer().emigrate(slot)
+ && (newUnit = europeWas.getNewUnit()) != null) {
europeWas.fireChanges();
- ret = europeWas.getNewUnit();
}
- return ret;
+ return newUnit;
}
+ /**
+ * Select all the units to emigrate from Europe. If they are all
+ * the same they can be picked automatically, but otherwise use
+ * the emigration dialog. Only to be called if the player is
+ * allowed to select the unit type (i.e. FoY or has Brewster).
+ *
+ * The server contains the count of available FoY-units, and
+ * maintains the immigration/immigrationRequired amounts, so this
+ * routine will fail harmlessly if it asks for too much.
+ *
+ * @param player The Player
that owns the unit.
+ * @param n The number of units known to be eligible to emigrate.
+ * @param fountainOfYouth True if this migration if due to a FoY.
+ */
+ private void emigration(Player player, int n, boolean fountainOfYouth) {
+ final Europe europe = player.getEurope();
+ if (europe == null) return;
+
+ for (; n > 0 || player.checkEmigrate() ; n--) {
+ if (!allSame(europe.getRecruitables())) {
+ final int nf = n;
+ gui.showEmigrationDialog(player, fountainOfYouth,
+ (Integer value) -> { // Value is a valid slot
+ emigrate(player,
+ Europe.MigrationType.convertToMigrantSlot(value),
+ nf-1, fountainOfYouth);
+ });
+ return;
+ }
+ Unit u = askEmigrate(europe, Europe.MigrationType.getDefaultSlot());
+ if (u == null) break; // Give up on failure, try again next turn
+ player.addModelMessage(player.getEmigrationMessage(u));
+ }
+ }
+
/**
* Load some goods onto a carrier.
*
@@ -439,10 +525,12 @@ public final class InGameController implements NetworkConstants {
// Try to purchase.
int oldAmount = carrier.getGoodsContainer().getGoodsCount(type);
- boolean ret = askServer().loadGoods(loc, type, amount, carrier)
- && carrier.getGoodsContainer().getGoodsCount(type) != oldAmount;
- if (ret && marketWas != null) marketWas.fireChanges(type, amount);
- return ret;
+ if (askServer().loadGoods(loc, type, amount, carrier)
+ && carrier.getGoodsContainer().getGoodsCount(type) != oldAmount) {
+ if (marketWas != null) marketWas.fireChanges(type, amount);
+ return true;
+ }
+ return false;
}
/**
@@ -473,10 +561,12 @@ public final class InGameController implements NetworkConstants {
MarketWas marketWas = (market != null) ? new MarketWas(player) : null;
int oldAmount = carrier.getGoodsContainer().getGoodsCount(type);
- boolean ret = askServer().unloadGoods(type, amount, carrier)
- && carrier.getGoodsContainer().getGoodsCount(type) != oldAmount;
- if (ret && marketWas != null) marketWas.fireChanges(type, -amount);
- return ret;
+ if (askServer().unloadGoods(type, amount, carrier)
+ && carrier.getGoodsContainer().getGoodsCount(type) != oldAmount) {
+ if (marketWas != null) marketWas.fireChanges(type, -amount);
+ return true;
+ }
+ return false;
}
@@ -493,8 +583,9 @@ public final class InGameController implements NetworkConstants {
final String gid = Integer.toHexString(game.getUUID().hashCode());
final Turn turn = game.getTurn();
return (/* player.getName() + "_" */ gid
- + "_" + Messages.message(player.getNationName())
- + "_" + turn.getSaveGameSuffix())
+ + "_" + Messages.message(player.getNationLabel())
+ + "_" + turn.getSaveGameSuffix()
+ + "." + FreeCol.FREECOL_SAVE_EXTENSION)
.replaceAll(" ", "_");
}
@@ -512,10 +603,10 @@ public final class InGameController implements NetworkConstants {
final String prefix = options.getText(ClientOptions.AUTO_SAVE_PREFIX);
final String lastTurnName = prefix + "-"
+ options.getText(ClientOptions.LAST_TURN_NAME)
- + FreeCol.FREECOL_SAVE_EXTENSION;
+ + "." + FreeCol.FREECOL_SAVE_EXTENSION;
final String beforeLastTurnName = prefix + "-"
+ options.getText(ClientOptions.BEFORE_LAST_TURN_NAME)
- + FreeCol.FREECOL_SAVE_EXTENSION;
+ + "." + FreeCol.FREECOL_SAVE_EXTENSION;
File autoSaveDir = FreeColDirectories.getAutosaveDirectory();
File lastTurnFile = new File(autoSaveDir, lastTurnName);
File beforeLastTurnFile = new File(autoSaveDir, beforeLastTurnName);
@@ -530,8 +621,7 @@ public final class InGameController implements NetworkConstants {
int saveGamePeriod = options.getInteger(ClientOptions.AUTOSAVE_PERIOD);
int turnNumber = game.getTurn().getNumber();
if (saveGamePeriod >= 1 && turnNumber % saveGamePeriod == 0) {
- String fileName = prefix + "-" + getSaveGameString(game)
- + FreeCol.FREECOL_SAVE_EXTENSION;
+ String fileName = prefix + "-" + getSaveGameString(game);
saveGame(new File(autoSaveDir, fileName));
}
}
@@ -558,6 +648,7 @@ public final class InGameController implements NetworkConstants {
return result;
}
+
// Utilities for message handling.
/**
@@ -664,34 +755,16 @@ public final class InGameController implements NetworkConstants {
Runnable uiTask;
if (endOfTurn) {
turnReportMessages.addAll(messages);
- uiTask = new Runnable() {
- @Override
- public void run() {
- displayTurnReportMessages();
- }
- };
+ uiTask = () -> { displayTurnReportMessages(); };
} else {
- uiTask = new Runnable() {
- @Override
- public void run() {
- gui.showModelMessages(messages);
- }
- };
- }
- updateControls();
- if (SwingUtilities.isEventDispatchThread()) {
- uiTask.run();
- } else {
- try {
- SwingUtilities.invokeAndWait(uiTask);
- } catch (InterruptedException|InvocationTargetException ex) {
- logger.log(Level.WARNING, "Message display", ex);
- }
+ uiTask = () -> { gui.showModelMessages(messages); };
}
+ gui.invokeNowOrWait(uiTask);
}
return !messages.isEmpty();
}
+
// Utilities to handle the transitions between the active-unit,
// execute-orders and end-turn states.
@@ -762,12 +835,16 @@ public final class InGameController implements NetworkConstants {
*/
private boolean doEndTurn(boolean showDialog) {
if (showDialog) {
- ListUnit
.
+ * @param defender The defending Unit
.
+ * @param attackerTile The Tile
the attack originates from.
+ * @param defenderTile The Tile
the defence takes place on.
+ * @param success True if the attack succeeds.
+ */
+ public void animateAttack(Unit attacker, Unit defender,
+ Tile attackerTile, Tile defenderTile,
+ boolean success) {
+ // Note: we used to focus the map on the unit even when
+ // animation is off as long as the center-active-unit option
+ // was set. However IR#115 requested that if animation is off
+ // that we display nothing so as to speed up the other player
+ // moves as much as possible.
+ if (freeColClient.getAnimationSpeed(attacker.getOwner()) > 0) {
+ gui.animateUnitAttack(attacker, defender,
+ attackerTile, defenderTile, success);
+ }
+ gui.refresh();
+ }
+
+ /**
+ * Animate a move.
+ *
+ * Called from IGIH.animateMove.
+ *
+ * @param unit The Unit
that moves.
+ * @param oldTile The Tile
the move begins at.
+ * @param newTile The Tile
the move ends at.
+ */
+ public void animateMove(Unit unit, Tile oldTile, Tile newTile) {
+ // Note: we used to focus the map on the unit even when
+ // animation is off as long as the center-active-unit option
+ // was set. However IR#115 requested that if animation is off
+ // that we display nothing so as to speed up the other player
+ // moves as much as possible.
+ if (freeColClient.getAnimationSpeed(unit.getOwner()) > 0) {
+ gui.animateUnitMove(unit, oldTile, newTile);
+ } else if (freeColClient.getMyPlayer().owns(unit)) {
+ gui.requireFocus(newTile);
+ }
+ gui.refresh();
+ }
+
/**
* Assigns a student to a teacher.
*
@@ -2589,13 +2635,16 @@ public final class InGameController implements NetworkConstants {
|| !student.canBeStudent(teacher)
|| teacher.getColony() == null
|| student.getColony() != teacher.getColony()
- || !teacher.getColony().canTrain(teacher)) {
+ || !teacher.getColony().canTrain(teacher))
return false;
- }
UnitWas unitWas = new UnitWas(student);
- boolean ret = askServer().assignTeacher(student, teacher);
- unitWas.fireChanges();
+ boolean ret = askServer().assignTeacher(student, teacher)
+ && student.getTeacher() == teacher;
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -2614,9 +2663,10 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askAssignTradeRoute(unit, tradeRoute);
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -2633,26 +2683,12 @@ public final class InGameController implements NetworkConstants {
public boolean boardShip(Unit unit, Unit carrier) {
if (!requireOurTurn() || unit == null || unit.isCarrier()
|| carrier == null || !carrier.canCarryUnits()
- || !Map.isSameLocation(unit.getLocation(), carrier.getLocation())
- ) return false;
+ || !unit.isAtLocation(carrier.getLocation())) return false;
- // Proceed to board
- ColonyWas colonyWas = (unit.getColony() != null)
- ? new ColonyWas(unit.getColony()) : null;
- EuropeWas europeWas = (unit.isInEurope())
- ? new EuropeWas(unit.getOwner().getEurope()) : null;
- UnitWas unitWas = new UnitWas(unit);
- boolean ret = askServer().embark(unit, carrier, null)
- && unit.getLocation() == carrier;
+ boolean ret = askEmbark(unit, carrier);
if (ret) {
- freeColClient.getSoundController()
- .playSound("sound.event.loadCargo");
+ updateGUI(null);
}
- unitWas.fireChanges();
- if (colonyWas != null) colonyWas.fireChanges();
- if (europeWas != null) europeWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
return ret;
}
@@ -2669,7 +2705,7 @@ public final class InGameController implements NetworkConstants {
// Check unit, which must be on the map and able to build.
if (unit == null) return false;
- Tile tile = unit.getTile();
+ final Tile tile = unit.getTile();
if (tile == null) return false;
if (!unit.canBuildColony()) {
gui.showInformationMessage(unit, StringTemplate
@@ -2679,10 +2715,11 @@ public final class InGameController implements NetworkConstants {
}
// Join existing colony if present
- Colony colony = tile.getColony();
+ final Colony colony = tile.getColony();
if (colony != null) {
askServer().joinColony(unit, colony);
- gui.showColonyPanel(colony, unit);
+ updateGUI(null);
+ colonyPanel(colony, unit);
return false;
}
@@ -2703,7 +2740,7 @@ public final class InGameController implements NetworkConstants {
.getBoolean(ClientOptions.SHOW_COLONY_WARNINGS)) {
StringTemplate warnings = tile.getBuildColonyWarnings(unit);
if (!warnings.getReplacements().isEmpty()
- && !gui.confirm(true, tile, warnings,
+ && !gui.confirm(tile, warnings,
unit, "buildColony.yes", "buildColony.no")) {
return false;
}
@@ -2717,25 +2754,25 @@ public final class InGameController implements NetworkConstants {
// Only native owners that we can steal, buy from, or use a
// bonus center tile exception should be possible by this point.
UnitWas unitWas = new UnitWas(unit);
- boolean ret = (tile.getOwner() == null
- || player.owns(tile)
- || player.canClaimToFoundSettlement(tile))
- && askClaimTile(player, tile, unit, player.getLandPrice(tile));
-
- ret = ret && askServer().buildColony(name, unit)
- && tile.hasSettlement();
+ boolean ret = player.owns(tile);
+ if (!ret) {
+ ret = askClaimTile(player, tile, unit, player.getLandPrice(tile));
+ if (!ret) NameCache.putSettlementName(player, name);
+ }
if (ret) {
- player.invalidateCanSeeTiles();
- gui.setActiveUnit(null);
- gui.setSelectedTile(tile, false);
- freeColClient.getSoundController()
- .playSound("sound.event.buildingComplete");
- // Check units present for treasure cash-in as they are now
- // at a colony.
- for (Unit u : tile.getUnitList()) checkCashInTreasureTrain(u);
+ ret = askServer().buildColony(name, unit)
+ && tile.hasSettlement();
+ if (ret) {
+ sound("sound.event.buildingComplete");
+ player.invalidateCanSeeTiles();
+ unitWas.fireChanges();
+ // Check units present for treasure cash-in as they are now
+ // at a colony.
+ for (Unit u : tile.getUnitList()) checkCashInTreasureTrain(u);
+ colonyPanel((Colony)tile.getSettlement(), unit);
+ }
+ updateGUI(null);
}
- unitWas.fireChanges();
- updateControls();
return ret;
}
@@ -2756,21 +2793,32 @@ public final class InGameController implements NetworkConstants {
|| !carrier.isInEurope()
|| !freeColClient.getMyPlayer().owns(carrier)) return false;
- Europe europe = carrier.getOwner().getEurope();
+ final Europe europe = carrier.getOwner().getEurope();
EuropeWas europeWas = new EuropeWas(europe);
UnitWas unitWas = new UnitWas(carrier);
boolean ret = askLoadGoods(europe, type, amount, carrier);
if (ret) {
- freeColClient.getSoundController()
- .playSound("sound.event.loadCargo");
- displayModelMessages(false, false);
+ sound("sound.event.loadCargo");
+ europeWas.fireChanges();
+ unitWas.fireChanges();
+ updateGUI(null);
}
- europeWas.fireChanges();
- unitWas.fireChanges();
- updateControls();
return ret;
}
+ /**
+ * Chat with another player.
+ *
+ * Called from IGIH.chat.
+ *
+ * @param player The Player
to chat with.
+ * @param message What to say.
+ * @param pri If true, the message is private.
+ */
+ public void chat(Player player, String message, boolean pri) {
+ gui.displayChatMessage(player, message, pri);
+ }
+
/**
* Changes the state of this Unit
.
*
@@ -2781,8 +2829,9 @@ public final class InGameController implements NetworkConstants {
* @return True if the state was changed.
*/
public boolean changeState(Unit unit, UnitState state) {
- if (!requireOurTurn() || unit == null
- || !unit.checkSetState(state)) return false;
+ if (!requireOurTurn() || unit == null) return false;
+ if (unit.getState() == state) return true;
+ if (!unit.checkSetState(state)) return false;
// Check if this is a hostile fortification, and give the player
// a chance to confirm.
@@ -2793,19 +2842,19 @@ public final class InGameController implements NetworkConstants {
if (tile != null && tile.getOwningSettlement() != null) {
Player enemy = tile.getOwningSettlement().getOwner();
if (player != enemy
- && player.getStance(enemy) != Stance.ALLIANCE) {
- if (!gui.confirmHostileAction(unit, tile))
- return false; // Aborted
- }
+ && player.getStance(enemy) != Stance.ALLIANCE
+ && !gui.confirmHostileAction(unit, tile))
+ return false; // Aborted
}
}
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().changeState(unit, state)
&& unit.getState() == state;
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -2819,7 +2868,7 @@ public final class InGameController implements NetworkConstants {
* @return True if the improvement was changed.
*/
public boolean changeWorkImprovementType(Unit unit,
- TileImprovementType improvementType) {
+ TileImprovementType improvementType) {
if (!requireOurTurn() || unit == null || improvementType == null
|| !unit.hasTile()
|| !unit.checkSetState(UnitState.IMPROVING)
@@ -2827,19 +2876,20 @@ public final class InGameController implements NetworkConstants {
// May need to claim the tile first
final Player player = freeColClient.getMyPlayer();
+ final Tile tile = unit.getTile();
UnitWas unitWas = new UnitWas(unit);
- boolean ret = true;
- Tile tile = unit.getTile();
- if (!player.owns(tile)) {
- if (!askClaimTile(player, tile, unit,
- player.getLandPrice(tile))) ret = false;
+ boolean ret = player.owns(tile)
+ || askClaimTile(player, tile, unit, player.getLandPrice(tile));
+ if (ret) {
+ ret = askServer()
+ .changeWorkImprovementType(unit, improvementType)
+ && unit.getWorkImprovement() != null
+ && unit.getWorkImprovement().getType() == improvementType;
+ if (ret) {
+ unitWas.fireChanges();
+ }
+ updateGUI(null);
}
-
- ret = ret && askServer().changeWorkImprovementType(unit,
- improvementType);
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(tile);
return ret;
}
@@ -2858,9 +2908,10 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().changeWorkType(unit, workType)
&& unit.getWorkType() == workType;
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -2875,11 +2926,10 @@ public final class InGameController implements NetworkConstants {
*/
public boolean checkCashInTreasureTrain(Unit unit) {
if (!requireOurTurn() || unit == null
- || !unit.canCarryTreasure() || !unit.canCashInTreasureTrain()) {
+ || !unit.canCarryTreasure() || !unit.canCashInTreasureTrain())
return false; // Fail quickly if just not a candidate.
- }
- Tile tile = unit.getTile();
+ final Tile tile = unit.getTile();
final Europe europe = unit.getOwner().getEurope();
if (europe == null || unit.isInEurope()) {
;// No need to check for transport.
@@ -2894,7 +2944,7 @@ public final class InGameController implements NetworkConstants {
template = StringTemplate.template("cashInTreasureTrain.pay")
.addAmount("%fee%", percent);
}
- if (!gui.confirm(true, unit.getTile(), template, unit,
+ if (!gui.confirm(unit.getTile(), template, unit,
"accept", "reject")) return false;
}
@@ -2902,12 +2952,10 @@ public final class InGameController implements NetworkConstants {
boolean ret = askServer().cashInTreasureTrain(unit)
&& unit.isDisposed();
if (ret) {
- freeColClient.getSoundController()
- .playSound("sound.event.cashInTreasureTrain");
+ sound("sound.event.cashInTreasureTrain");
+ unitWas.fireChanges();
+ updateGUI(tile);
}
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(tile);
return ret;
}
@@ -2929,6 +2977,19 @@ public final class InGameController implements NetworkConstants {
return askServer().chooseFoundingFather(ffs, ff);
}
+ /**
+ * Choose a founding father from an offered list.
+ *
+ * Called from IGIH.chooseFoundingFather.
+ *
+ * @param ffs A list of FoundingFather
s to choose from.
+ */
+ public void chooseFoundingFather(ListUnit
to clear the destination for.
* @return True if the unit has no destination.
@@ -2970,8 +3033,10 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askClearGotoOrders(unit);
- unitWas.fireChanges();
- updateControls();
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -2988,7 +3053,7 @@ public final class InGameController implements NetworkConstants {
if (!requireOurTurn() || unit == null) return false;
if (unit.getState() == UnitState.IMPROVING
- && !gui.confirm(true, unit.getTile(), StringTemplate
+ && !gui.confirm(unit.getTile(), StringTemplate
.template("clearOrders.text")
.addAmount("%turns%", unit.getWorkTurnsLeft()),
unit, "ok", "cancel")) {
@@ -2999,8 +3064,10 @@ public final class InGameController implements NetworkConstants {
boolean ret = askClearGotoOrders(unit)
&& (unit.getState() == UnitState.ACTIVE
|| askServer().changeState(unit, UnitState.ACTIVE));
- unitWas.fireChanges();
- updateControls();
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -3026,8 +3093,8 @@ public final class InGameController implements NetworkConstants {
return false;
}
- Tile tile = (gui.isShowingSubPanel()) ? null : unit.getTile();
- if (!gui.confirm(true, tile, StringTemplate
+ final Tile tile = (gui.isShowingSubPanel()) ? null : unit.getTile();
+ if (!gui.confirm(tile, StringTemplate
.template("clearSpeciality.areYouSure")
.addStringTemplate("%oldUnit%",
unit.getLabel(Unit.UnitLabelType.NATIONAL))
@@ -3042,12 +3109,22 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().clearSpeciality(unit)
&& unit.getType() == newType;
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
+ if (ret) {
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
+ /**
+ * Close any open GUI menus.
+ *
+ * Called from IGIH.closeMenus.
+ */
+ public void closeMenus() {
+ gui.closeMenus();
+ }
+
/**
* Declares independence for the home country.
*
@@ -3057,7 +3134,11 @@ public final class InGameController implements NetworkConstants {
*/
public boolean declareIndependence() {
if (!requireOurTurn()) return false;
+
final Player player = freeColClient.getMyPlayer();
+ if (player.getNewLandName() == null) {
+ return false; // Can only happen in debug mode.
+ }
// Check for adequate support.
StringTemplate declare = player.checkDeclareIndependence();
@@ -3065,10 +3146,6 @@ public final class InGameController implements NetworkConstants {
gui.showInformationMessage(declare);
return false;
}
- if (player.getNewLandName() == null) {
- // Can only happen in debug mode.
- return false;
- }
// Confirm intention, and collect nation+country names.
ListPlayer
that owns the unit.
* @param slot The slot to emigrate from, [0..RECRUIT_COUNT].
- * @return True if a unit emigrated.
+ * @param n The number of remaining units known to be eligible to migrate.
+ * @param foY True if this migration is due to a fountain of youth event.
*/
- public boolean emigrate(Player player, int slot) {
+ public void emigrate(Player player, int slot, int n, boolean foY) {
if (player == null || !player.isColonial()
- || !MigrationType.validMigrantSlot(slot)) return false;
+ || !MigrationType.validMigrantSlot(slot)) return;
- return askEmigrate(player.getEurope(), slot) != null;
- }
-
- /**
- * Loop through selecting (or not when all are the same) a new unit
- * to emigrate from Europe. Only to be called if the player is allowed
- * to select the unit type (i.e. FoY or has Brewster).
- *
- * Called from GUI.showEmigrationDialog
- *
- * @param player The Player
that owns the unit.
- * @param n The number of units known to be eligible to emigrate.
- * @param fountainOfYouth True if this migration if due to a FoY.
- */
- public void emigrationLoop(Player player, int n, boolean fountainOfYouth) {
- final Europe europe = player.getEurope();
- if (europe == null) return;
-
- for (;;) {
- if (n == 0 && player.checkEmigrate()) n = 1;
- if (n <= 0) return;
- if (!allSame(europe.getRecruitables())) break;
- Unit u = askEmigrate(europe,
- Europe.MigrationType.getDefaultSlot());
- if (u != null) {
- player.addModelMessage(player.getEmigrationMessage(u));
- }
- n--;
+ if (askEmigrate(player.getEurope(), slot) != null) {
+ emigration(player, n, foY);
}
- gui.showEmigrationDialog(player, n, fountainOfYouth);
}
-
+
/**
* End the turn command.
*
@@ -3316,14 +3369,30 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().equipUnitForRole(unit, role, roleCount)
&& unit.getRole() == role;
- if (colonyWas != null) colonyWas.fireChanges();
- if (europeWas != null) europeWas.fireChanges();
- if (marketWas != null) marketWas.fireChanges(req);
- unitWas.fireChanges();
- updateControls();
+ if (ret) {
+ if (colonyWas != null) colonyWas.fireChanges();
+ if (europeWas != null) europeWas.fireChanges();
+ if (marketWas != null) marketWas.fireChanges(req);
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
+ /**
+ * Display an error.
+ *
+ * Called from IGIH.error.
+ *
+ * @param messageId The i18n-keyname of the error message to display.
+ * @param message An alternative (possibly non-i18n) message to
+ * display if the resource specified by messageId
+ * is unavailable.
+ */
+ public void error(String messageId, String message) {
+ gui.showErrorMessage(messageId, message);
+ }
+
/**
* Execute goto orders command.
*
@@ -3355,18 +3424,45 @@ public final class InGameController implements NetworkConstants {
if (player == null || player == null || player == other
|| tile == null) return false;
- return askServer().firstContact(player, other, tile, result);
+ boolean ret = askServer().firstContact(player, other, tile, result);
+ if (ret) {
+ updateGUI(null);
+ }
+ return ret;
}
/**
- * Retrieves client statistics.
+ * A player makes first contact with a native player.
*
- * Called from StatisticsPanel
+ * Called from IGIH.firstContact.
*
- * @return A Map
containing the client statistics.
+ * @param player The Player
making contact.
+ * @param other The native Player
being contacted.
+ * @param tile An optional Tile
to offer the player if
+ * they have made a first landing.
+ * @param n The number of settlements claimed by the native player.
*/
- public java.util.MapUnit
that is looting.
+ * @param goods A list of Goods
to choose from.
+ * @param defenderId The identifier of the defender unit (may have sunk).
+ */
+ public void loot(Unit unit, ListMonarchAction
to perform.
+ * @param template A StringTemplate
describing the action.
+ * @param monarchKey A key for the monarch involved.
+ */
+ public void monarch(MonarchAction action, StringTemplate template,
+ String monarchKey) {
+ gui.showMonarchDialog(action, template, monarchKey,
+ (Boolean b) -> monarchAction(action, b));
}
/**
@@ -3740,27 +3870,25 @@ public final class InGameController implements NetworkConstants {
// Sanity check current state.
if (destination instanceof Europe) {
if (unit.isInEurope()) {
- freeColClient.getSoundController()
- .playSound("sound.event.illegalMove");
+ sound("sound.event.illegalMove");
return false;
}
} else if (destination instanceof Map) {
if (unit.hasTile() && unit.getTile().getMap() == destination) {
- freeColClient.getSoundController()
- .playSound("sound.event.illegalMove");
+ sound("sound.event.illegalMove");
return false;
}
} else if (destination instanceof Settlement) {
if (unit.hasTile()) {
- freeColClient.getSoundController()
- .playSound("sound.event.illegalMove");
+ sound("sound.event.illegalMove");
return false;
}
} else {
return false;
}
- // Autoload emigrants?
+ // Autoload?
+ boolean update = false;
if (freeColClient.getClientOptions()
.getBoolean(ClientOptions.AUTOLOAD_EMIGRANTS)
&& unit.isInEurope()) {
@@ -3768,16 +3896,18 @@ public final class InGameController implements NetworkConstants {
if (!u.isNaval()
&& u.getState() == UnitState.SENTRY
&& unit.canAdd(u)) {
- boardShip(u, unit);
+ if (askEmbark(u, unit)) update = true;
}
}
}
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().moveTo(unit, destination);
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
+ if (ret) {
+ unitWas.fireChanges();
+ update = true;
+ }
+ if (update) updateGUI(null);
return ret;
}
@@ -3794,18 +3924,29 @@ public final class InGameController implements NetworkConstants {
*/
public boolean moveUnit(Unit unit, Direction direction) {
if (!requireOurTurn() || unit == null
- || direction == null) return false;
+ || direction == null || !unit.hasTile()) return false;
+ if (!askClearGotoOrders(unit)) return false;
+
+ final int unitCount = unit.getUnitCount(),
+ goodsCount = unit.getGoodsList().size();
+ final Tile oldTile = unit.getTile();
UnitWas unitWas = new UnitWas(unit);
ColonyWas colonyWas = (unit.getColony() == null) ? null
: new ColonyWas(unit.getColony());
unit.setState(UnitState.ACTIVE);
- boolean ret = askClearGotoOrders(unit)
- && moveDirection(unit, direction, true);
- unitWas.fireChanges();
- if (colonyWas != null) colonyWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
+ moveDirection(unit, direction, true);
+ boolean ret = unit.getTile() != oldTile
+ || unitWas.fireChanges();
+ if (ret) {
+ if (colonyWas != null) colonyWas.fireChanges();
+ updateGUI(null);
+ if (!unit.couldMove() && unit.hasTile()) {
+ // Show colony panel if unit out of moves
+ Colony colony = unit.getTile().getColony();
+ if (colony != null) colonyPanel(colony, unit);
+ }
+ }
return ret;
}
@@ -3820,13 +3961,13 @@ public final class InGameController implements NetworkConstants {
public boolean moveTileCursor(Direction direction) {
if (direction == null) return false;
- Tile tile = gui.getSelectedTile();
+ final Tile tile = gui.getSelectedTile();
if (tile == null) return false;
- Tile newTile = tile.getNeighbourOrNull(direction);
+ final Tile newTile = tile.getNeighbourOrNull(direction);
if (newTile == null) return false;
- gui.setSelectedTile(newTile, false);
+ gui.setSelectedTile(newTile);
return true;
}
@@ -3853,7 +3994,7 @@ public final class InGameController implements NetworkConstants {
null);
// Add tutorial message.
- String key = FreeColActionUI.getHumanKeyStrokeText(freeColClient
+ final String key = FreeColActionUI.getHumanKeyStrokeText(freeColClient
.getActionManager().getFreeColAction("buildColonyAction")
.getAccelerator());
player.addModelMessage(new ModelMessage(ModelMessage.MessageType.TUTORIAL,
@@ -3861,14 +4002,14 @@ public final class InGameController implements NetworkConstants {
.addName("%colonyKey%", key)
.add("%colonyMenuItem%", "buildColonyAction.name")
.add("%ordersMenuItem%", "menuBar.orders"));
- displayModelMessages(false, false);
+ displayModelMessages(false);
return true;
}
/**
* The player names a new region.
*
- * Called from IGIH.newRegionName, GUI.showNameNewRegionDialog
+ * Called from newRegionName, GUI.showNameNewRegionDialog
*
* @param tile The Tile
within the region.
* @param unit The Unit
that has discovered the region.
@@ -3886,16 +4027,25 @@ public final class InGameController implements NetworkConstants {
/**
* Ask the player to name the new land.
*
+ * Called from IGIH.newLandName.
+ *
* @param defaultName The default name to use.
* @param unit The Unit
that has landed.
*/
public void newLandName(String defaultName, Unit unit) {
- gui.showNameNewLandDialog("newLand.text", defaultName, unit);
+ gui.showNamingDialog(
+ StringTemplate.key("newLand.text"), defaultName, unit,
+ (String name) -> {
+ if (name == null || name.isEmpty()) name = defaultName;
+ nameNewLand(unit, name);
+ });
}
/**
* Ask the player to name a new region.
*
+ * Called from IGIH.newRegionName.
+ *
* @param region The Region
to name.
* @param defaultName The default name to use.
* @param tile The Tile
the unit landed at.
@@ -3910,10 +4060,14 @@ public final class InGameController implements NetworkConstants {
}
nameNewRegion(tile, unit, region, defaultName);
} else {
- gui.showNameNewRegionDialog(StringTemplate
- .template("nameRegion.text")
- .addStringTemplate("%type%", region.getLabel()),
- defaultName, unit, tile, region);
+ gui.showNamingDialog(
+ StringTemplate.template("nameRegion.text")
+ .addStringTemplate("%type%", region.getLabel()),
+ defaultName, unit,
+ (String name) -> {
+ if (name == null || name.isEmpty()) name = defaultName;
+ nameNewRegion(tile, unit, region, name);
+ });
}
}
@@ -3939,12 +4093,9 @@ public final class InGameController implements NetworkConstants {
final boolean alert = freeColClient.getClientOptions()
.getBoolean(ClientOptions.AUDIO_ALERTS);
- if (alert) {
- freeColClient.getSoundController()
- .playSound("sound.event.alertSound");
- }
+ if (alert) sound("sound.event.alertSound");
- Turn currTurn = game.getTurn();
+ final Turn currTurn = game.getTurn();
if (currTurn.isFirstSeasonTurn()) {
player.addModelMessage(new ModelMessage(MessageType.WARNING,
"twoTurnsPerYear", player)
@@ -3964,7 +4115,7 @@ public final class InGameController implements NetworkConstants {
public boolean nextActiveUnit() {
if (!requireOurTurn()) return false;
- updateActiveUnit(null);
+ updateGUI(null);
return true;
}
@@ -4003,14 +4154,14 @@ public final class InGameController implements NetworkConstants {
return false;
}
- boolean ret = gui.confirm(true, null, StringTemplate
- .template("payArrears.text")
- .addAmount("%amount%", arrears),
- gui.createGoodsImageIcon(type),
- "ok", "cancel")
- && askServer().payArrears(type)
- && player.canTrade(type);
- updateControls();
+ StringTemplate t = StringTemplate.template("payArrears.text")
+ .addAmount("%amount%", arrears);
+ if (!gui.confirm(null, t, type, "ok", "cancel")) return false;
+
+ boolean ret = askServer().payArrears(type) && player.canTrade(type);
+ if (ret) {
+ updateGUI(null);
+ }
return ret;
}
@@ -4037,20 +4188,18 @@ public final class InGameController implements NetworkConstants {
return false;
}
- int price = colony.getPriceForBuilding();
- if (!gui.confirm(true, null, StringTemplate
- .template("payForBuilding.text")
- .addAmount("%amount%", price),
- gui.createSettlementImageIcon(colony),
- "yes", "no")) {
- return false;
- }
+ final int price = colony.getPriceForBuilding();
+ StringTemplate t = StringTemplate.template("payForBuilding.text")
+ .addAmount("%amount%", price);
+ if (!gui.confirm(null, t, colony, "yes", "no")) return false;
ColonyWas colonyWas = new ColonyWas(colony);
boolean ret = askServer().payForBuilding(colony)
&& colony.getPriceForBuilding() == 0;
- colonyWas.fireChanges();
- updateControls();
+ if (ret) {
+ colonyWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -4073,9 +4222,11 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().putOutsideColony(unit)
&& unit.getLocation() == colony.getTile();
- colonyWas.fireChanges();
- unitWas.fireChanges();
- updateControls();
+ if (ret) {
+ colonyWas.fireChanges();
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -4121,11 +4272,54 @@ public final class InGameController implements NetworkConstants {
if (newUnit != null) {
player.setNextActiveUnit(newUnit);
gui.setActiveUnit(newUnit);
- updateControls();
+ updateGUI(null);
}
return newUnit != null;
}
+ /**
+ * Remove game objects.
+ *
+ * Called from IGIH.remove().
+ *
+ * @param objects A list of FreeColGameObject
s to remove.
+ */
+ public void remove(ListNameable
.
*
@@ -4144,7 +4338,7 @@ public final class InGameController implements NetworkConstants {
String name = null;
if (object instanceof Colony) {
Colony colony = (Colony) object;
- name = gui.getInput(true, colony.getTile(),
+ name = gui.getInput(colony.getTile(),
StringTemplate.key("renameColony.text"),
colony.getName(), "rename", "cancel");
if (name == null) { // User cancelled
@@ -4163,7 +4357,7 @@ public final class InGameController implements NetworkConstants {
}
} else if (object instanceof Unit) {
Unit unit = (Unit) object;
- name = gui.getInput(true, unit.getTile(),
+ name = gui.getInput(unit.getTile(),
StringTemplate.key("renameUnit.text"),
unit.getName(), "rename", "cancel");
if (name == null) return false; // User cancelled
@@ -4193,14 +4387,13 @@ public final class InGameController implements NetworkConstants {
File file = gui.showSaveDialog(FreeColDirectories.getSaveDirectory(),
fileName);
if (file == null) return false;
-
final boolean confirm = freeColClient.getClientOptions()
.getBoolean(ClientOptions.CONFIRM_SAVE_OVERWRITE);
if (!confirm
|| !file.exists()
|| gui.confirm("saveConfirmationDialog.areYouSure.text",
"ok", "cancel")) {
- FreeColDirectories.setSaveDirectory(file.getParentFile());
+ FreeColDirectories.setSavegameFile(file.getPath());
return saveGame(file);
}
return false;
@@ -4239,10 +4432,9 @@ public final class InGameController implements NetworkConstants {
moveToDestination(unit, null);
}
}
+ unitWas.fireChanges();
+ updateGUI(null);
}
- unitWas.fireChanges();
- updateControls();
- updateActiveUnit(null);
return ret;
}
@@ -4265,16 +4457,13 @@ public final class InGameController implements NetworkConstants {
Europe europe = player.getEurope();
EuropeWas europeWas = new EuropeWas(europe);
UnitWas unitWas = new UnitWas(carrier);
- boolean ret = askUnloadGoods(goods.getType(), goods.getAmount(),
- carrier);
+ boolean ret = askUnloadGoods(goods.getType(), goods.getAmount(), carrier);
if (ret) {
- freeColClient.getSoundController()
- .playSound("sound.event.sellCargo");
- displayModelMessages(false, false);
+ sound("sound.event.sellCargo");
+ europeWas.fireChanges();
+ unitWas.fireChanges();
+ updateGUI(null);
}
- europeWas.fireChanges();
- unitWas.fireChanges();
- updateControls();
return ret;
}
@@ -4308,7 +4497,10 @@ public final class InGameController implements NetworkConstants {
ColonyWas colonyWas = new ColonyWas(colony);
boolean ret = askServer().setBuildQueue(colony, buildQueue);
- colonyWas.fireChanges();
+ if (ret) {
+ colonyWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
@@ -4329,6 +4521,7 @@ public final class InGameController implements NetworkConstants {
final Game game = freeColClient.getGame();
game.setCurrentPlayer(player);
+
if (freeColClient.getMyPlayer().equals(player)) {
if (FreeColDebugger.isInDebugMode(FreeColDebugger.DebugMode.DESYNC)
&& DebugUtils.checkDesyncAction(freeColClient)) {
@@ -4336,49 +4529,35 @@ public final class InGameController implements NetworkConstants {
return false;
}
+ // Save the game (if it isn't newly loaded)
+ if (freeColClient.getFreeColServer() != null
+ && game.getTurn().getNumber() > 0) autoSaveGame();
+
// Get turn report out quickly before more message display occurs.
player.removeDisplayedModelMessages();
displayModelMessages(true, true);
player.invalidateCanSeeTiles();
- // Save the game (if it isn't newly loaded)
- if (freeColClient.getFreeColServer() != null
- && game.getTurn().getNumber() > 0) autoSaveGame();
-
// Check for emigration.
Europe europe = player.getEurope();
if (player.hasAbility(Ability.SELECT_RECRUIT)) {
- emigrationLoop(player, 0, false);
+ emigration(player, 0, false);
} else {
while (player.checkEmigrate()) {
askEmigrate(europe,
- Europe.MigrationType.getUnspecificSlot());
+ Europe.MigrationType.getUnspecificSlot());
}
}
- try {
- ListUnit
to skip.
- * @return True if the active unit is not null.
+ * @param tile The Tile
to find the colony on.
+ * @param recover A Runnable
to restore the normal
+ * player view of the tile when the spying colony panel is closed.
*/
- public boolean skipUnit(Unit unit) {
- if (!requireOurTurn() || unit == null) return false;
-
- if (unit.getState() == UnitState.SKIPPED) return true;
-
- unit.setState(UnitState.SKIPPED);
- updateActiveUnit(null);
- return true;
+ public void spyColony(Tile tile, Runnable recover) {
+ gui.showSpyColonyPanel(tile, recover);
}
-
+
/**
* Trains a unit of a specified type in Europe.
*
@@ -4533,23 +4705,21 @@ public final class InGameController implements NetworkConstants {
if (!requireOurTurn() || unitType == null) return false;
final Player player = freeColClient.getMyPlayer();
- Europe europe = player.getEurope();
+ final Europe europe = player.getEurope();
if (!player.checkGold(europe.getUnitPrice(unitType))) {
gui.showInformationMessage("info.notEnoughGold");
return false;
}
EuropeWas europeWas = new EuropeWas(europe);
- boolean ret = false;
- if (askServer().trainUnitInEurope(unitType)) {
- Unit newUnit = europeWas.getNewUnit();
+ Unit newUnit = null;
+ boolean ret = askServer().trainUnitInEurope(unitType)
+ && (newUnit = europeWas.getNewUnit()) != null;
+ if (ret) {
europeWas.fireChanges();
- if (newUnit != null) {
- player.setNextActiveUnit(newUnit);
- gui.setActiveUnit(newUnit);
- ret = true;
- }
- updateControls();
+ player.setNextActiveUnit(newUnit);
+ gui.setActiveUnit(newUnit);
+ updateGUI(null);
}
return ret;
}
@@ -4559,7 +4729,7 @@ public final class InGameController implements NetworkConstants {
*
* Called from UnloadAction, UnitLabel
*
- * @param unit The Unit that is dumping.
+ * @param unit The Unit
that is dumping.
* @return True if the unit unloaded.
*/
public boolean unload(Unit unit) {
@@ -4567,7 +4737,6 @@ public final class InGameController implements NetworkConstants {
|| !unit.isCarrier()) return false;
boolean ret = true;
- boolean inEurope = unit.isInEurope();
Colony colony = unit.getColony();
if (colony != null) { // In colony, unload units and goods.
for (Unit u : unit.getUnitList()) {
@@ -4584,7 +4753,10 @@ public final class InGameController implements NetworkConstants {
}
}
if (unit.hasGoodsCargo()) { // Goods left here must be dumped.
- gui.showDumpCargoDialog(unit);
+ gui.showDumpCargoDialog(unit,
+ (List goodsList) -> {
+ for (Goods g : goodsList) unloadCargo(g, true);
+ });
return false;
}
} else { // Dump goods, units dislike jumping overboard
@@ -4603,7 +4775,7 @@ public final class InGameController implements NetworkConstants {
* Called from CargoPanel, ColonyPanel, EuropePanel.MarketPanel,
* GUI.showDumpCargoDialog, QuickActionMenu, unload()
*
- * @param goods The Goods to unload.
+ * @param goods The Goods
to unload.
* @param dump If true, dump the goods.
* @return True if the unload succeeds.
*/
@@ -4613,26 +4785,24 @@ public final class InGameController implements NetworkConstants {
|| !(goods.getLocation() instanceof Unit)) return false;
// Find the carrier
- Unit carrier = (Unit)goods.getLocation();
+ final Unit carrier = (Unit)goods.getLocation();
// Use Europe-specific routine if needed
if (carrier.isInEurope()) return sellGoods(goods);
// Check for a colony
- Colony colony = carrier.getColony();
+ final Colony colony = carrier.getColony();
// Unload
ColonyWas colonyWas = (colony == null) ? null : new ColonyWas(colony);
UnitWas unitWas = new UnitWas(carrier);
- boolean ret = askUnloadGoods(goods.getType(), goods.getAmount(),
- carrier);
- if (ret && !dump) {
- freeColClient.getSoundController()
- .playSound("sound.event.unloadCargo");
+ boolean ret = askUnloadGoods(goods.getType(), goods.getAmount(), carrier);
+ if (ret) {
+ if (!dump) sound("sound.event.unloadCargo");
+ if (colonyWas != null) colonyWas.fireChanges();
+ unitWas.fireChanges();
+ updateGUI(null);
}
- if (colonyWas != null) colonyWas.fireChanges();
- unitWas.fireChanges();
- updateControls();
return ret;
}
@@ -4650,16 +4820,29 @@ public final class InGameController implements NetworkConstants {
return askServer().updateTradeRoute(route);
}
+ /**
+ * The player has won, show the high scores and victory dialog.
+ *
+ * Called from IGIH.gameEnded.
+ *
+ * @param score If "true", a new high score was reached.
+ */
+ public void victory(String score) {
+ displayHighScores("true".equalsIgnoreCase(score));
+ gui.showVictoryDialog((Boolean result) -> victory(result));
+ }
+
/**
* The player has won!
*
* Called from GUI.showVictoryDialog
*
+ * @param quit If true, leave this game and start a new one.
* @return True.
*/
public boolean victory(Boolean quit) {
if (quit) {
- freeColClient.quit();
+ freeColClient.newGame(false);
} else {
askServer().continuePlaying();
}
@@ -4674,8 +4857,11 @@ public final class InGameController implements NetworkConstants {
* @return True, this can not fail.
*/
public boolean waitUnit() {
+ if (!requireOurTurn()) return false;
+
+ // Defeat the normal check for whether the current unit can move.
gui.setActiveUnit(null);
- updateActiveUnit(null);
+ updateGUI(null);
return true;
}
@@ -4713,9 +4899,11 @@ public final class InGameController implements NetworkConstants {
UnitWas unitWas = new UnitWas(unit);
boolean ret = askServer().work(unit, workLocation)
&& unit.getLocation() == workLocation;
- colonyWas.fireChanges();
- unitWas.fireChanges();
- updateControls();
+ if (ret) {
+ colonyWas.fireChanges();
+ unitWas.fireChanges();
+ updateGUI(null);
+ }
return ret;
}
}
diff --git a/src/net/sf/freecol/client/control/InGameInputHandler.java b/src/net/sf/freecol/client/control/InGameInputHandler.java
index 76c3e254e..3f95b68a4 100644
--- a/src/net/sf/freecol/client/control/InGameInputHandler.java
+++ b/src/net/sf/freecol/client/control/InGameInputHandler.java
@@ -24,12 +24,8 @@ import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.swing.SwingUtilities;
-
-import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.debug.FreeColDebugger;
-import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.DiplomaticTrade;
@@ -48,7 +44,6 @@ import net.sf.freecol.common.model.Stance;
import net.sf.freecol.common.model.Region;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Specification;
-import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TradeRoute;
import net.sf.freecol.common.model.Unit;
@@ -69,12 +64,11 @@ import org.w3c.dom.NodeList;
/**
- * Handles the network messages that arrives while in the game.
+ * Handle the network messages that arrives while in the game.
*
- * Usually delegate to the real handlers in InGameController, making
- * sure anything non-trivial that touches the GUI is doing so inside
- * the EDT. Usually this is done with SwingUtilities.invokeLater, but
- * some messages demand a response which requires invokeAndWait.
+ * Delegate to the real handlers in InGameController which are allowed
+ * to touch the GUI. Call IGC through invokeLater except for the messages
+ * that demand a response, which requires invokeAndWait.
*
* Note that the EDT often calls the controller, which queries the
* server, which results in handling the reply here, still within the
@@ -84,47 +78,23 @@ import org.w3c.dom.NodeList;
*
* ...except for the special case of the animations. These have to be
* done in series but are sometimes in the EDT (our unit moves) and
- * sometimes not (other nation unit moves). Hence the hack in the
- * local invokeAndWait wrapper.
+ * sometimes not (other nation unit moves). Hence the hack
+ * GUI.invokeNowOrWait.
*/
public final class InGameInputHandler extends InputHandler {
private static final Logger logger = Logger.getLogger(InGameInputHandler.class.getName());
// A bunch of predefined non-closure runnables.
- private final Runnable closeMenusRunnable = new Runnable() {
- @Override
- public void run() {
- getGUI().closeMenus();
- }
- };
- private final Runnable deselectActiveUnitRunnable = new Runnable() {
- @Override
- public void run() {
- getGUI().setActiveUnit(null);
- }
- };
- private final Runnable displayModelMessagesRunnable = new Runnable() {
- @Override
- public void run() {
- igc().displayModelMessages(false);
- }
- };
- private final Runnable reconnectRunnable = new Runnable() {
- @Override
- public void run() {
- igc().reconnect();
- }
- };
- private final Runnable updateMenuBarRunnable = new Runnable() {
- @Override
- public void run() {
- getGUI().updateMenuBar();
- }
- };
-
- /** The unit last appearing in an animation. */
- private Unit lastAnimatedUnit = null;
+ private final Runnable closeMenusRunnable = () -> {
+ igc().closeMenus();
+ };
+ private final Runnable displayModelMessagesRunnable = () -> {
+ igc().displayModelMessages(false);
+ };
+ private final Runnable reconnectRunnable = () -> {
+ igc().reconnect();
+ };
/**
@@ -147,45 +117,30 @@ public final class InGameInputHandler extends InputHandler {
}
/**
- * Wrapper for SwingUtilities.invokeAndWait. This has to handle the
- * case where we are already in the EDT.
+ * Shorthand to run in the EDT and wait.
*
- * @param runnable A Runnable
to run.
+ * @param runnable The Runnable
to run.
*/
private void invokeAndWait(Runnable runnable) {
- if (SwingUtilities.isEventDispatchThread()) {
- runnable.run();
- } else {
- try {
- SwingUtilities.invokeAndWait(runnable);
- } catch (Exception e) {}
- }
+ getFreeColClient().getGUI().invokeNowOrWait(runnable);
}
-
+
/**
- * Refresh the canvas.
+ * Shorthand to run in the EDT eventually.
*
- * @param focus If true, request the focus.
+ * @param runnable The Runnable
to run.
*/
- private void refreshCanvas(final boolean focus) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- getGUI().refresh();
-
- if (focus && !getGUI().isShowingSubPanel()) {
- getGUI().requestFocusInWindow();
- }
- }
- });
+ private void invokeLater(Runnable runnable) {
+ getFreeColClient().getGUI().invokeNowOrLater(runnable);
}
-
+
/**
* Get the integer value of an element attribute.
*
* @param element The Element
to query.
* @param attrib The attribute to use.
- * @return The integer value of the attribute, or MIN_INT on failure.
+ * @return The integer value of the attribute, or
+ * Integer.MIN_VALUE on failure.
*/
private static int getIntegerAttribute(Element element, String attrib) {
int n;
@@ -219,6 +174,7 @@ public final class InGameInputHandler extends InputHandler {
* Sometimes units appear which the client does not know about,
* and are passed in as the children of the parent element.
* Worse, if their location is a Unit, that unit has to be passed in too.
+ * Pull a unit out of the children by id.
*
* @param game The Game
to add the unit to.
* @param element The Element
to find a unit in.
@@ -232,7 +188,7 @@ public final class InGameInputHandler extends InputHandler {
if (e != null) {
u = new Unit(game, e);
if (u.getLocation() == null) {
- throw new IllegalStateException("Null location: " + u);
+ throw new RuntimeException("Null location: " + u);
}
}
return u;
@@ -252,7 +208,7 @@ public final class InGameInputHandler extends InputHandler {
Element reply;
String type = element.getTagName();
- logger.log(Level.FINEST, "Received message: " + type);
+ logger.log(Level.FINEST, "Received: " + type);
switch (type) {
case "disconnect":
reply = disconnect(element); break; // Inherited
@@ -325,7 +281,7 @@ public final class InGameInputHandler extends InputHandler {
final FreeColClient fcc = getFreeColClient();
if (Boolean.TRUE.toString().equals(element.getAttribute("flush"))
&& fcc.currentPlayerIsMyPlayer()) {
- SwingUtilities.invokeLater(displayModelMessagesRunnable);
+ invokeLater(displayModelMessagesRunnable);
}
return reply;
}
@@ -355,7 +311,8 @@ public final class InGameInputHandler extends InputHandler {
final String tag = e.getTagName();
if (FoundingFather.getXMLElementTagName().equals(tag)) {
- FoundingFather father = spec.getFoundingFather(FreeColObject.readId(e));
+ FoundingFather father
+ = spec.getFoundingFather(FreeColObject.readId(e));
if (father != null) player.addFather(father);
player.invalidateCanSeeTiles();// Might be coronado?
@@ -379,7 +336,7 @@ public final class InGameInputHandler extends InputHandler {
}
/**
- * Handles an "addPlayer"-message.
+ * Handle an "addPlayer"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -402,7 +359,7 @@ public final class InGameInputHandler extends InputHandler {
}
/**
- * Handles an "animateAttack"-message. This only performs animation, if
+ * Handle an "animateAttack"-message. This only performs animation, if
* required. It does not actually perform any attacks.
*
* @param element An element (root element in a DOM-parsed XML
@@ -412,8 +369,7 @@ public final class InGameInputHandler extends InputHandler {
* @return Null.
*/
private Element animateAttack(Element element) {
- FreeColClient freeColClient = getFreeColClient();
- if (freeColClient.isHeadless()) return null;
+ final FreeColClient freeColClient = getFreeColClient();
final Game game = getGame();
final Player player = freeColClient.getMyPlayer();
String str;
@@ -465,26 +421,15 @@ public final class InGameInputHandler extends InputHandler {
= Boolean.parseBoolean(element.getAttribute("success"));
// All is well, do the animation.
- // Use lastAnimatedUnit as a filter to avoid excessive refocussing.
- final boolean focus = lastAnimatedUnit != attacker;
- lastAnimatedUnit = attacker;
- invokeAndWait(new Runnable() {
- @Override
- public void run() {
- if (focus || !getGUI().onScreen(attackerTile)
- || !getGUI().onScreen(defenderTile)) {
- getGUI().setFocusImmediately(attackerTile);
- }
- getGUI().animateUnitAttack(attacker, defender,
- attackerTile, defenderTile, success);
- refreshCanvas(false);
- }
+ invokeAndWait(() -> {
+ igc().animateAttack(attacker, defender,
+ attackerTile, defenderTile, success);
});
return null;
}
/**
- * Handles an "animateMove"-message. This only performs
+ * Handle an "animateMove"-message. This only performs
* animation, if required. It does not actually change unit
* positions, which happens in an "update".
*
@@ -495,8 +440,7 @@ public final class InGameInputHandler extends InputHandler {
* @return Null.
*/
private Element animateMove(Element element) {
- FreeColClient freeColClient = getFreeColClient();
- if (freeColClient.isHeadless()) return null;
+ final FreeColClient freeColClient = getFreeColClient();
final Game game = getGame();
final Player player = freeColClient.getMyPlayer();
@@ -544,37 +488,12 @@ public final class InGameInputHandler extends InputHandler {
return null;
}
- final boolean focus = unit != lastAnimatedUnit;
- lastAnimatedUnit = unit;
- invokeAndWait(new Runnable() {
- @Override
- public void run() {
- if (getGUI().getAnimationSpeed(unit) > 0) {
- // All is well, queue the animation. Use
- // lastAnimatedUnit as a filter to avoid
- // excessive refocussing.
- if (focus || !getGUI().onScreen(oldTile)) {
- getGUI().setFocusImmediately(oldTile);
- }
- getGUI().animateUnitMove(unit, oldTile, newTile);
- refreshCanvas(false);
- } else {
- // Not animating, but if the centering
- // option is enabled at least refocus so
- // we can see the move happen.
- if (!getGUI().onScreen(oldTile)
- && getFreeColClient().getClientOptions()
- .getBoolean(ClientOptions.ALWAYS_CENTER)) {
- getGUI().setFocus(oldTile);
- }
- }
- }
- });
+ invokeAndWait(() -> { igc().animateMove(unit, oldTile, newTile); });
return null;
}
/**
- * Handles a "chat"-message.
+ * Handle a "chat"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -584,19 +503,15 @@ public final class InGameInputHandler extends InputHandler {
final Game game = getGame();
final ChatMessage chatMessage = new ChatMessage(game, element);
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- getGUI().displayChatMessage(chatMessage.getPlayer(game),
- chatMessage.getMessage(),
- chatMessage.isPrivate());
- }
- });
+ invokeLater(() -> {
+ igc().chat(chatMessage.getPlayer(game),
+ chatMessage.getMessage(), chatMessage.isPrivate());
+ });
return null;
}
/**
- * Handles an "chooseFoundingFather"-request.
+ * Handle an "chooseFoundingFather"-request.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -607,7 +522,7 @@ public final class InGameInputHandler extends InputHandler {
= new ChooseFoundingFatherMessage(getGame(), element);
final List ffs = message.getFathers();
- getGUI().showChooseFoundingFatherDialog(ffs);
+ invokeLater(() -> { igc().chooseFoundingFather(ffs); });
return null;
}
@@ -627,7 +542,7 @@ public final class InGameInputHandler extends InputHandler {
}
/**
- * Handles a "diplomacy"-request. If the message informs of an
+ * Handle a "diplomacy"-request. If the message informs of an
* acceptance or rejection then display the result and return
* null. If the message is a proposal, then ask the user about
* it and return the response with appropriate response set.
@@ -654,14 +569,9 @@ public final class InGameInputHandler extends InputHandler {
return null;
}
- invokeAndWait(new Runnable() {
- @Override
- public void run() {
- message.setAgreement(igc().diplomacy(our, other,
- agreement));
- }
+ invokeAndWait(() -> {
+ message.setAgreement(igc().diplomacy(our, other, agreement));
});
- SwingUtilities.invokeLater(updateMenuBarRunnable);
return (message.getAgreement() == null) ? null
: message.toXMLElement();
}
@@ -696,7 +606,7 @@ public final class InGameInputHandler extends InputHandler {
}
/**
- * Handles an "error"-message.
+ * Handle an "error"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -706,12 +616,7 @@ public final class InGameInputHandler extends InputHandler {
final String messageId = element.getAttribute("messageID");
final String message = element.getAttribute("message");
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- getGUI().showErrorMessage(messageId, message);
- }
- });
+ invokeLater(() -> { igc().error(messageId, message); });
return null;
}
@@ -786,9 +691,9 @@ public final class InGameInputHandler extends InputHandler {
logger.warning("firstContact with bad tile: " + tile);
return null;
}
+ final int n = message.getSettlementCount();
- getGUI().showFirstContactDialog(player, other, tile,
- message.getSettlementCount());
+ invokeLater(() -> { igc().firstContact(player, other, tile, n); });
return null;
}
@@ -800,19 +705,19 @@ public final class InGameInputHandler extends InputHandler {
* @return Null.
*/
private Element fountainOfYouth(Element element) {
- int n = getIntegerAttribute(element, "migrants");
- if (n > 0) {
- getGUI().showEmigrationDialog(getFreeColClient().getMyPlayer(),
- n, true);
- } else {
+ final int n = getIntegerAttribute(element, "migrants");
+ if (n <= 0) {
logger.warning("Invalid migrants attribute: "
+ element.getAttribute("migrants"));
+ return null;
}
+
+ invokeLater(() -> { igc().fountainOfYouth(n); });
return null;
}
/**
- * Handles a "gameEnded"-message.
+ * Handle a "gameEnded"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -824,23 +729,20 @@ public final class InGameInputHandler extends InputHandler {
final Player winner
= getGame().getFreeColGameObject(element.getAttribute("winner"),
Player.class);
- final boolean highScore
- = "true".equalsIgnoreCase(element.getAttribute("highScore"));
+ if (winner == null) {
+ logger.warning("Invalid player for gameEnded");
+ return null;
+ }
+ final String highScore = element.getAttribute("highScore");
if (winner == freeColClient.getMyPlayer()) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- igc().displayHighScores(highScore);
- }
- });
- getGUI().showVictoryDialog();
+ invokeLater(() -> { igc().victory(highScore); });
}
return null;
}
/**
- * Handles an "indianDemand"-request.
+ * Handle an "indianDemand"-request.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -852,14 +754,12 @@ public final class InGameInputHandler extends InputHandler {
final Player player = getFreeColClient().getMyPlayer();
final IndianDemandMessage message
= new IndianDemandMessage(game, element);
-
final Unit unit = message.getUnit(game);
if (unit == null) {
logger.warning("IndianDemand with null unit: "
+ element.getAttribute("unit"));
return null;
}
-
final Colony colony = message.getColony(game);
if (colony == null) {
logger.warning("IndianDemand with null colony: "
@@ -869,13 +769,9 @@ public final class InGameInputHandler extends InputHandler {
throw new IllegalArgumentException("Demand to anothers colony");
}
- invokeAndWait(new Runnable() {
- @Override
- public void run() {
- boolean accepted = igc().indianDemand(unit, colony,
- message.getType(game), message.getAmount());
- message.setResult(accepted);
- }
+ invokeAndWait(() -> {
+ message.setResult(igc().indianDemand(unit, colony,
+ message.getType(game), message.getAmount()));
});
return message.toXMLElement();
}
@@ -895,12 +791,12 @@ public final class InGameInputHandler extends InputHandler {
final List goods = message.getGoods();
if (unit == null || goods == null) return null;
- getGUI().showCaptureGoodsDialog(unit, goods, defenderId);
+ invokeLater(() -> { igc().loot(unit, goods, defenderId); });
return null;
}
/**
- * Handles a "monarchAction"-request.
+ * Handle a "monarchAction"-request.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -911,8 +807,10 @@ public final class InGameInputHandler extends InputHandler {
final MonarchActionMessage message
= new MonarchActionMessage(game, element);
- getGUI().showMonarchDialog(message.getAction(), message.getTemplate(),
- message.getMonarchKey());
+ invokeLater(() -> {
+ igc().monarch(message.getAction(), message.getTemplate(),
+ message.getMonarchKey());
+ });
return null;
}
@@ -954,7 +852,7 @@ public final class InGameInputHandler extends InputHandler {
if (unit == null || defaultName == null
|| !unit.hasTile()) return null;
- igc().newLandName(defaultName, unit);
+ invokeLater(() -> { igc().newLandName(defaultName, unit); });
return null;
}
@@ -974,12 +872,14 @@ public final class InGameInputHandler extends InputHandler {
final String defaultName = message.getNewRegionName();
if (defaultName == null || region == null) return null;
- igc().newRegionName(region, defaultName, tile, unit);
+ invokeLater(() -> {
+ igc().newRegionName(region, defaultName, tile, unit);
+ });
return null;
}
/**
- * Handles a "newTurn"-message.
+ * Handle a "newTurn"-message.
*
* @param element The element (root element in a DOM-parsed XML tree)
* that holds all the information.
@@ -987,23 +887,17 @@ public final class InGameInputHandler extends InputHandler {
*/
private Element newTurn(Element element) {
final int n = getIntegerAttribute(element, "turn");
+ if (n < 0) {
+ logger.warning("Invalid turn for newTurn");
+ return null;
+ }
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- igc().newTurn(n);
- }
- });
-
- igc().setCurrentPlayer(null);
- refreshCanvas(false);
-
- SwingUtilities.invokeLater(updateMenuBarRunnable);
+ invokeLater(() -> { igc().newTurn(n); });
return null;
}
/**
- * Handles an "reconnect"-message.
+ * Handle an "reconnect"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1012,12 +906,12 @@ public final class InGameInputHandler extends InputHandler {
private Element reconnect(@SuppressWarnings("unused") Element element) {
logger.finest("Entered reconnect.");
- SwingUtilities.invokeLater(reconnectRunnable);
+ invokeLater(reconnectRunnable);
return null;
}
/**
- * Handles a "remove"-message.
+ * Handle a "remove"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1025,11 +919,9 @@ public final class InGameInputHandler extends InputHandler {
*/
private Element remove(Element element) {
final Game game = getGame();
- String ds = element.getAttribute("divert");
- FreeColGameObject divert = game.getFreeColGameObject(ds);
- Player player = getFreeColClient().getMyPlayer();
- boolean visibilityChange = false;
-
+ final FreeColGameObject divert
+ = game.getFreeColGameObject(element.getAttribute("divert"));
+ final List objects = new ArrayList<>();
NodeList nodeList = element.getChildNodes();
for (int i = 0; i < nodeList.getLength(); i++) {
Element e = (Element)nodeList.item(i);
@@ -1042,42 +934,17 @@ public final class InGameInputHandler extends InputHandler {
// freeColGameObjects, before this remove is processed.
continue;
}
- if (divert != null) {
- player.divertModelMessages(fcgo, divert);
- }
- if (fcgo instanceof Settlement) {
- Settlement settlement = (Settlement)fcgo;
- if (settlement != null && settlement.getOwner() != null) {
- settlement.getOwner().removeSettlement(settlement);
- }
- visibilityChange = true;//-vis(player)
-
- } else if (fcgo instanceof Unit) {
- // Deselect the object if it is the current active unit.
- Unit u = (Unit)fcgo;
- if (u == getGUI().getActiveUnit()) {
- invokeAndWait(deselectActiveUnitRunnable);
- }
- // Temporary hack until we have real containers.
- if (u != null && u.getOwner() != null) {
- u.getOwner().removeUnit(u);
- }
- visibilityChange = true;//-vis(player)
- }
-
- // Do just the low level dispose that removes
- // reference to this object in the client. The other
- // updates should have done the rest.
- fcgo.disposeResources();
+ objects.add(fcgo);
}
- if (visibilityChange) player.invalidateCanSeeTiles();//+vis(player)
- refreshCanvas(false);
+ if (!objects.isEmpty()) {
+ invokeLater(() -> { igc().remove(objects, divert); });
+ }
return null;
}
/**
- * Handles a "setAI"-message.
+ * Handle a "setAI"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1093,25 +960,27 @@ public final class InGameInputHandler extends InputHandler {
}
/**
- * Handles a "setCurrentPlayer"-message.
+ * Handle a "setCurrentPlayer"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
* @return Null.
*/
private Element setCurrentPlayer(Element element) {
- Player player
+ final Player player
= getGame().getFreeColGameObject(element.getAttribute("player"),
Player.class);
-
- igc().setCurrentPlayer(player);
+ if (player == null) {
+ logger.warning("Invalid player for setCurrentPlayer");
+ return null;
+ }
- refreshCanvas(true);
+ igc().setCurrentPlayer(player); // It is safe to call this one directly
return null;
}
/**
- * Handles a "setDead"-message.
+ * Handle a "setDead"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1120,18 +989,17 @@ public final class InGameInputHandler extends InputHandler {
private Element setDead(Element element) {
final Player player = getGame()
.getFreeColGameObject(element.getAttribute("player"),Player.class);
+ if (player == null) {
+ logger.warning("Invalid player for setDead");
+ return null;
+ }
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- igc().setDead(player);
- }
- });
+ invokeLater(() -> { igc().setDead(player); });
return null;
}
/**
- * Handles a "setStance"-request.
+ * Handle a "setStance"-request.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1141,22 +1009,29 @@ public final class InGameInputHandler extends InputHandler {
final Game game = getGame();
final Stance stance = Enum.valueOf(Stance.class,
element.getAttribute("stance"));
+ if (stance == null) {
+ logger.warning("Invalid stance for setStance");
+ return null;
+ }
final Player p1 = game
.getFreeColGameObject(element.getAttribute("first"), Player.class);
+ if (p1 == null) {
+ logger.warning("Invalid player1 for setStance");
+ return null;
+ }
final Player p2 = game
.getFreeColGameObject(element.getAttribute("second"),Player.class);
+ if (p2 == null) {
+ logger.warning("Invalid player2 for setStance");
+ return null;
+ }
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- igc().setStance(stance, p1, p2);
- }
- });
+ invokeLater(() -> { igc().setStance(stance, p1, p2); });
return null;
}
/**
- * Handles a "spyResult" message.
+ * Handle a "spyResult" message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1190,23 +1065,17 @@ public final class InGameInputHandler extends InputHandler {
// is closed.
final Element fullElement = (Element)nodeList.item(0);
final Element normalElement = (Element)nodeList.item(1);
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- tile.readFromXMLElement(fullElement);
- getGUI().showSpyColonyPanel(tile, new Runnable() {
- @Override
- public void run() {
- tile.readFromXMLElement(normalElement);
- }
- });
- }
+ tile.readFromXMLElement(fullElement);
+ invokeLater(() -> {
+ igc().spyColony(tile, () -> {
+ tile.readFromXMLElement(normalElement);
+ });
});
return null;
}
/**
- * Handles an "update"-message.
+ * Handle an "update"-message.
*
* @param element The element (root element in a DOM-parsed XML
* tree) that holds all the information.
@@ -1234,7 +1103,6 @@ public final class InGameInputHandler extends InputHandler {
}
if (visibilityChange) player.invalidateCanSeeTiles();//+vis(player)
- refreshCanvas(false);
return null;
}
}
diff --git a/src/net/sf/freecol/client/control/InputHandler.java b/src/net/sf/freecol/client/control/InputHandler.java
index 63c341522..da1b4aa77 100644
--- a/src/net/sf/freecol/client/control/InputHandler.java
+++ b/src/net/sf/freecol/client/control/InputHandler.java
@@ -101,15 +101,12 @@ public abstract class InputHandler implements MessageHandler {
*/
protected Element disconnect(Element element) {
// Updating the GUI should always be done in the EDT:
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- if (getGUI().containsInGameComponents()) {
- if (freeColClient.getFreeColServer() == null) {
- getGUI().returnToTitle();
- } else {
- getGUI().removeInGameComponents();
- }
+ javax.swing.SwingUtilities.invokeLater(() -> {
+ if (getGUI().containsInGameComponents()) {
+ if (freeColClient.getFreeColServer() == null) {
+ getGUI().returnToTitle();
+ } else {
+ getGUI().removeInGameComponents();
}
}
});
diff --git a/src/net/sf/freecol/client/control/MapEditorController.java b/src/net/sf/freecol/client/control/MapEditorController.java
index a87b40017..4142d64e1 100644
--- a/src/net/sf/freecol/client/control/MapEditorController.java
+++ b/src/net/sf/freecol/client/control/MapEditorController.java
@@ -31,7 +31,6 @@ import javax.xml.stream.XMLStreamException;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.GUI;
-import net.sf.freecol.client.gui.panel.MapEditorTransformPanel.MapTransform;
import net.sf.freecol.common.FreeColException;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.io.FreeColDirectories;
@@ -43,13 +42,12 @@ import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
-import net.sf.freecol.common.networking.NoRouteToServerException;
import net.sf.freecol.common.option.MapGeneratorOptions;
import net.sf.freecol.common.option.OptionGroup;
import net.sf.freecol.common.util.LogBuilder;
import net.sf.freecol.server.FreeColServer;
-import net.sf.freecol.server.model.ServerPlayer;
import net.sf.freecol.server.generator.MapGenerator;
+import net.sf.freecol.server.model.ServerPlayer;
/**
@@ -65,11 +63,21 @@ public final class MapEditorController {
private final GUI gui;
+ public interface IMapTransform {
+
+ /**
+ * Applies this transformation to the given tile.
+ * @param t The Tile
to be transformed,
+ */
+ public abstract void transform(Tile t);
+
+ }
+
/**
* The transform that should be applied to a Tile
* that is clicked on the map.
*/
- private MapTransform currentMapTransform = null;
+ private IMapTransform currentMapTransform = null;
/**
@@ -107,9 +115,6 @@ public final class MapEditorController {
freeColClient.setInGame(true);
gui.changeViewMode(GUI.VIEW_TERRAIN_MODE);
gui.startMapEditorGUI();
- } catch (NoRouteToServerException e) {
- gui.showErrorMessage("server.noRouteToServer");
- return;
} catch (IOException e) {
gui.showErrorMessage("server.initialize");
return;
@@ -132,7 +137,7 @@ public final class MapEditorController {
* @param mt The transform that should be applied to a
* Tile
that is clicked on the map.
*/
- public void setMapTransform(MapTransform mt) {
+ public void setMapTransform(IMapTransform mt) {
currentMapTransform = mt;
gui.updateMapControls();
}
@@ -142,7 +147,7 @@ public final class MapEditorController {
* @return The transform that should be applied to a
* Tile
that is clicked on the map.
*/
- public MapTransform getMapTransform() {
+ public IMapTransform getMapTransform() {
return currentMapTransform;
}
@@ -177,7 +182,7 @@ public final class MapEditorController {
.createMap(new LogBuilder(-1));
requireNativeNations(game);
gui.setFocus(game.getMap().getTile(1,1));
- freeColClient.updateActions();
+ gui.updateMenuBar();
gui.refresh();
}
@@ -211,19 +216,13 @@ public final class MapEditorController {
BufferedImage thumb = gui.createMiniMapThumbNail();
freeColClient.getFreeColServer()
.saveMapEditorGame(file, thumb);
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- gui.closeStatusPanel();
- gui.requestFocusInWindow();
- }
+ SwingUtilities.invokeLater(() -> {
+ gui.closeStatusPanel();
+ gui.requestFocusInWindow();
});
} catch (IOException e) {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- gui.showErrorMessage(FreeCol.badSave(file));
- }
+ SwingUtilities.invokeLater(() -> {
+ gui.showErrorMessage(FreeCol.badSave(file));
});
}
}
@@ -248,7 +247,7 @@ public final class MapEditorController {
public void requireNativeNations(Game game) {
final Specification spec = game.getSpecification();
for (Nation n : spec.getIndianNations()) {
- Player p = game.getPlayer(n.getId());
+ Player p = game.getPlayerByNation(n);
if (p == null) {
p = new ServerPlayer(game, false, n, null, null);
game.addPlayer(p);
@@ -282,54 +281,43 @@ public final class MapEditorController {
gui.showStatusPanel(Messages.message("status.loadingGame"));
- Runnable loadGameJob = new Runnable() {
- @Override
- public void run() {
- FreeColServer freeColServer
- = freeColClient.getFreeColServer();
- try {
- Specification spec = getDefaultSpecification();
- Game game = FreeColServer.readGame(new FreeColSavegameFile(theFile),
- spec, freeColServer);
- freeColClient.setGame(game);
- requireNativeNations(game);
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- gui.closeStatusPanel();
- gui.setFocus(freeColClient.getGame()
- .getMap().getTile(1,1));
- freeColClient.updateActions();
- gui.refresh();
- }
- });
- } catch (FreeColException e) {
- reloadMainPanel();
- SwingUtilities.invokeLater(new ErrorJob(StringTemplate.name(e.getMessage())));
- } catch (FileNotFoundException e) {
- reloadMainPanel();
- SwingUtilities.invokeLater(new ErrorJob(StringTemplate.key("server.fileNotFound")));
- } catch (IOException e) {
- reloadMainPanel();
- SwingUtilities.invokeLater(new ErrorJob(StringTemplate.key("server.initialize")));
- } catch (XMLStreamException e) {
- reloadMainPanel();
- SwingUtilities.invokeLater(new ErrorJob(FreeCol.badLoad(theFile)));
- }
- }
- };
+ Runnable loadGameJob = () -> {
+ FreeColServer freeColServer = freeColClient.getFreeColServer();
+ try {
+ Specification spec = getDefaultSpecification();
+ Game game = FreeColServer.readGame(new FreeColSavegameFile(theFile),
+ spec, freeColServer);
+ freeColClient.setGame(game);
+ requireNativeNations(game);
+ SwingUtilities.invokeLater(() -> {
+ gui.closeStatusPanel();
+ gui.setFocus(freeColClient.getGame().getMap().getTile(1,1));
+ gui.updateMenuBar();
+ gui.refresh();
+ });
+ } catch (FreeColException e) {
+ reloadMainPanel();
+ SwingUtilities.invokeLater(new ErrorJob(StringTemplate.name(e.getMessage())));
+ } catch (FileNotFoundException e) {
+ reloadMainPanel();
+ SwingUtilities.invokeLater(new ErrorJob(StringTemplate.key("server.fileNotFound")));
+ } catch (IOException e) {
+ reloadMainPanel();
+ SwingUtilities.invokeLater(new ErrorJob(StringTemplate.key("server.initialize")));
+ } catch (XMLStreamException e) {
+ reloadMainPanel();
+ SwingUtilities.invokeLater(new ErrorJob(FreeCol.badLoad(theFile)));
+ }
+ };
freeColClient.setWork(loadGameJob);
}
private void reloadMainPanel () {
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- gui.closeMainPanel();
- gui.showMainPanel(null);
- freeColClient.getSoundController()
- .playSound("sound.intro.general");
- }
+ SwingUtilities.invokeLater(() -> {
+ gui.closeMainPanel();
+ gui.showMainPanel(null);
+ freeColClient.getSoundController()
+ .playSound("sound.intro.general");
});
}
}
diff --git a/src/net/sf/freecol/client/control/PreGameController.java b/src/net/sf/freecol/client/control/PreGameController.java
index 9cdb7594b..6a36aa630 100644
--- a/src/net/sf/freecol/client/control/PreGameController.java
+++ b/src/net/sf/freecol/client/control/PreGameController.java
@@ -28,7 +28,6 @@ import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.GameOptions;
-import net.sf.freecol.common.model.Direction;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.NationOptions.NationState;
import net.sf.freecol.common.model.NationType;
diff --git a/src/net/sf/freecol/client/control/PreGameInputHandler.java b/src/net/sf/freecol/client/control/PreGameInputHandler.java
index bcf10a7cf..1e9e309d2 100644
--- a/src/net/sf/freecol/client/control/PreGameInputHandler.java
+++ b/src/net/sf/freecol/client/control/PreGameInputHandler.java
@@ -283,12 +283,9 @@ public final class PreGameInputHandler extends InputHandler {
} catch (Exception ex) {}
}
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- getFreeColClient().getPreGameController()
- .startGame();
- }
+ SwingUtilities.invokeLater(() -> {
+ getFreeColClient().getPreGameController()
+ .startGame();
});
}
}.start();
@@ -339,7 +336,6 @@ public final class PreGameInputHandler extends InputHandler {
Game game = fcc.getGame();
game.readFromXMLElement((Element)children.item(0));
fcc.addSpecificationActions(game.getSpecification());
- fcc.updateActions();
} else {
logger.warning("Child node expected: " + element.getTagName());
}
diff --git a/src/net/sf/freecol/client/gui/AbstractCanvasListener.java b/src/net/sf/freecol/client/gui/AbstractCanvasListener.java
index 68ed1db8e..07bf9a8a3 100644
--- a/src/net/sf/freecol/client/gui/AbstractCanvasListener.java
+++ b/src/net/sf/freecol/client/gui/AbstractCanvasListener.java
@@ -41,8 +41,7 @@ public class AbstractCanvasListener {
/** The enclosing client. */
protected final FreeColClient freeColClient;
- /** The map viewer to scroll. */
- protected final MapViewer mapViewer;
+ protected final Canvas canvas;
/** The scroll thread itself. */
protected ScrollThread scrollThread = null;
@@ -53,9 +52,9 @@ public class AbstractCanvasListener {
*
* @param freeColClient The FreeColClient
for the game.
*/
- public AbstractCanvasListener(FreeColClient freeColClient, MapViewer mapViewer) {
+ public AbstractCanvasListener(FreeColClient freeColClient, Canvas canvas) {
this.freeColClient = freeColClient;
- this.mapViewer = mapViewer;
+ this.canvas = canvas;
this.scrollThread = null;
}
@@ -107,7 +106,7 @@ public class AbstractCanvasListener {
*/
private void scroll(int x, int y, int scrollSpace) {
Direction direction;
- Dimension size = mapViewer.getSize();
+ Dimension size = canvas.getSize();
if (x < scrollSpace && y < scrollSpace) { // Upper-Left
direction = Direction.NW;
} else if (x >= size.width - scrollSpace
@@ -134,7 +133,7 @@ public class AbstractCanvasListener {
if (direction == null) {
stopScrollIfScrollIsActive();
} else if (scrollThread == null || scrollThread.isInterrupted()) {
- scrollThread = new ScrollThread(mapViewer);
+ scrollThread = new ScrollThread(canvas);
scrollThread.setDirection(direction);
scrollThread.start();
} else {
diff --git a/src/net/sf/freecol/client/gui/Canvas.java b/src/net/sf/freecol/client/gui/Canvas.java
index 2b13fa73e..8563d6cfa 100644
--- a/src/net/sf/freecol/client/gui/Canvas.java
+++ b/src/net/sf/freecol/client/gui/Canvas.java
@@ -25,15 +25,12 @@ import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
-import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.event.ActionListener;
-import java.awt.event.ComponentAdapter;
-import java.awt.event.ComponentEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
@@ -41,10 +38,12 @@ import java.awt.font.TextLayout;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
@@ -57,22 +56,20 @@ import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileFilter;
+import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.plaf.basic.BasicInternalFrameUI;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.action.FreeColAction;
-import net.sf.freecol.client.gui.menu.FreeColMenuBar;
-import net.sf.freecol.client.gui.menu.InGameMenuBar;
-import net.sf.freecol.client.gui.menu.MapEditorMenuBar;
import net.sf.freecol.client.gui.panel.*;
import net.sf.freecol.client.gui.panel.LabourData.UnitData;
import net.sf.freecol.common.ServerInfo;
import net.sf.freecol.common.i18n.Messages;
-import net.sf.freecol.common.io.FreeColFileFilter;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.DiplomaticTrade;
+import net.sf.freecol.common.model.Direction;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.FreeColObject;
@@ -179,7 +176,7 @@ public final class Canvas extends JDesktopPane {
private final FreeColClient freeColClient;
/** The parent GUI. */
- private final GUI gui;
+ private final SwingGUI gui;
private final GraphicsDevice graphicsDevice;
@@ -188,8 +185,6 @@ public final class Canvas extends JDesktopPane {
private boolean windowed;
- private Rectangle windowBounds;
-
private MainPanel mainPanel;
private final StartGamePanel startGamePanel;
@@ -202,6 +197,8 @@ public final class Canvas extends JDesktopPane {
private final MapViewer mapViewer;
+ private Point gotoDragPoint;
+
private GrayLayer greyLayer;
private final ServerListPanel serverListPanel;
@@ -225,22 +222,24 @@ public final class Canvas extends JDesktopPane {
*
* @param freeColClient The FreeColClient
for the game.
* @param graphicsDevice The used graphics device.
+ * @param gui The gui.
* @param desiredSize The desired size of the frame.
* @param mapViewer The object responsible of drawing the map onto
* this component.
*/
Canvas(final FreeColClient freeColClient,
- final GraphicsDevice graphicsDevice,
- final Dimension desiredSize,
- MapViewer mapViewer) {
+ final GraphicsDevice graphicsDevice,
+ final SwingGUI gui,
+ final Dimension desiredSize,
+ MapViewer mapViewer) {
this.freeColClient = freeColClient;
- this.gui = freeColClient.getGUI();
+ this.gui = gui;
this.graphicsDevice = graphicsDevice;
chatDisplay = new ChatDisplay();
this.mapViewer = mapViewer;
// Determine if windowed mode should be used and set the window size.
- windowBounds = null;
+ Rectangle windowBounds = null;
if (desiredSize == null) {
if(graphicsDevice.isFullScreenSupported()) {
windowed = false;
@@ -274,7 +273,8 @@ public final class Canvas extends JDesktopPane {
setFocusTraversalKeysEnabled(false);
createKeyBindings();
- changeWindowedMode(windowed);
+ createFrame(null, windowBounds);
+ mapViewer.startCursorBlinking();
logger.info("Canvas created.");
}
@@ -284,36 +284,30 @@ public final class Canvas extends JDesktopPane {
/**
* Change the windowed mode.
- *
- * @param windowed Use true
for windowed mode
- * and false
for fullscreen mode.
*/
- void changeWindowedMode(boolean windowed) {
+ void changeWindowedMode() {
// Clean up the old frame
JMenuBar menuBar = null;
+ Rectangle windowBounds = null;
if (frame != null) {
menuBar = frame.getJMenuBar();
- if (this.windowed) {
+ if (windowed) {
windowBounds = frame.getBounds();
}
frame.setVisible(false);
frame.dispose();
}
- this.windowed = windowed;
+ windowed = !windowed;
+ createFrame(menuBar, windowBounds);
+ }
+
+ private void createFrame(JMenuBar menuBar, Rectangle windowBounds) {
+ // FIXME: Check this:
// User might have moved window to new screen in a
// multi-screen setup, so make this.gd point to the current screen.
frame = new FreeColFrame(freeColClient, graphicsDevice,
menuBar, this, windowed, windowBounds);
- if (windowed) {
- frame.addComponentListener(new ComponentAdapter() {
- @Override
- public void componentResized(ComponentEvent e) {
- logger.info("Window size changes to " + getSize());
- }
- });
- }
-
updateSizes();
frame.setVisible(true);
}
@@ -327,11 +321,11 @@ public final class Canvas extends JDesktopPane {
// We may need to reset the zoom value to the default value
gui.resetMapZoom();
- frame.setJMenuBar(new MapEditorMenuBar(freeColClient, mapViewer));
+ frame.setMapEditorMenuBar();
showMapEditorTransformPanel();
CanvasMapEditorMouseListener listener
- = new CanvasMapEditorMouseListener(freeColClient, this, mapViewer);
+ = new CanvasMapEditorMouseListener(freeColClient, this);
addMouseListener(listener);
addMouseMotionListener(listener);
}
@@ -340,10 +334,8 @@ public final class Canvas extends JDesktopPane {
* Quit the GUI. All that is required is to exit the full screen.
*/
void quit() throws Exception {
- if (frame != null) {
- GraphicsConfiguration GraphicsConf = frame.getGraphicsConfiguration();
- GraphicsDevice gd = GraphicsConf.getDevice();
- if (!windowed) gd.setFullScreenWindow(null);
+ if (frame != null && !windowed) {
+ frame.exitFullScreen();
}
}
@@ -352,9 +344,7 @@ public final class Canvas extends JDesktopPane {
*/
void initializeInGame() {
if (frame == null) return;
-
- frame.setJMenuBar(new InGameMenuBar(freeColClient, mapViewer));
- frame.paintAll(getGraphics());
+ frame.setInGameMenuBar();
}
/**
@@ -362,19 +352,90 @@ public final class Canvas extends JDesktopPane {
*/
void resetMenuBar() {
if (frame == null) return;
- JMenuBar menuBar = frame.getJMenuBar();
- if (menuBar != null) {
- ((FreeColMenuBar)menuBar).reset();
- }
+ frame.resetMenuBar();
}
/**
* Update the menu bar.
*/
void updateMenuBar() {
- if (frame != null && frame.getJMenuBar() != null) {
- ((FreeColMenuBar)frame.getJMenuBar()).update();
- }
+ if (frame == null) return;
+ frame.updateMenuBar();
+ }
+
+ /**
+ * Scroll the map in the given direction.
+ *
+ * @param direction The Direction
to scroll in.
+ * @return True if scrolling occurred.
+ */
+ boolean scrollMap(Direction direction) {
+ return mapViewer.scrollMap(direction);
+ }
+
+ /**
+ * Converts the given screen coordinates to Map coordinates.
+ * It checks to see to which Tile the given pixel 'belongs'.
+ *
+ * @param x The x-coordinate in pixels.
+ * @param y The y-coordinate in pixels.
+ * @return The Tile that is located at the given position on the screen.
+ */
+ Tile convertToMapTile(int x, int y) {
+ return mapViewer.convertToMapTile(x, y);
+ }
+
+ /**
+ * Get the view mode.
+ *
+ * @return The view mode.
+ */
+ public int getViewMode() {
+ return mapViewer.getViewMode();
+ }
+
+ /**
+ * Gets the active unit.
+ *
+ * @return The Unit
.
+ */
+ Unit getActiveUnit() {
+ return mapViewer.getActiveUnit();
+ }
+
+ /**
+ * Set the current active unit path.
+ *
+ * @param path The current PathNode
.
+ */
+ void setCurrentPath(PathNode path) {
+ mapViewer.setCurrentPath(path);
+ }
+
+ /**
+ * Sets the path of the active unit to display it.
+ */
+ void updateCurrentPathForActiveUnit() {
+ mapViewer.updateCurrentPathForActiveUnit();
+ }
+
+ /**
+ * Gets the point at which the map was clicked for a drag.
+ *
+ * @return The Point where the mouse was initially clicked.
+ */
+ Point getDragPoint() {
+ return gotoDragPoint;
+ }
+
+ /**
+ * Sets the point at which the map was clicked for a drag.
+ *
+ * @param x The mouse's x position.
+ * @param y The mouse's y position.
+ */
+ void setDragPoint(int x, int y) {
+ gotoDragPoint = new Point(x, y);
}
/**
@@ -547,7 +608,7 @@ public final class Canvas extends JDesktopPane {
private Point chooseLocation(Component comp, int width, int height,
PopupPosition popupPosition) {
Point p = null;
- if ((comp instanceof FreeColPanel || comp instanceof FreeColDialog>)
+ if ((comp instanceof FreeColPanel)
&& (p = getSavedPosition(comp)) != null) {
// Sanity check stuff coming out of client options.
if (p.getX() < 0
@@ -621,15 +682,9 @@ public final class Canvas extends JDesktopPane {
Point p = new Point(x, y);
todo.add(p);
- List allComponents = new ArrayList<>();
- for (Component c : this.getComponents()) {
- if (c instanceof GrayLayer || !c.isValid()) {
- // GrayLayer always intersects and blocks early
- // dialogs like FF-selection
- continue;
- }
- allComponents.add(c);
- }
+ List allComponents = Arrays.stream(this.getComponents())
+ .filter(c -> !(c instanceof GrayLayer) && c.isValid())
+ .collect(Collectors.toList());
for (FreeColDialog> fcd : dialogs) allComponents.add(fcd);
// Find the position with the least overlap
@@ -731,13 +786,13 @@ public final class Canvas extends JDesktopPane {
}
/**
- * Given a tile to be made visible, determine a position to popup
+ * Make a tile visible, then determine corresponding position to popup
* a panel.
*
* @param tile A Tile
to be made visible.
* @return A PopupPosition
for a panel to be displayed.
*/
- private PopupPosition getPopupPosition(Tile tile) {
+ private PopupPosition setOffsetFocus(Tile tile) {
if (tile == null) return PopupPosition.CENTERED;
int where = mapViewer.setOffsetFocus(tile);
return (where > 0) ? PopupPosition.CENTERED_LEFT
@@ -795,6 +850,21 @@ public final class Canvas extends JDesktopPane {
}
}
+ /**
+ * Initialize the file filters to filter for saved games.
+ *
+ * @return File filters for the FreeCol save game extension.
+ */
+ private FileFilter[] getFileFilters() {
+ if (fileFilters == null) {
+ String s = Messages.message("filter.savedGames");
+ fileFilters = new FileFilter[] {
+ new FileNameExtensionFilter(s, FreeCol.FREECOL_SAVE_EXTENSION)
+ };
+ }
+ return fileFilters;
+ }
+
/**
* A component is closing. Some components need position and size
* to be saved.
@@ -893,6 +963,7 @@ public final class Canvas extends JDesktopPane {
* for the presence of other dialogs.
*/
private void restartBlinking() {
+ if (mapViewer.getViewMode() != GUI.MOVE_UNITS_MODE) return;
for (FreeColDialog> f : dialogs) {
if (f.isModal()) return;
}
@@ -903,7 +974,6 @@ public final class Canvas extends JDesktopPane {
* Stop blinking on the map.
*/
private void stopBlinking() {
- if (gui.getViewMode() != GUI.MOVE_UNITS_MODE) return;
mapViewer.stopBlinking();
}
@@ -935,7 +1005,7 @@ public final class Canvas extends JDesktopPane {
*/
private void showFreeColPanel(FreeColPanel panel, Tile tile,
boolean resizable) {
- showSubPanel(panel, getPopupPosition(tile), resizable);
+ showSubPanel(panel, setOffsetFocus(tile), resizable);
}
/**
@@ -986,8 +1056,7 @@ public final class Canvas extends JDesktopPane {
*/
public void add(Component comp, Integer i) {
addToCanvas(comp, i);
- updateMenuBar();
- freeColClient.updateActions();
+ gui.updateMenuBar();
}
/**
@@ -1095,12 +1164,9 @@ public final class Canvas extends JDesktopPane {
T ret = type.cast(c2);
if (ret != null) {
final JInternalFrame jif = (JInternalFrame)c1;
- SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- jif.toFront();
- jif.repaint();
- }
+ SwingUtilities.invokeLater(() -> {
+ jif.toFront();
+ jif.repaint();
});
return ret;
}
@@ -1288,16 +1354,14 @@ public final class Canvas extends JDesktopPane {
// inGame. (Retrieve value of GUI::inGame.) If GUI thinks
// we're still in the game then log an error because at this
// point the GUI should have been informed.
- closeMenus();
removeInGameComponents();
showMainPanel(null);
repaint();
}
void setupMouseListeners() {
- addMouseListener(new CanvasMouseListener(freeColClient, this,
- mapViewer));
- addMouseMotionListener(new CanvasMouseMotionListener(freeColClient, this, mapViewer));
+ addMouseListener(new CanvasMouseListener(freeColClient, this));
+ addMouseMotionListener(new CanvasMouseMotionListener(freeColClient, this));
}
/**
@@ -1407,10 +1471,8 @@ public final class Canvas extends JDesktopPane {
@Override
public void remove(Component comp) {
removeFromCanvas(comp);
- final boolean takeFocus = (comp != statusPanel);
- updateMenuBar();
- freeColClient.updateActions();
- if (takeFocus && !isShowingSubPanel()) {
+ gui.updateMenuBar();
+ if (comp != statusPanel && !isShowingSubPanel()) {
requestFocus();
}
}
@@ -1444,9 +1506,8 @@ public final class Canvas extends JDesktopPane {
// Dialog display
/**
- * Displays a dialog with text and a choice of options.
+ * Displays a modal dialog with text and a choice of options.
*
- * @param modal True if this dialog should be modal.
* @param tile An optional Tile
to make visible (not
* under the dialog!)
* @param obj An object that explains the choice for the user.
@@ -1457,19 +1518,17 @@ public final class Canvas extends JDesktopPane {
* @return The corresponding member of the values array to the selected
* option.
*/
- T showChoiceDialog(boolean modal, Tile tile, Object obj,
- ImageIcon icon, String cancelKey,
- List> choices) {
+ T showChoiceDialog(Tile tile, Object obj, ImageIcon icon,
+ String cancelKey, List> choices) {
FreeColChoiceDialog fcd
- = new FreeColChoiceDialog<>(freeColClient, frame, modal, obj, icon,
+ = new FreeColChoiceDialog<>(freeColClient, frame, true, obj, icon,
cancelKey, choices);
return showFreeColDialog(fcd, tile);
}
/**
- * Displays a dialog with a text and a ok/cancel option.
+ * Displays a modal dialog with a text and a ok/cancel option.
*
- * @param modal True if this dialog should be modal.
* @param tile An optional Tile
to make visible (not
* under the dialog!)
* @param obj An object that explains the choice for the user.
@@ -1478,19 +1537,17 @@ public final class Canvas extends JDesktopPane {
* @param cancelKey The text displayed on the "cancel"-button.
* @return True if the user clicked the "ok"-button.
*/
- boolean showConfirmDialog(boolean modal, Tile tile,
- Object obj, ImageIcon icon,
- String okKey, String cancelKey) {
+ boolean showConfirmDialog(Tile tile, Object obj, ImageIcon icon,
+ String okKey, String cancelKey) {
FreeColConfirmDialog fcd
- = new FreeColConfirmDialog(freeColClient, frame, modal, obj, icon,
+ = new FreeColConfirmDialog(freeColClient, frame, true, obj, icon,
okKey, cancelKey);
return showFreeColDialog(fcd, tile);
}
/**
- * Displays a dialog with a text field and a ok/cancel option.
+ * Displays a modal dialog with a text field and a ok/cancel option.
*
- * @param modal True if this dialog should be modal.
* @param tile An optional tile to make visible (not under the dialog).
* @param template A StringTemplate
that explains the
* action to the user.
@@ -1499,11 +1556,11 @@ public final class Canvas extends JDesktopPane {
* @param cancelKey A key displayed on the optional "cancel"-button.
* @return The text the user entered, or null if cancelled.
*/
- String showInputDialog(boolean modal, Tile tile,
- StringTemplate template, String defaultValue,
- String okKey, String cancelKey) {
+ String showInputDialog(Tile tile, StringTemplate template,
+ String defaultValue,
+ String okKey, String cancelKey) {
FreeColStringInputDialog fcd
- = new FreeColStringInputDialog(freeColClient, frame, modal,
+ = new FreeColStringInputDialog(freeColClient, frame, true,
Messages.message(template),
defaultValue, okKey, cancelKey);
return showFreeColDialog(fcd, tile);
@@ -1518,9 +1575,25 @@ public final class Canvas extends JDesktopPane {
*/
private void viewFreeColDialog(final FreeColDialog freeColDialog,
Tile tile) {
- freeColDialog.setLocation(chooseLocation(freeColDialog,
- freeColDialog.getWidth(), freeColDialog.getHeight(),
- getPopupPosition(tile)));
+ PopupPosition pp = setOffsetFocus(tile);
+
+ // TODO: Remove compatibility code when all non-modal dialogs
+ // have been converted into panels.
+ if(!freeColDialog.isModal()) {
+ int canvasWidth = getWidth();
+ int dialogWidth = freeColDialog.getWidth();
+ if(dialogWidth*2 <= canvasWidth) {
+ Point location = freeColDialog.getLocation();
+ if(pp == PopupPosition.CENTERED_LEFT) {
+ freeColDialog.setLocation(location.x - canvasWidth/4,
+ location.y);
+ } else if(pp == PopupPosition.CENTERED_RIGHT) {
+ freeColDialog.setLocation(location.x + canvasWidth/4,
+ location.y);
+ }
+ }
+ }
+
dialogAdd(freeColDialog);
if (freeColDialog.isModal()) stopBlinking();
freeColDialog.requestFocus();
@@ -1577,7 +1650,7 @@ public final class Canvas extends JDesktopPane {
* @param handler A DialogHandler
for the dialog response.
*/
void showCaptureGoodsDialog(Unit unit, List gl,
- DialogHandler> handler) {
+ DialogHandler> handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new CaptureGoodsDialog(freeColClient, frame, unit, gl),
@@ -1602,7 +1675,7 @@ public final class Canvas extends JDesktopPane {
* @param handler A DialogHandler
for the dialog response.
*/
void showChooseFoundingFatherDialog(List ffs,
- DialogHandler handler) {
+ DialogHandler handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new ChooseFoundingFatherDialog(freeColClient, frame, ffs),
@@ -1622,12 +1695,6 @@ public final class Canvas extends JDesktopPane {
group = showFreeColDialog(dialog, null);
} finally {
clientOptionsDialogShowing = false;
- if (group != null) {
- freeColClient.updateActions();
- resetMenuBar();
- // Immediately redraw the minimap if that was updated.
- gui.updateMapControls();
- }
}
return group;
}
@@ -1718,30 +1785,18 @@ public final class Canvas extends JDesktopPane {
PopupPosition.CENTERED, false);
}
- /**
- * Display the difficulty dialog.
- *
- * @return The resulting OptionGroup
.
- */
- OptionGroup showDifficultyDialog() {
- Game game = freeColClient.getGame();
- Specification spec = game.getSpecification();
- return showFreeColDialog(new DifficultyDialog(freeColClient, frame, spec,
- spec.getDifficultyOptionGroup(), false),
- null);
- }
-
/**
* Display the difficulty dialog for a given group.
*
* @param spec The enclosing Specification
.
* @param group The OptionGroup
containing the difficulty.
+ * @param editable If the options should be editable.
* @return The resulting OptionGroup
.
*/
OptionGroup showDifficultyDialog(Specification spec,
- OptionGroup group) {
- return showFreeColDialog(new DifficultyDialog(freeColClient, frame, spec,
- group, group.isEditable()),
+ OptionGroup group, boolean editable) {
+ return showFreeColDialog(new DifficultyDialog(freeColClient, frame,
+ spec, group, editable),
null);
}
@@ -1751,8 +1806,7 @@ public final class Canvas extends JDesktopPane {
* @param unit The Unit
that is dumping.
* @param handler A DialogHandler
for the dialog response.
*/
- void showDumpCargoDialog(Unit unit,
- DialogHandler> handler) {
+ void showDumpCargoDialog(Unit unit, DialogHandler> handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new DumpCargoDialog(freeColClient, frame, unit),
@@ -1790,7 +1844,7 @@ public final class Canvas extends JDesktopPane {
* @param handler A DialogHandler
for the dialog response.
*/
void showEmigrationDialog(Player player, boolean fountainOfYouth,
- DialogHandler handler) {
+ DialogHandler handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new EmigrationDialog(freeColClient, frame, player.getEurope(),
@@ -1848,13 +1902,8 @@ public final class Canvas extends JDesktopPane {
if (freeColClient.getGame() == null) return;
EuropePanel panel = getExistingFreeColPanel(EuropePanel.class);
if (panel == null) {
- panel = new EuropePanel(freeColClient, this);
- panel.addClosingCallback(new Runnable() {
- @Override
- public void run() {
- removeEuropeanSubpanels();
- }
- });
+ panel = new EuropePanel(freeColClient, (getHeight() > 780));
+ panel.addClosingCallback(() -> { removeEuropeanSubpanels(); });
showSubPanel(panel, true);
}
}
@@ -1892,8 +1941,8 @@ public final class Canvas extends JDesktopPane {
* @param handler A DialogHandler
for the dialog response.
*/
void showFirstContactDialog(Player player, Player other,
- Tile tile, int settlementCount,
- DialogHandler handler) {
+ Tile tile, int settlementCount,
+ DialogHandler handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new FirstContactDialog(freeColClient, frame, player, other, tile,
@@ -1950,6 +1999,28 @@ public final class Canvas extends JDesktopPane {
showFreeColPanel(panel, indianSettlement.getTile(), true);
}
+ /**
+ * Make image icon from an image.
+ * Use only if you know having null is possible!
+ *
+ * @param image The Image
to create an icon for.
+ * @return The ImageIcon
.
+ */
+ private static ImageIcon createImageIcon(Image image) {
+ return (image==null) ? null : new ImageIcon(image);
+ }
+
+ /**
+ * Make image icon from an object.
+ *
+ * @param display The FreeColObject to find an icon for.
+ * @return The ImageIcon
found.
+ */
+ private ImageIcon createObjectImageIcon(FreeColObject display) {
+ return (display == null) ? null
+ : createImageIcon(gui.getImageLibrary().getObjectImage(display, 2f));
+ }
+
/**
* Shows a message with some information and an "OK"-button.
*
@@ -1961,7 +2032,7 @@ public final class Canvas extends JDesktopPane {
ImageIcon icon = null;
Tile tile = null;
if(displayObject != null) {
- icon = gui.createObjectImageIcon(displayObject);
+ icon = createObjectImageIcon(displayObject);
tile = (displayObject instanceof Location)
? ((Location)displayObject).getTile()
: null;
@@ -1990,32 +2061,15 @@ public final class Canvas extends JDesktopPane {
* Displays a dialog where the user may choose a file.
*
* @param directory The directory containing the files.
+ * @param filters The file filters which the user can select in the dialog.
* @return The selected File
.
*/
- File showLoadDialog(File directory) {
- if (fileFilters == null) {
- fileFilters = new FileFilter[] {
- FreeColFileFilter.freeColSaveDirectoryFilter,
- };
- }
- return showFreeColDialog(new LoadDialog(freeColClient, frame, directory,
- fileFilters),
- null);
- }
-
- /**
- * Displays a dialog where the user may choose a file.
- *
- * @param directory The directory containing the files.
- * @param fileFilters The file filters which the user can select in the
- * dialog.
- * @return The selected File
.
- */
- File showLoadDialog(File directory, FileFilter[] fileFilters) {
+ File showLoadDialog(File directory, FileFilter[] filters) {
+ if (filters == null) filters = getFileFilters();
File response = null;
for (;;) {
response = showFreeColDialog(new LoadDialog(freeColClient, frame,
- directory, fileFilters),
+ directory, filters),
null);
if (response == null || response.isFile()) break;
showErrorMessage("error.noSuchFile");
@@ -2055,7 +2109,7 @@ public final class Canvas extends JDesktopPane {
*/
void showMainPanel(String userMsg) {
closeMenus();
- frame.setJMenuBar(null);
+ frame.removeMenuBar();
mainPanel = new MainPanel(freeColClient);
addCentered(mainPanel, JLayeredPane.DEFAULT_LAYER);
if (userMsg != null) gui.showInformationMessage(userMsg);
@@ -2110,7 +2164,7 @@ public final class Canvas extends JDesktopPane {
ModelMessage m = messages.get(i);
texts[i] = Messages.message(m);
fcos[i] = game.getMessageSource(m);
- icons[i] = gui.createObjectImageIcon(game.getMessageDisplay(m));
+ icons[i] = createObjectImageIcon(game.getMessageDisplay(m));
if (tile == null && fcos[i] instanceof Location) {
tile = ((Location)fcos[i]).getTile();
}
@@ -2131,8 +2185,8 @@ public final class Canvas extends JDesktopPane {
* @param handler A DialogHandler
for the dialog response.
*/
void showMonarchDialog(MonarchAction action,
- StringTemplate template, String monarchKey,
- DialogHandler handler) {
+ StringTemplate template, String monarchKey,
+ DialogHandler handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new MonarchDialog(freeColClient, frame, action, template, monarchKey),
@@ -2140,36 +2194,16 @@ public final class Canvas extends JDesktopPane {
}
/**
- * Display a dialog to set a new land name.
- *
- * @param key A key for the message to explain the dialog.
- * @param defaultName The default name for the new land.
- * @param unit The Unit
discovering the new land.
- * @param handler A DialogHandler
for the dialog response.
- */
- void showNameNewLandDialog(String key, String defaultName,
- Unit unit,
- DialogHandler handler) {
- SwingUtilities.invokeLater(
- new DialogCallback<>(
- new FreeColStringInputDialog(freeColClient, frame, false,
- Messages.message(key),
- defaultName, "ok", null),
- unit.getTile(), handler));
- }
-
- /**
- * Display a dialog to set a new region name.
+ * Display a dialog to set a new name for something.
*
* @param template A StringTemplate
for the message
* to explain the dialog.
- * @param defaultName The default name for the new region.
- * @param unit The Unit
discovering the new region.
+ * @param defaultName The default name.
+ * @param unit The Unit
discovering it.
* @param handler A DialogHandler
for the dialog response.
*/
- void showNameNewRegionDialog(StringTemplate template,
- String defaultName, Unit unit,
- DialogHandler handler) {
+ void showNamingDialog(StringTemplate template, String defaultName,
+ Unit unit, DialogHandler handler) {
SwingUtilities.invokeLater(
new DialogCallback<>(
new FreeColStringInputDialog(freeColClient, frame, false,
@@ -2203,14 +2237,7 @@ public final class Canvas extends JDesktopPane {
}
/**
- * Display the NewPanel.
- */
- void showNewPanel() {
- showSubPanel(new NewPanel(freeColClient), false);
- }
-
- /**
- * Display the NewPanel for a given specification.
+ * Display the NewPanel for a given optional specification.
*
* @param specification The Specification
to use.
*/
@@ -2312,35 +2339,15 @@ public final class Canvas extends JDesktopPane {
*
* @param directory The directory containing the files in which
* the user may overwrite.
+ * @param filters The available file filters in the dialog.
* @param defaultName Default filename for the savegame.
* @return The selected File
.
*/
- File showSaveDialog(File directory, String defaultName) {
- if (fileFilters == null) {
- fileFilters = new FileFilter[] {
- FreeColFileFilter.freeColSaveDirectoryFilter,
- };
- }
- return showSaveDialog(directory, fileFilters, defaultName,
- FreeCol.FREECOL_SAVE_EXTENSION);
- }
-
- /**
- * Displays a dialog where the user may choose a filename.
- *
- * @param directory The directory containing the files in which
- * the user may overwrite.
- * @param fileFilters The available file filters in the dialog.
- * @param defaultName Default filename for the savegame.
- * @param extension This extension will be added to the specified
- * filename (if not added by the user).
- * @return The selected File
.
- */
- File showSaveDialog(File directory, FileFilter[] fileFilters,
- String defaultName, String extension) {
+ public File showSaveDialog(File directory, FileFilter[] filters,
+ String defaultName) {
+ if (filters == null) filters = getFileFilters();
return showFreeColDialog(new SaveDialog(freeColClient, frame, directory,
- fileFilters, defaultName,
- extension),
+ filters, defaultName),
null);
}
@@ -2496,7 +2503,7 @@ public final class Canvas extends JDesktopPane {
void showTilePopup(Tile tile, int x, int y) {
if (tile == null)
return;
- TilePopup tp = new TilePopup(freeColClient, mapViewer, tile);
+ TilePopup tp = new TilePopup(freeColClient, this, tile);
if (tp.hasItem()) {
tp.show(this, x, y);
tp.repaint();
@@ -2606,9 +2613,9 @@ public final class Canvas extends JDesktopPane {
} catch (Exception e) {
compact = false;
}
- ReportPanel r
- = getExistingFreeColPanel((compact) ? ReportCompactColonyPanel.class
- : ReportClassicColonyPanel.class);
+ ReportPanel r = (compact)
+ ? getExistingFreeColPanel(ReportCompactColonyPanel.class)
+ : getExistingFreeColPanel(ReportClassicColonyPanel.class);
if (r == null) {
showSubPanel((compact)
? new ReportCompactColonyPanel(freeColClient)
diff --git a/src/net/sf/freecol/client/gui/CanvasMapEditorMouseListener.java b/src/net/sf/freecol/client/gui/CanvasMapEditorMouseListener.java
index 2282600fb..4a3ed2b12 100644
--- a/src/net/sf/freecol/client/gui/CanvasMapEditorMouseListener.java
+++ b/src/net/sf/freecol/client/gui/CanvasMapEditorMouseListener.java
@@ -32,8 +32,8 @@ import javax.swing.JComponent;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.MapEditorController;
-import net.sf.freecol.client.gui.panel.RiverStyleDialog;
import net.sf.freecol.client.gui.panel.MapEditorTransformPanel.TileTypeTransform;
+import net.sf.freecol.client.gui.panel.RiverStyleDialog;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovement;
@@ -48,8 +48,6 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
private static final Logger logger = Logger.getLogger(CanvasMapEditorMouseListener.class.getName());
- private final Canvas canvas;
-
private Point endPoint;
private Point startPoint;
@@ -59,10 +57,8 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
*
* @param canvas The component this object gets created for.
*/
- public CanvasMapEditorMouseListener(FreeColClient freeColClient, Canvas canvas, MapViewer mapViewer) {
- super(freeColClient, mapViewer);
-
- this.canvas = canvas;
+ public CanvasMapEditorMouseListener(FreeColClient freeColClient, Canvas canvas) {
+ super(freeColClient, canvas);
}
@@ -93,10 +89,9 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
*/
private void drawBox(JComponent component,
Point startPoint, Point endPoint) {
- final MapEditorController controller;
if (startPoint == null || endPoint == null
|| startPoint.distance(endPoint) == 0
- || (controller = freeColClient.getMapEditorController()) == null)
+ || freeColClient.getMapEditorController() == null)
return;
Graphics2D graphics = (Graphics2D)component.getGraphics();
@@ -120,7 +115,7 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
try {
if (e.getClickCount() > 1) {
- mapViewer.convertToMapTile(e.getX(), e.getY());
+ canvas.convertToMapTile(e.getX(), e.getY());
} else {
canvas.requestFocus();
}
@@ -138,8 +133,8 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
try {
if (e.getButton() == MouseEvent.BUTTON1) {
- Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
- if (tile != null) getGUI().setSelectedTile(tile, false);
+ Tile tile = canvas.convertToMapTile(e.getX(), e.getY());
+ if (tile != null) getGUI().setSelectedTile(tile);
startPoint = endPoint = null;
} else if (e.getButton() == MouseEvent.BUTTON2) {
@@ -150,7 +145,7 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
} else if (e.getButton() == MouseEvent.BUTTON3
|| e.isPopupTrigger()) {
startPoint = e.getPoint();
- Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
+ Tile tile = canvas.convertToMapTile(e.getX(), e.getY());
if (tile != null) {
if (tile.hasRiver()) {
TileImprovement river = tile.getRiver();
@@ -167,7 +162,7 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
canvas.showEditSettlementDialog(tile.getIndianSettlement());
}
} else {
- getGUI().setSelectedTile(null, false);
+ getGUI().setSelectedTile(null);
}
}
} catch (Exception ex) {
@@ -191,9 +186,9 @@ public final class CanvasMapEditorMouseListener extends AbstractCanvasListener
endPoint = e.getPoint();
if (startPoint == null) startPoint = endPoint;
drawBox(component, startPoint, endPoint);
- Tile start = mapViewer.convertToMapTile(startPoint.x, startPoint.y);
+ Tile start = canvas.convertToMapTile(startPoint.x, startPoint.y);
Tile end = (startPoint == endPoint) ? start
- : mapViewer.convertToMapTile(endPoint.x, endPoint.y);
+ : canvas.convertToMapTile(endPoint.x, endPoint.y);
// edit 2 more conditions in if statement. we need to
// check for coordinator of X and Y if (x,y) outside of
diff --git a/src/net/sf/freecol/client/gui/CanvasMouseListener.java b/src/net/sf/freecol/client/gui/CanvasMouseListener.java
index b471742d0..0772ead8c 100644
--- a/src/net/sf/freecol/client/gui/CanvasMouseListener.java
+++ b/src/net/sf/freecol/client/gui/CanvasMouseListener.java
@@ -49,8 +49,6 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
private final Canvas canvas;
- private final MapViewer mapViewer;
-
private final Timer doubleClickTimer = new Timer(doubleClickDelay,this);
private int centerX, centerY;
@@ -61,14 +59,10 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
*
* @param freeColClient The enclosing FreeColClient
.
* @param canvas The component this object gets created for.
- * @param mapViewer The GUI that holds information such as screen
- * resolution.
*/
- public CanvasMouseListener(FreeColClient freeColClient, Canvas canvas,
- MapViewer mapViewer) {
+ public CanvasMouseListener(FreeColClient freeColClient, Canvas canvas) {
this.freeColClient = freeColClient;
this.canvas = canvas;
- this.mapViewer = mapViewer;
}
/**
@@ -80,7 +74,7 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
public void mouseClicked(MouseEvent e) {
try {
if (e.getClickCount() > 1) {
- Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
+ Tile tile = canvas.convertToMapTile(e.getX(), e.getY());
Colony colony = tile.getColony();
if (colony != null) {
if (FreeColDebugger.isInDebugMode(FreeColDebugger.DebugMode.MENUS)) {
@@ -128,19 +122,19 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
int me = e.getButton();
if (e.isPopupTrigger()) me = MouseEvent.BUTTON3;
- Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
+ Tile tile = canvas.convertToMapTile(e.getX(), e.getY());
switch (me) {
case MouseEvent.BUTTON1:
// Record initial click point for purposes of dragging
- mapViewer.setDragPoint(e.getX(), e.getY());
+ canvas.setDragPoint(e.getX(), e.getY());
if (canvas.isGotoStarted()) {
PathNode path = canvas.getGotoPath();
if (path != null) {
canvas.stopGoto();
// Move the unit
freeColClient.getInGameController()
- .goToTile(mapViewer.getActiveUnit(),
+ .goToTile(canvas.getActiveUnit(),
path.getLastNode().getTile());
}
} else if (doubleClickTimer.isRunning()) {
@@ -154,7 +148,7 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
break;
case MouseEvent.BUTTON2:
if (tile != null) {
- Unit unit = mapViewer.getActiveUnit();
+ Unit unit = canvas.getActiveUnit();
if (unit != null && unit.getTile() != tile) {
PathNode dragPath = unit.findPath(tile);
canvas.startGoto();
@@ -185,7 +179,7 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
canvas.stopGoto();
freeColClient.getInGameController()
- .goToTile(mapViewer.getActiveUnit(),
+ .goToTile(canvas.getActiveUnit(),
temp.getLastNode().getTile());
} else if (canvas.isGotoStarted()) {
@@ -203,9 +197,22 @@ public final class CanvasMouseListener implements ActionListener, MouseListener
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
doubleClickTimer.stop();
- mapViewer.setSelectedTile(mapViewer.convertToMapTile(centerX, centerY),
- true);
+ Tile tile=canvas.convertToMapTile(centerX, centerY);
+ if(canvas.getViewMode() == GUI.MOVE_UNITS_MODE) {
+ // Clear goto order when active unit is on the tile
+ Unit unit=canvas.getActiveUnit();
+ if(unit != null && unit.getTile() == tile) {
+ freeColClient.getInGameController().clearGotoOrders(unit);
+ canvas.updateCurrentPathForActiveUnit();
+ } else {
+ if (tile != null && tile.hasSettlement()) {
+ freeColClient.getGUI().showSettlement(tile.getSettlement());
+ return;
+ }
+ }
+ }
+ freeColClient.getGUI().setSelectedTile(tile);
}
}
diff --git a/src/net/sf/freecol/client/gui/CanvasMouseMotionListener.java b/src/net/sf/freecol/client/gui/CanvasMouseMotionListener.java
index 17da95866..ff1718b4d 100644
--- a/src/net/sf/freecol/client/gui/CanvasMouseMotionListener.java
+++ b/src/net/sf/freecol/client/gui/CanvasMouseMotionListener.java
@@ -19,6 +19,7 @@
package net.sf.freecol.client.gui;
+import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.logging.Logger;
@@ -40,8 +41,6 @@ public final class CanvasMouseMotionListener extends AbstractCanvasListener
/** Number of pixels that must be moved before a goto is enabled. */
private static final int DRAG_THRESHOLD = 16;
- private Canvas canvas;
-
/**
* Temporary variable for checking if we need to recalculate the
* path when dragging units.
@@ -54,9 +53,8 @@ public final class CanvasMouseMotionListener extends AbstractCanvasListener
*
* @param freeColClient The FreeColClient
for the game.
*/
- public CanvasMouseMotionListener(FreeColClient freeColClient, Canvas canvas, MapViewer mapViewer) {
- super(freeColClient, mapViewer);
- this.canvas = canvas;
+ public CanvasMouseMotionListener(FreeColClient freeColClient, Canvas canvas) {
+ super(freeColClient, canvas);
}
@@ -72,15 +70,15 @@ public final class CanvasMouseMotionListener extends AbstractCanvasListener
}
if (canvas.isGotoStarted()) {
- if (mapViewer.getActiveUnit() == null) {
+ if (canvas.getActiveUnit() == null) {
canvas.stopGoto();
}
- Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
+ Tile tile = canvas.convertToMapTile(e.getX(), e.getY());
if (tile != null) {
if (lastTile != tile) {
- Unit active = mapViewer.getActiveUnit();
+ Unit active = canvas.getActiveUnit();
lastTile = tile;
if (active != null && active.getTile() != tile) {
PathNode dragPath = active.findPath(tile);
@@ -103,13 +101,13 @@ public final class CanvasMouseMotionListener extends AbstractCanvasListener
performDragScrollIfActive(e);
- Tile tile = mapViewer.convertToMapTile(e.getX(), e.getY());
+ Tile tile = canvas.convertToMapTile(e.getX(), e.getY());
if (tile != null
&& ((e.getModifiers() & MouseEvent.BUTTON1_MASK)
== MouseEvent.BUTTON1_MASK)) {
// only perform the goto for the left mouse button
if (canvas.isGotoStarted()) {
- Unit active = mapViewer.getActiveUnit();
+ Unit active = canvas.getActiveUnit();
if (active == null) {
canvas.stopGoto();
} else if (lastTile != tile) {
@@ -119,8 +117,9 @@ public final class CanvasMouseMotionListener extends AbstractCanvasListener
}
} else {
// Only start a goto if the drag is 16 pixels or more
- int deltaX = Math.abs(e.getX() - mapViewer.getDragPoint().x);
- int deltaY = Math.abs(e.getY() - mapViewer.getDragPoint().y);
+ Point dragPoint = canvas.getDragPoint();
+ int deltaX = Math.abs(e.getX() - dragPoint.x);
+ int deltaY = Math.abs(e.getY() - dragPoint.y);
if (deltaX >= DRAG_THRESHOLD || deltaY >= DRAG_THRESHOLD) {
canvas.startGoto();
}
diff --git a/src/net/sf/freecol/client/gui/ChatDisplay.java b/src/net/sf/freecol/client/gui/ChatDisplay.java
index fbf0e86f4..32d1dc77f 100644
--- a/src/net/sf/freecol/client/gui/ChatDisplay.java
+++ b/src/net/sf/freecol/client/gui/ChatDisplay.java
@@ -93,7 +93,7 @@ public class ChatDisplay {
if (getMessageCount() > 0) {
// Don't edit the list of messages while I'm drawing them.
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor());
+ FontLibrary.FontSize.TINY, lib.getScaleFactor());
GUIMessage message = getMessage(0);
Image si = lib.getStringImage(
g, message.getMessage(), message.getColor(), font);
diff --git a/src/net/sf/freecol/client/gui/panel/ChoiceItem.java b/src/net/sf/freecol/client/gui/ChoiceItem.java
similarity index 99%
rename from src/net/sf/freecol/client/gui/panel/ChoiceItem.java
rename to src/net/sf/freecol/client/gui/ChoiceItem.java
index e09628f6f..725232dbc 100644
--- a/src/net/sf/freecol/client/gui/panel/ChoiceItem.java
+++ b/src/net/sf/freecol/client/gui/ChoiceItem.java
@@ -17,7 +17,7 @@
* along with FreeCol. If not, see .
*/
-package net.sf.freecol.client.gui.panel;
+package net.sf.freecol.client.gui;
import javax.swing.ImageIcon;
diff --git a/src/net/sf/freecol/client/gui/panel/DialogHandler.java b/src/net/sf/freecol/client/gui/DialogHandler.java
similarity index 81%
rename from src/net/sf/freecol/client/gui/panel/DialogHandler.java
rename to src/net/sf/freecol/client/gui/DialogHandler.java
index d9a4a9837..370a17bde 100644
--- a/src/net/sf/freecol/client/gui/panel/DialogHandler.java
+++ b/src/net/sf/freecol/client/gui/DialogHandler.java
@@ -17,14 +17,14 @@
* along with FreeCol. If not, see .
*/
-package net.sf.freecol.client.gui.panel;
+package net.sf.freecol.client.gui;
/**
- * The base class for non-modal dialog handlers.
+ * The interface for non-modal dialog handlers.
*/
-public abstract class DialogHandler {
+public interface DialogHandler {
- public abstract void handle(T response);
+ void handle(T response);
};
diff --git a/src/net/sf/freecol/client/gui/FontLibrary.java b/src/net/sf/freecol/client/gui/FontLibrary.java
index 163dfe273..ab055c5b0 100644
--- a/src/net/sf/freecol/client/gui/FontLibrary.java
+++ b/src/net/sf/freecol/client/gui/FontLibrary.java
@@ -137,6 +137,18 @@ public class FontLibrary {
return createFont(fontType, fontSize, style, scaleFactor);
}
+ public Font createCompatibleScaledFont(String string, FontType fontType,
+ FontSize fontSize) {
+ return createCompatibleFont(string, fontType, fontSize, Font.PLAIN,
+ scaleFactor);
+ }
+
+ public Font createCompatibleScaledFont(String string, FontType fontType,
+ FontSize fontSize, int style) {
+ return createCompatibleFont(string, fontType, fontSize, style,
+ scaleFactor);
+ }
+
public static Font createFont(FontType fontType, FontSize fontSize) {
return createFont(fontType, fontSize, Font.PLAIN, 1f);
}
@@ -163,6 +175,23 @@ public class FontLibrary {
return createFont(fontType, fontSize, Font.PLAIN, scaleFactor);
}
+ public static Font createCompatibleFont(String string, FontType fontType,
+ FontSize fontSize) {
+ return createCompatibleFont(string, fontType, fontSize, Font.PLAIN, 1f);
+ }
+
+ public static Font createCompatibleFont(String string, FontType fontType,
+ FontSize fontSize, int style) {
+ return createCompatibleFont(string, fontType, fontSize, style, 1f);
+ }
+
+ public static Font createCompatibleFont(String string, FontType fontType,
+ FontSize fontSize,
+ float scaleFactor) {
+ return createCompatibleFont(string, fontType, fontSize, Font.PLAIN,
+ scaleFactor);
+ }
+
/**
* Create a scaled Font
where the scale factor is provided
* explicitly in the parameter.
@@ -179,19 +208,54 @@ public class FontLibrary {
*/
public static Font createFont(FontType fontType, FontSize fontSize,
int style, float scaleFactor) {
- String fontName;
- switch(fontType) {
- default:
- logger.warning("Unknown FontType");
- case NORMAL:
- fontName = (mainFont != null) ? null : "normal";
- break;
- case SIMPLE:
- fontName = "simple";
- break;
- case HEADER:
- fontName = "header";
+ float scaledSize = calcScaledSize(fontSize, scaleFactor);
+ String fontKey = getFontKey(fontType);
+ Font font = (fontKey == null)
+ ? mainFont
+ : ResourceManager.getFont(fontKey);
+ font = font.deriveFont(style, scaledSize);
+ return font;
+ }
+
+ /**
+ * Create a scaled Font
which can display all characters
+ * inside the given text string.
+ * This is mostly necessary for the header font. Thats because the currently
+ * used ShadowedBlack is missing support for CJK and others. Even some
+ * special glyphs for European languages like the triple-dot are missing.
+ *
+ * @param string The text to find a compatible font for.
+ * @param fontType How the font should look like.
+ * @param fontSize Its relative size.
+ * @param style The font style for choosing plain, bold or italic.
+ * @param scaleFactor The applied scale factor.
+ * @return The created Font.
+ */
+ public static Font createCompatibleFont(String string, FontType fontType,
+ FontSize fontSize,
+ int style, float scaleFactor) {
+ // TODO: Consider testing the normal font for compatibility and try
+ // some or all other available fonts for complete/longest match:
+ // header/simple->main->normal->simple/header->emergency
+ float scaledSize = calcScaledSize(fontSize, scaleFactor);
+ String fontKey = getFontKey(fontType);
+ Font font = null;
+ if(fontType != FontType.NORMAL) {
+ font = ResourceManager.getFont(fontKey);
+ if(font.canDisplayUpTo(string) != -1)
+ font = null;
}
+ if(font == null) {
+ fontKey = getFontKey(FontType.NORMAL);
+ font = (fontKey == null)
+ ? mainFont
+ : ResourceManager.getFont(fontKey);
+ }
+ font = font.deriveFont(style, scaledSize);
+ return font;
+ }
+
+ private static float calcScaledSize(FontSize fontSize, float scaleFactor) {
float pixelSize;
switch(fontSize) {
default:
@@ -211,12 +275,24 @@ public class FontLibrary {
case BIG:
pixelSize = 48f;
}
- float scaledSize = pixelSize * scaleFactor;
- Font font = (fontName == null)
- ? mainFont
- : ResourceManager.getFont("font." + fontName);
- font = font.deriveFont(style, scaledSize);
- return font;
+ return pixelSize * scaleFactor;
+ }
+
+ private static String getFontKey(FontType fontType) {
+ String fontName;
+ switch(fontType) {
+ default:
+ logger.warning("Unknown FontType");
+ case NORMAL:
+ fontName = (mainFont != null) ? null : "font.normal";
+ break;
+ case SIMPLE:
+ fontName = "font.simple";
+ break;
+ case HEADER:
+ fontName = "font.header";
+ }
+ return fontName;
}
}
diff --git a/src/net/sf/freecol/client/gui/FreeColFrame.java b/src/net/sf/freecol/client/gui/FreeColFrame.java
index 05faf10b6..95f2d622c 100644
--- a/src/net/sf/freecol/client/gui/FreeColFrame.java
+++ b/src/net/sf/freecol/client/gui/FreeColFrame.java
@@ -20,10 +20,13 @@
package net.sf.freecol.client.gui;
import java.awt.Dimension;
+import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.Toolkit;
+import java.awt.event.ComponentAdapter;
+import java.awt.event.ComponentEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -32,11 +35,15 @@ import javax.swing.JMenuBar;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.menu.FreeColMenuBar;
+import net.sf.freecol.client.gui.menu.InGameMenuBar;
+import net.sf.freecol.client.gui.menu.MapEditorMenuBar;
+import net.sf.freecol.client.gui.menu.MenuMouseMotionListener;
import net.sf.freecol.common.resources.ResourceManager;
/**
- * The base frame for FreeCol panels.
+ * The base frame for FreeCol.
*/
public class FreeColFrame extends JFrame {
@@ -45,6 +52,9 @@ public class FreeColFrame extends JFrame {
/** The FreeCol client controlling the frame. */
protected final FreeColClient freeColClient;
+ /** The Canvas contained inside the frame. */
+ protected final Canvas canvas;
+
/**
* Create a new main frame.
@@ -62,6 +72,7 @@ public class FreeColFrame extends JFrame {
super(getFrameName(), gd.getDefaultConfiguration());
this.freeColClient = freeColClient;
+ this.canvas = canvas;
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
if(windowed) {
setResizable(true);
@@ -73,7 +84,7 @@ public class FreeColFrame extends JFrame {
addWindowListener(windowed
? new WindowedFrameListener(freeColClient)
: new FullScreenFrameListener(freeColClient, this));
- setCanvas(canvas);
+ setCanvas();
setIconImage(ResourceManager.getImage("image.miscicon.FrameIcon"));
pack(); // necessary for getInsets
@@ -88,15 +99,60 @@ public class FreeColFrame extends JFrame {
if (windowed) {
Insets screenInsets = Toolkit.getDefaultToolkit()
.getScreenInsets(gd.getDefaultConfiguration());
- bounds = new Rectangle(0, 0,
- bounds.width - (bounds.x+screenInsets.left+screenInsets.right),
- bounds.height - (bounds.y+screenInsets.top+screenInsets.bottom));
+ bounds = new Rectangle(
+ bounds.x + screenInsets.left,
+ bounds.y + screenInsets.top,
+ bounds.width - screenInsets.right,
+ bounds.height - screenInsets.bottom);
}
}
setBounds(bounds);
logger.info("Frame created in size " + bounds.width + "x" + bounds.height);
+ if (windowed) {
+ addComponentListener(new ComponentAdapter() {
+ @Override
+ public void componentResized(ComponentEvent e) {
+ logger.info("Window size changes to " + getSize());
+ }
+ });
+ }
}
+ public void exitFullScreen() {
+ GraphicsConfiguration GraphicsConf = getGraphicsConfiguration();
+ GraphicsDevice gd = GraphicsConf.getDevice();
+ gd.setFullScreenWindow(null);
+ }
+
+ public void setInGameMenuBar() {
+ setJMenuBar(new InGameMenuBar(freeColClient,
+ new MenuMouseMotionListener(freeColClient, canvas)));
+ validate();
+ }
+
+ public void setMapEditorMenuBar() {
+ setJMenuBar(new MapEditorMenuBar(freeColClient,
+ new MenuMouseMotionListener(freeColClient, canvas)));
+ }
+
+ public void removeMenuBar() {
+ setJMenuBar(null);
+ validate();
+ }
+
+ public void resetMenuBar() {
+ JMenuBar menuBar = getJMenuBar();
+ if (menuBar != null) {
+ ((FreeColMenuBar)menuBar).reset();
+ }
+ }
+
+ public void updateMenuBar() {
+ JMenuBar menuBar = getJMenuBar();
+ if (menuBar != null) {
+ ((FreeColMenuBar)menuBar).update();
+ }
+ }
/**
* Get the standard name for the main frame.
@@ -110,10 +166,8 @@ public class FreeColFrame extends JFrame {
/**
* Set the canvas for this frame.
- *
- * @param canvas The Canvas
to use.
*/
- private void setCanvas(Canvas canvas) {
+ private void setCanvas() {
// This crashes deep in the Java libraries when changing full screen
// mode during the opening video
// Java version: 1.7.0_45
diff --git a/src/net/sf/freecol/client/gui/GUI.java b/src/net/sf/freecol/client/gui/GUI.java
index 0c7a3f6d4..b3cf083b6 100644
--- a/src/net/sf/freecol/client/gui/GUI.java
+++ b/src/net/sf/freecol/client/gui/GUI.java
@@ -19,41 +19,28 @@
package net.sf.freecol.client.gui;
-import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics2D;
-import java.awt.Image;
-import java.awt.Point;
import java.awt.Rectangle;
-import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
-import java.util.Map;
+import java.util.logging.Level;
import java.util.logging.Logger;
-import javax.swing.ImageIcon;
-import javax.swing.JLabel;
-import javax.swing.filechooser.FileFilter;
+import javax.swing.SwingUtilities;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.InGameController;
import net.sf.freecol.client.control.InGameController.*;
-import net.sf.freecol.client.gui.panel.ChoiceItem;
-import net.sf.freecol.client.gui.panel.ColonyPanel;
-import net.sf.freecol.client.gui.panel.ColorChooserPanel;
-import net.sf.freecol.client.gui.panel.FreeColDialog;
-import net.sf.freecol.client.gui.panel.LabourData.UnitData;
-import net.sf.freecol.client.gui.panel.LoadingSavegameDialog;
import net.sf.freecol.client.gui.panel.MiniMap;
import net.sf.freecol.client.gui.panel.Parameters;
-import net.sf.freecol.client.gui.panel.TradeRoutePanel;
-import net.sf.freecol.client.gui.panel.Utility;
import net.sf.freecol.common.FreeColException;
-import net.sf.freecol.common.ServerInfo;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.io.FreeColDirectories;
@@ -74,9 +61,9 @@ import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Monarch.MonarchAction;
+import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.NationSummary;
import net.sf.freecol.common.model.Player;
-import net.sf.freecol.common.model.Region;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Stance;
@@ -84,9 +71,7 @@ import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tension;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TradeRoute;
-import net.sf.freecol.common.model.TypeCountMap;
import net.sf.freecol.common.model.Unit;
-import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.option.Option;
import net.sf.freecol.common.option.OptionGroup;
import net.sf.freecol.common.resources.ResourceManager;
@@ -133,18 +118,10 @@ public class GUI {
return freeColClient.getInGameController();
}
- public Canvas getCanvas() {
- return null;
- }
-
public ImageLibrary getImageLibrary() {
return imageLibrary;
}
- public MapViewer getColonyTileMapViewer() {
- return null;
- }
-
public boolean isWindowed() {
return true;
}
@@ -183,9 +160,9 @@ public class GUI {
/**
* Display the splash screen.
*
- * @param splashFilename The name of the file to find the image in.
+ * @param splashStream A stream to find the image in.
*/
- public void displaySplashScreen(final String splashFilename) {
+ public void displaySplashScreen(final InputStream splashStream) {
}
/**
@@ -213,11 +190,8 @@ public class GUI {
/**
* Change the windowed mode.
- *
- * @param windowed Use true
for windowed mode
- * and false
for fullscreen mode.
*/
- public void changeWindowedMode(boolean windowed) {
+ public void changeWindowedMode() {
}
/**
@@ -241,43 +215,13 @@ public class GUI {
public void clearGotoPath() {
}
- /**
- * Make image icon from an image.
- * Use only if you know having null is possible!
- *
- * @param image The Image
to create an icon for.
- * @return The ImageIcon
.
- */
- public static ImageIcon createImageIcon(Image image) {
- return (image==null) ? null : new ImageIcon(image);
- }
-
- public ImageIcon createUnitImageIcon(Unit unit) {
- return new ImageIcon(imageLibrary.getUnitImage(unit));
- }
-
- public ImageIcon createSettlementImageIcon(Settlement settlement) {
- return new ImageIcon(imageLibrary.getSettlementImage(settlement));
- }
-
- public ImageIcon createGoodsImageIcon(GoodsType goodsType) {
- return new ImageIcon(imageLibrary.getIconImage(goodsType));
- }
-
- /**
- * Make image icon from an object.
- *
- * @param display The FreeColObject to find an icon for.
- * @return The ImageIcon
found.
- */
- protected ImageIcon createObjectImageIcon(FreeColObject display) {
- return (display == null) ? null
- : createImageIcon(imageLibrary.getObjectImage(display, 2f));
- }
-
/**
* Create a thumbnail for the minimap.
*
+ * FIXME: Delete all code inside this method and replace it with
+ * sensible code directly drawing in necessary size,
+ * without creating a throwaway GUI panel, drawing in wrong
+ * size and immediately resizing.
* @return The created image.
*/
public BufferedImage createMiniMapThumbNail() {
@@ -293,8 +237,6 @@ public class GUI {
miniMap.paintMap(g1);
g1.dispose();
- // FIXME: this can probably done more efficiently by applying
- // a suitable AffineTransform to the Graphics2D
int scaledWidth = Math.min((int)((64 * width) / (float)height), 128);
BufferedImage scaledImage = new BufferedImage(scaledWidth, 64,
BufferedImage.TYPE_INT_ARGB);
@@ -323,14 +265,6 @@ public class GUI {
public void refresh() {
}
- /**
- * Refreshes the screen at the specified Tile.
- *
- * @param tile The Tile
to refresh.
- */
- public void refreshTile(Tile tile) {
- }
-
/**
* Reset the menu bar.
*/
@@ -361,8 +295,10 @@ public class GUI {
* Set the active unit.
*
* @param unit The Unit
to activate.
+ * @return true if the focus was set.
*/
- public void setActiveUnit(Unit unit) {
+ public boolean setActiveUnit(Unit unit) {
+ return false;
}
/**
@@ -375,18 +311,15 @@ public class GUI {
// Animation handling
/**
- * Common utility routine to retrieve animation speed.
+ * Require the given tile to be in the onScreen()-area.
*
- * @param unit The Unit
to be animated.
- * @return The animation speed.
+ * @param tile The Tile
to check.
+ * @return True if the focus was set.
*/
- public int getAnimationSpeed(Unit unit) {
- String key = (freeColClient.getMyPlayer() == unit.getOwner())
- ? ClientOptions.MOVE_ANIMATION_SPEED
- : ClientOptions.ENEMY_MOVE_ANIMATION_SPEED;
- return freeColClient.getClientOptions().getInteger(key);
+ public boolean requireFocus(Tile tile) {
+ return false;
}
-
+
/**
* Animate a unit attack.
*
@@ -427,9 +360,6 @@ public class GUI {
public void updateMapControls() {
}
- public void updateMapControlsInCanvas() {
- }
-
public void zoomInMapControls() {
}
@@ -454,7 +384,7 @@ public class GUI {
// Dialogs that return values
/**
- * Simple confirmation dialog.
+ * Simple modal confirmation dialog.
*
* @param textKey A string to use as the message key.
* @param okKey A key for the "ok" button.
@@ -466,51 +396,42 @@ public class GUI {
}
/**
- * General confirmation dialog.
+ * General modal confirmation dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param template The StringTemplate
explaining the choice.
* @param okKey A key for the "ok" button.
* @param cancelKey A key for the "cancel" button.
* @return True if the "ok" button was selected.
*/
- public boolean confirm(boolean modal, Tile tile,
- StringTemplate template,
+ public boolean confirm(Tile tile, StringTemplate template,
String okKey, String cancelKey) {
return false;
}
/**
- * General confirmation dialog.
+ * General modal confirmation dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param template The StringTemplate
explaining the choice.
- * @param obj An optional unit to make an icon for the dialog from.
+ * @param unit An optional unit to make an icon for the dialog from.
* @param okKey A key for the "ok" button.
* @param cancelKey A key for the "cancel" button.
* @return True if the "ok" button was selected.
*/
- public boolean confirm(boolean modal, Tile tile,
- StringTemplate template, Unit obj,
+ public boolean confirm(Tile tile, StringTemplate template, Unit unit,
String okKey, String cancelKey) {
return false;
}
- /**
- * General confirmation dialog.
- *
- * @param modal Is this a modal dialog?
- * @param tile An optional Tile
to expose.
- * @param template The StringTemplate
explaining the choice.
- * @param icon An optional icon for the dialog.
- * @param okKey A key for the "ok" button.
- * @param cancelKey A key for the "cancel" button.
- * @return True if the "ok" button was selected.
- */
- public boolean confirm(boolean modal, Tile tile,
- StringTemplate template, ImageIcon icon,
+ public boolean confirm(Tile tile, StringTemplate template,
+ Settlement settlement,
+ String okKey, String cancelKey) {
+ return false;
+ }
+
+ public boolean confirm(Tile tile, StringTemplate template,
+ GoodsType goodsType,
String okKey, String cancelKey) {
return false;
}
@@ -548,7 +469,7 @@ public class GUI {
.addNamed("%building%", school)
: null;
return template == null
- || confirm(true, unit.getTile(), template, unit,
+ || confirm(unit.getTile(), template, unit,
"abandonEducation.yes", "abandonEducation.no");
}
@@ -567,7 +488,7 @@ public class GUI {
.addStringTemplate("%unit%",
unit.getLabel(Unit.UnitLabelType.NATIONAL))
.addName("%route%", tr.getName());
- return confirm(true, unit.getTile(), template, unit, "yes", "no");
+ return confirm(unit.getTile(), template, unit, "yes", "no");
}
/**
@@ -602,14 +523,14 @@ public class GUI {
int gold = ns.getGold();
if (gold == 0) {
t = StringTemplate.template("confirmTribute.broke")
- .addStringTemplate("%nation%", other.getNationName());
+ .addStringTemplate("%nation%", other.getNationLabel());
showInformationMessage(t);
return -1;
}
int fin = (gold <= 100) ? 0 : (gold <= 1000) ? 1 : 2;
t = StringTemplate.template("confirmTribute.european")
- .addStringTemplate("%nation%", other.getNationName())
+ .addStringTemplate("%nation%", other.getNationLabel())
.addStringTemplate("%danger%",
StringTemplate.template("danger." + levels[mil]))
.addStringTemplate("%finance%",
@@ -666,9 +587,9 @@ public class GUI {
messageId = "confirmHostile.peace";
break;
}
- return confirm(true, attacker.getTile(), StringTemplate
+ return confirm(attacker.getTile(), StringTemplate
.template(messageId)
- .addStringTemplate("%nation%", enemy.getNationName()),
+ .addStringTemplate("%nation%", enemy.getNationLabel()),
attacker, "confirmHostile.yes", "cancel");
}
@@ -710,9 +631,9 @@ public class GUI {
: (is.getAlarm(player).getLevel() == Tension.Level.HAPPY)
? "confirmTribute.happy"
: "confirmTribute.normal";
- return (confirm(true, is.getTile(), StringTemplate.template(messageId)
+ return (confirm(is.getTile(), StringTemplate.template(messageId)
.addName("%settlement%", is.getName())
- .addStringTemplate("%nation%", other.getNationName()),
+ .addStringTemplate("%nation%", other.getNationLabel()),
attacker, "confirmTribute.yes", "confirmTribute.no"))
? 1 : -1;
}
@@ -763,10 +684,9 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("armedUnitSettlement.attack"),
ArmedUnitSettlementAction.SETTLEMENT_ATTACK));
- return getChoice(true, settlement.getTile(),
- Utility.localizedTextArea(settlement.getAlarmLevelLabel(player)),
- new ImageIcon(imageLibrary.getSettlementImage(settlement)),
- "cancel", choices);
+ return getChoice(settlement.getTile(),
+ settlement.getAlarmLevelLabel(player),
+ settlement, "cancel", choices);
}
/**
@@ -792,9 +712,8 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("boycottedGoods.dumpGoods"),
BoycottAction.DUMP_CARGO));
- return getChoice(true, null, Utility.localizedTextArea(template),
- new ImageIcon(imageLibrary.getIconImage(goods.getType())),
- "cancel", choices);
+ return getChoice(null, template,
+ goods.getType(), "cancel", choices);
}
/**
@@ -810,7 +729,7 @@ public class GUI {
public BuyAction getBuyChoice(Unit unit, Settlement settlement,
Goods goods, int gold, boolean canBuy) {
StringTemplate template = StringTemplate.template("buy.text")
- .addStringTemplate("%nation%", settlement.getOwner().getNationName())
+ .addStringTemplate("%nation%", settlement.getOwner().getNationLabel())
.addStringTemplate("%goods%", goods.getLabel(true))
.addAmount("%gold%", gold);
@@ -820,9 +739,8 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("buy.moreGold"),
BuyAction.HAGGLE));
- return getChoice(true, unit.getTile(), Utility.localizedTextArea(template),
- new ImageIcon(imageLibrary.getIconImage(goods.getType())),
- "cancel", choices);
+ return getChoice(unit.getTile(), template,
+ goods.getType(), "cancel", choices);
}
/**
@@ -840,7 +758,7 @@ public class GUI {
StringTemplate template;
if (owner.hasContacted(player)) {
template = StringTemplate.template("indianLand.text")
- .addStringTemplate("%player%", owner.getNationName());
+ .addStringTemplate("%player%", owner.getNationLabel());
StringTemplate pay = StringTemplate.template("indianLand.pay")
.addAmount("%amount%", price);
choices.add(new ChoiceItem<>(Messages.message(pay),
@@ -853,9 +771,8 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("indianLand.take"),
ClaimAction.STEAL));
- return getChoice(true, tile, Utility.localizedTextArea(template),
- new ImageIcon(imageLibrary.getMiscIconImage(owner.getNation())),
- "indianLand.cancel", choices);
+ return getChoice(tile, template,
+ owner.getNation(), "indianLand.cancel", choices);
}
/**
@@ -890,11 +807,8 @@ public class GUI {
}
if (choices.isEmpty()) return null;
- return getChoice(true, settlement.getTile(),
- Utility.localizedTextArea(template),
- new ImageIcon(
- imageLibrary.getSettlementImage(settlement)),
- "cancel", choices);
+ return getChoice(settlement.getTile(), template,
+ settlement, "cancel", choices);
}
/**
@@ -932,11 +846,8 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("missionarySettlement.incite"),
MissionaryAction.INCITE_INDIANS));
- return getChoice(true, unit.getTile(),
- Utility.localizedTextArea(template),
- new ImageIcon(
- imageLibrary.getSettlementImage(settlement)),
- "cancel", choices);
+ return getChoice(unit.getTile(), template,
+ settlement, "cancel", choices);
}
/**
@@ -948,7 +859,7 @@ public class GUI {
*/
public String getNewColonyName(Player player, Tile tile) {
String suggested = player.getSettlementName(null);
- String name = getInput(true, tile, StringTemplate
+ String name = getInput(tile, StringTemplate
.template("nameColony.text"), suggested,
"accept", "cancel");
if (name == null) {
@@ -991,11 +902,8 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("scoutColony.attack"),
ScoutColonyAction.FOREIGN_COLONY_ATTACK));
- return getChoice(true, unit.getTile(),
- Utility.localizedTextArea(template),
- new ImageIcon(
- imageLibrary.getSettlementImage(colony)),
- "cancel", choices);
+ return getChoice(unit.getTile(), template,
+ colony, "cancel", choices);
}
/**
@@ -1016,7 +924,7 @@ public class GUI {
.addName("\n\n")
.addStringTemplate(StringTemplate
.template("scoutSettlement.greetings")
- .addStringTemplate("%nation%", owner.getNationName())
+ .addStringTemplate("%nation%", owner.getNationLabel())
.addName("%settlement%", settlement.getName())
.addName("%number%", numberString)
.add("%settlementType%",
@@ -1053,11 +961,8 @@ public class GUI {
choices.add(new ChoiceItem<>(Messages.message("scoutSettlement.attack"),
ScoutIndianSettlementAction.INDIAN_SETTLEMENT_ATTACK));
- return getChoice(true, settlement.getTile(),
- Utility.localizedTextArea(template),
- new ImageIcon(
- imageLibrary.getSettlementImage(settlement)),
- "cancel", choices);
+ return getChoice(settlement.getTile(), template,
+ settlement, "cancel", choices);
}
/**
@@ -1073,7 +978,7 @@ public class GUI {
Goods goods, int gold) {
StringTemplate goodsTemplate = goods.getLabel(true);
StringTemplate template = StringTemplate.template("sell.text")
- .addStringTemplate("%nation%", settlement.getOwner().getNationName())
+ .addStringTemplate("%nation%", settlement.getOwner().getNationLabel())
.addStringTemplate("%goods%", goodsTemplate)
.addAmount("%gold%", gold);
@@ -1087,35 +992,49 @@ public class GUI {
.addStringTemplate("%goods%", goodsTemplate)),
SellAction.GIFT));
- return getChoice(true, unit.getTile(),
- Utility.localizedTextArea(template),
- new ImageIcon(imageLibrary.getIconImage(goods.getType())),
- "cancel", choices);
+ return getChoice(unit.getTile(), template,
+ goods.getType(), "cancel", choices);
}
/**
- * General choice dialog.
+ * General modal choice dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param explain An object explaining the choice.
- * @param icon An optional icon for the dialog.
* @param cancelKey A key for the "cancel" button.
* @param choices A list a ChoiceItem
s to choose from.
* @return The selected value of the selected ChoiceItem
,
* or null if cancelled.
*/
- public T getChoice(boolean modal, Tile tile, Object explain,
- ImageIcon icon,
+ public T getChoice(Tile tile, Object explain,
+ String cancelKey, List> choices) {
+ return null;
+ }
+
+ public T getChoice(Tile tile, Object explain, Unit unit,
+ String cancelKey, List> choices) {
+ return null;
+ }
+
+ public T getChoice(Tile tile, Object explain, Settlement settlement,
+ String cancelKey, List> choices) {
+ return null;
+ }
+
+ public T getChoice(Tile tile, Object explain, GoodsType goodsType,
+ String cancelKey, List> choices) {
+ return null;
+ }
+
+ public T getChoice(Tile tile, Object explain, Nation nation,
String cancelKey, List> choices) {
return null;
}
/**
- * General input dialog.
+ * General modal string input dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param template A StringTemplate
explaining the choice.
* @param defaultValue The default value to show initially.
@@ -1123,8 +1042,9 @@ public class GUI {
* @param cancelKey A key for the "cancel" button.
* @return The chosen value.
*/
- public String getInput(boolean modal, Tile tile, StringTemplate template,
- String defaultValue, String okKey, String cancelKey) {
+ public String getInput(Tile tile, StringTemplate template,
+ String defaultValue,
+ String okKey, String cancelKey) {
return null;
}
@@ -1141,13 +1061,7 @@ public class GUI {
return false;
}
- public void dialogRemove(FreeColDialog> fcd) {
- }
-
- public void displayObject(FreeColObject fco) {
- }
-
- public LoadingSavegameDialog getLoadingSavegameDialog() {
+ public LoadingSavegameInfo getLoadingSavegameInfo() {
return null;
}
@@ -1172,15 +1086,9 @@ public class GUI {
public void refreshPlayersTable() {
}
- public void removeFromCanvas(Component component) {
- }
-
public void removeInGameComponents() {
}
- public void removeTradeRoutePanel(TradeRoutePanel panel) {
- }
-
public void requestFocusForSubPanel() {
}
@@ -1188,36 +1096,24 @@ public class GUI {
return false;
}
- public void restoreSavedSize(Component comp, int w, int h) {
- }
-
- public void restoreSavedSize(Component comp, Dimension size) {
- }
-
public void returnToTitle() {
}
public void showAboutPanel() {
}
- public void showBuildQueuePanel(Colony colony) {
- }
-
- public void showBuildQueuePanel(Colony colony, Runnable callBack) {
- }
-
public void showCaptureGoodsDialog(final Unit unit, List gl,
- final String defenderId) {
+ DialogHandler> handler) {
}
public void showChatPanel() {
}
- public void showChooseFoundingFatherDialog(final List ffs) {
+ public void showChooseFoundingFatherDialog(final List ffs,
+ DialogHandler handler) {
}
- public OptionGroup showClientOptionsDialog() {
- return null;
+ public void showClientOptionsDialog() {
}
/**
@@ -1242,23 +1138,15 @@ public class GUI {
protected void showForeignColony(Settlement settlement) {
}
- public ColonyPanel showColonyPanel(Colony colony, Unit unit) {
- return null;
+ public void showColonyPanel(Colony colony, Unit unit) {
}
public void showColopediaPanel(String nodeId) {
}
- public ColorChooserPanel showColorChooserPanel(ActionListener al) {
- return null;
- }
-
public void showCompactLabourReport() {
}
- public void showCompactLabourReport(UnitData unitData) {
- }
-
public void showDeclarationPanel() {
}
@@ -1266,23 +1154,21 @@ public class GUI {
return null;
}
- public OptionGroup showDifficultyDialog(Specification spec,
- OptionGroup group) {
- return null;
- }
-
- public void showDumpCargoDialog(Unit unit) {
+ public void showDumpCargoDialog(Unit unit,
+ DialogHandler> handler) {
}
public boolean showEditOptionDialog(Option option) {
return false;
}
- public void showEmigrationDialog(final Player player, final int n,
- final boolean fountainOfYouth) {
+ public void showEmigrationDialog(final Player player,
+ final boolean fountainOfYouth,
+ DialogHandler handler) {
}
- public void showEndTurnDialog(final List units) {
+ public void showEndTurnDialog(final List units,
+ DialogHandler handler) {
}
public void showErrorMessage(StringTemplate template) {
@@ -1360,10 +1246,6 @@ public class GUI {
return null;
}
- public File showLoadDialog(File directory, FileFilter[] fileFilters) {
- return null;
- }
-
final public File showLoadSaveFileDialog() {
File file = showLoadDialog(FreeColDirectories.getSaveDirectory());
if (file != null && !file.isFile()) {
@@ -1396,21 +1278,19 @@ public class GUI {
}
public void showMonarchDialog(final MonarchAction action,
- StringTemplate template, String monarchKey) {
+ StringTemplate template, String monarchKey,
+ DialogHandler handler) {
}
- public void showNameNewLandDialog(String key, final String defaultName,
- final Unit unit) {
- }
-
- public void showNameNewRegionDialog(StringTemplate template,
- final String defaultName,
- final Unit unit, final Tile tile,
- final Region region) {
+ public void showNamingDialog(StringTemplate template,
+ final String defaultName,
+ final Unit unit,
+ DialogHandler handler) {
}
public void showFirstContactDialog(final Player player, final Player other,
- final Tile tile, int settlementCount) {
+ final Tile tile, int settlementCount,
+ DialogHandler handler) {
}
public DiplomaticTrade showNegotiationDialog(FreeColGameObject our,
@@ -1438,12 +1318,6 @@ public class GUI {
return false;
}
- public void showPurchasePanel() {
- }
-
- public void showRecruitPanel() {
- }
-
public void showReportCargoPanel() {
}
@@ -1468,11 +1342,6 @@ public class GUI {
public void showReportIndianPanel() {
}
- public void showReportLabourDetailPanel(UnitType unitType,
- Map> data,
- TypeCountMap unitCount, List colonies) {
- }
-
public void showReportLabourPanel() {
}
@@ -1501,11 +1370,6 @@ public class GUI {
return null;
}
- public File showSaveDialog(File directory, FileFilter[] fileFilters,
- String defaultName, String extension) {
- return null;
- }
-
public Dimension showScaleMapSizeDialog() {
return null;
}
@@ -1524,9 +1388,6 @@ public class GUI {
return null;
}
- public void showServerListPanel(List serverList) {
- }
-
public void showStartGamePanel(Game game, Player player,
boolean singlePlayerMode) {
}
@@ -1537,33 +1398,13 @@ public class GUI {
public void showStatusPanel(String message) {
}
- public void showTilePanel(Tile tile) {
- }
-
public void showTilePopUpAtSelectedTile() {
}
public void showTradeRoutePanel(Unit unit) {
}
- public void showTradeRouteInputPanel(TradeRoute newRoute,
- Runnable callBack) {
- }
-
- public void showTrainPanel() {
- }
-
- public void showVictoryDialog() {
- }
-
- public boolean showWarehouseDialog(Colony colony) {
- return false;
- }
-
- public void showWorkProductionPanel(Unit unit) {
- }
-
- public void updateEuropeanSubpanels() {
+ public void showVictoryDialog(DialogHandler handler) {
}
public void updateGameOptions() {
@@ -1578,15 +1419,6 @@ public class GUI {
public void changeViewMode(int newViewMode) {
}
- public Point calculateUnitLabelPositionInTile(JLabel unitLabel, Point tileP) {
- return null;
- }
-
- public void executeWithUnitOutForAnimation(final Unit unit,
- final Tile sourceTile,
- final OutForAnimationCallback r) {
- }
-
public Unit getActiveUnit() {
return null;
}
@@ -1595,45 +1427,18 @@ public class GUI {
return null;
}
- public float getMapScale() {
- return 1.0f;
- }
-
public Tile getSelectedTile() {
return null;
}
- public Rectangle getTileBounds(Tile tile) {
- return null;
- }
-
- public Point getTilePosition(Tile tile) {
- return null;
- }
-
- public double getTileWidthHeightRatio() {
- return ImageLibrary.TILE_SIZE.width / (double)ImageLibrary.TILE_SIZE.height;
- }
-
public int getViewMode() {
return -1;
}
- public boolean onScreen(Tile tileToCheck) {
- return true; // Lets pretend.
- }
-
- public void restartBlinking() {
- }
-
public void setFocus(Tile tileToFocus) {
}
- public void setFocusImmediately(Tile tileToFocus) {
- }
-
- public boolean setSelectedTile(Tile newTileToSelect,
- boolean clearGoToOrders) {
+ public boolean setSelectedTile(Tile newTileToSelect) {
return true; // Pretending again.
}
@@ -1675,4 +1480,38 @@ public class GUI {
return freeColClient.getSoundController().getSoundMixerLabelText();
}
+ // invoke method forwarding
+
+ /**
+ * Wrapper for SwingUtilities.invokeLater that handles the case
+ * where we are already in the EDT.
+ *
+ * @param runnable A Runnable
to run.
+ */
+ public void invokeNowOrLater(Runnable runnable) {
+ if (SwingUtilities.isEventDispatchThread()) {
+ runnable.run();
+ } else {
+ SwingUtilities.invokeLater(runnable);
+ }
+ }
+
+ /**
+ * Wrapper for SwingUtilities.invokeAndWait that handles the case
+ * where we are already in the EDT.
+ *
+ * @param runnable A Runnable
to run.
+ */
+ public void invokeNowOrWait(Runnable runnable) {
+ if (SwingUtilities.isEventDispatchThread()) {
+ runnable.run();
+ } else {
+ try {
+ SwingUtilities.invokeAndWait(runnable);
+ } catch (InterruptedException | InvocationTargetException ex) {
+ logger.log(Level.WARNING, "Client GUI interaction", ex);
+ }
+ }
+ }
+
}
diff --git a/src/net/sf/freecol/client/gui/ImageLibrary.java b/src/net/sf/freecol/client/gui/ImageLibrary.java
index a1c4883bb..337782fb8 100644
--- a/src/net/sf/freecol/client/gui/ImageLibrary.java
+++ b/src/net/sf/freecol/client/gui/ImageLibrary.java
@@ -32,12 +32,13 @@ import java.awt.RenderingHints;
import java.awt.TexturePaint;
import java.awt.image.BufferedImage;
import java.awt.image.RescaleOp;
-import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
+import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import javax.swing.JComponent;
@@ -79,12 +80,12 @@ public final class ImageLibrary {
/**
* Canonical sizes of images GUI elements and map are expecting
- * in some cases already and current image files have.
- * ATM this is just for documentation.
- * Currently, most images result in a size of image size times scaling
- * factor times requested size. If these canonical sizes would get used
- * in the equation, the game could tolerate changing sizes in the files,
- * without GUI elements sized wrongly, parts cut off or moved unexpectedly.
+ * and current image files have.
+ * ICON_SIZE, TILE_SIZE, TILE_OVERLAY_SIZE and TILE_FOREST_SIZE constants
+ * are used in this way already, allowing them to tolerate changing sizes
+ * in the files.
+ * Most other images are currently still shown in a size of image size
+ * times scaling factor times requested size.
*/
public static final Dimension ICON_SIZE = new Dimension(32, 32),
BUILDING_SIZE = new Dimension(128, 96),
@@ -143,11 +144,13 @@ public final class ImageLibrary {
/**
- * The scaling factor used when creating this
+ * The scale factor used when creating this
* ImageLibrary
. The value 1
is used if
* this object is not a result of a scaling operation.
*/
- private final float scalingFactor;
+ private final float scaleFactor;
+
+ final Dimension tileSize, tileOverlaySize, tileForestSize;
private final HashMap stringImageCache;
@@ -168,11 +171,14 @@ public final class ImageLibrary {
* but this gets multiplied for tiny 0.25(rarely, candidate for removal),
* smaller 0.5, small 0.75 and normal 1.0 image retrieval methods.
*
- * @param scalingFactor The factor used when scaling. 2 is twice
+ * @param scaleFactor The factor used when scaling. 2 is twice
* the size of the original images and 0.5 is half.
*/
- public ImageLibrary(float scalingFactor) {
- this.scalingFactor = scalingFactor;
+ public ImageLibrary(float scaleFactor) {
+ this.scaleFactor = scaleFactor;
+ tileSize = scaleDimension(TILE_SIZE, scaleFactor);
+ tileOverlaySize = scaleDimension(TILE_OVERLAY_SIZE, scaleFactor);
+ tileForestSize = scaleDimension(TILE_FOREST_SIZE, scaleFactor);
stringImageCache = new HashMap<>();
}
@@ -183,8 +189,17 @@ public final class ImageLibrary {
* this object.
* @return The scaling factor of this ImageLibrary.
*/
- public float getScalingFactor() {
- return scalingFactor;
+ public float getScaleFactor() {
+ return scaleFactor;
+ }
+
+ public Dimension scaleDimension(Dimension size) {
+ return scaleDimension(size, scaleFactor);
+ }
+
+ public static Dimension scaleDimension(Dimension size, float scaleFactor) {
+ return new Dimension(Math.round(size.width*scaleFactor),
+ Math.round(size.height*scaleFactor));
}
/**
@@ -246,7 +261,7 @@ public final class ImageLibrary {
public BufferedImage getBeachCornerImage(int index, int x, int y) {
return ResourceManager.getImage("image.tile.model.tile.beach.corner" + index
+ ".r" + ((isEven(x, y)) ? "0" : "1"),
- scalingFactor);
+ tileSize);
}
/**
@@ -260,7 +275,7 @@ public final class ImageLibrary {
public BufferedImage getBeachEdgeImage(int index, int x, int y) {
return ResourceManager.getImage("image.tile.model.tile.beach.edge" + index
+ ".r"+ ((isEven(x, y)) ? "0" : "1"),
- scalingFactor);
+ tileSize);
}
/**
@@ -278,8 +293,8 @@ public final class ImageLibrary {
int x, int y) {
String key = (type == null) ? "model.tile.unexplored" : type.getId();
return ResourceManager.getImage("image.tile." + key + ".border." + direction
- + ".r" + ((isEven(x, y)) ? "0" : "1")
- , scalingFactor);
+ + ".r" + ((isEven(x, y)) ? "0" : "1"),
+ tileSize);
}
/**
@@ -289,18 +304,22 @@ public final class ImageLibrary {
* @return The image at the given index.
*/
public BufferedImage getForestImage(TileType type) {
- return getForestImage(type, scalingFactor);
+ return getForestImage(type, tileForestSize);
}
- public BufferedImage getForestImage(TileType type, TileImprovementStyle riverStyle) {
- return getForestImage(type, riverStyle, scalingFactor);
+ public static BufferedImage getForestImage(TileType type, Dimension size) {
+ return ResourceManager.getImage("image.tileforest." + type.getId(),
+ size);
}
- public static BufferedImage getForestImage(TileType type, float scale) {
- return ResourceManager.getImage("image.tileforest." + type.getId(), scale);
+ public BufferedImage getForestImage(TileType type,
+ TileImprovementStyle riverStyle) {
+ return getForestImage(type, riverStyle, tileForestSize);
}
- public static BufferedImage getForestImage(TileType type, TileImprovementStyle riverStyle, float scale) {
+ public static BufferedImage getForestImage(TileType type,
+ TileImprovementStyle riverStyle,
+ Dimension size) {
if (riverStyle != null) {
String key = "image.tileforest." + type.getId() + ".s" + riverStyle.getMask();
// @compat 0.10.6
@@ -312,9 +331,9 @@ public final class ImageLibrary {
// Consider keeping the fallback, as its safer to have one.
if (ResourceManager.hasImageResource(key))
// end @compat
- return ResourceManager.getImage(key, scale);
+ return ResourceManager.getImage(key, size);
}
- return ResourceManager.getImage("image.tileforest." + type.getId(), scale);
+ return ResourceManager.getImage("image.tileforest." + type.getId(), size);
}
/**
@@ -333,7 +352,7 @@ public final class ImageLibrary {
public BufferedImage getSmallBuildableImage(BuildableType buildable, Player player) {
// FIXME: distinguish national unit types
- float scale = scalingFactor * 0.75f;
+ float scale = scaleFactor * 0.75f;
BufferedImage image = (buildable instanceof BuildingType)
? ImageLibrary.getBuildingImage(
(BuildingType) buildable, player, scale)
@@ -350,18 +369,18 @@ public final class ImageLibrary {
public BufferedImage getSmallBuildingImage(Building building) {
return getBuildingImage(building.getType(), building.getOwner(),
- scalingFactor * 0.75f);
+ scaleFactor * 0.75f);
}
public BufferedImage getBuildingImage(Building building) {
return getBuildingImage(building.getType(), building.getOwner(),
- scalingFactor);
+ scaleFactor);
}
public static BufferedImage getBuildingImage(BuildingType buildingType,
Player player, float scale) {
String key = "image.buildingicon." + buildingType.getId()
- + "." + player.getNationNameKey();
+ + "." + player.getNationResourceKey();
if (!ResourceManager.hasImageResource(key)) {
key = "image.buildingicon." + buildingType.getId();
}
@@ -381,33 +400,30 @@ public final class ImageLibrary {
}
public BufferedImage getSmallerIconImage(FreeColGameObjectType type) {
- return getMiscImage("image.icon." + type.getId(), new Dimension(
- Math.round(scalingFactor * (ICON_SIZE.width * 0.5f)),
- Math.round(scalingFactor * (ICON_SIZE.height * 0.5f))));
+ return getMiscImage("image.icon." + type.getId(),
+ scaleDimension(ICON_SIZE, scaleFactor * 0.5f));
}
public BufferedImage getSmallIconImage(FreeColGameObjectType type) {
- return getMiscImage("image.icon." + type.getId(), new Dimension(
- Math.round(scalingFactor * (ICON_SIZE.width * 0.75f)),
- Math.round(scalingFactor * (ICON_SIZE.height * 0.75f))));
+ return getMiscImage("image.icon." + type.getId(),
+ scaleDimension(ICON_SIZE, scaleFactor * 0.75f));
}
public BufferedImage getIconImage(FreeColGameObjectType type) {
- return getMiscImage("image.icon." + type.getId(), new Dimension(
- Math.round(scalingFactor * ICON_SIZE.width),
- Math.round(scalingFactor * ICON_SIZE.height)));
+ return getMiscImage("image.icon." + type.getId(),
+ scaleDimension(ICON_SIZE, scaleFactor));
}
public BufferedImage getSmallerMiscIconImage(FreeColGameObjectType type) {
- return getMiscIconImage(type, scalingFactor * 0.5f);
+ return getMiscIconImage(type, scaleFactor * 0.5f);
}
public BufferedImage getSmallMiscIconImage(FreeColGameObjectType type) {
- return getMiscIconImage(type, scalingFactor * 0.75f);
+ return getMiscIconImage(type, scaleFactor * 0.75f);
}
public BufferedImage getMiscIconImage(FreeColGameObjectType type) {
- return getMiscIconImage(type, scalingFactor);
+ return getMiscIconImage(type, scaleFactor);
}
public static BufferedImage getMiscIconImage(FreeColGameObjectType type, float scale) {
@@ -425,7 +441,7 @@ public final class ImageLibrary {
* @return The image.
*/
public BufferedImage getMiscImage(String id) {
- return getMiscImage(id, scalingFactor);
+ return getMiscImage(id, scaleFactor);
}
public static BufferedImage getMiscImage(String id, float scale) {
@@ -446,10 +462,8 @@ public final class ImageLibrary {
*/
public BufferedImage getObjectImage(FreeColObject display, float scale) {
try {
- final float combinedScale = scalingFactor * scale;
- final Dimension size = new Dimension(
- Math.round(combinedScale*ICON_SIZE.width),
- Math.round(combinedScale*ICON_SIZE.height));
+ final float combinedScale = scaleFactor * scale;
+ final Dimension size = scaleDimension(ICON_SIZE, combinedScale);
BufferedImage image;
if (display instanceof Goods) {
display = ((Goods)display).getType();
@@ -510,7 +524,7 @@ public final class ImageLibrary {
* @return A pseudo-random terrain image.
*/
public BufferedImage getOverlayImage(Tile tile) {
- return getOverlayImage(tile.getType(), tile.getId(), scalingFactor);
+ return getOverlayImage(tile.getType(), tile.getId(), tileOverlaySize);
}
/**
@@ -519,13 +533,14 @@ public final class ImageLibrary {
*
* @param type The type of the terrain-image to return.
* @param id A string used to get a random image.
- * @param scale The scale of the image to return.
+ * @param size The size of the image to return.
* @return The terrain-image at the given index.
*/
- public static BufferedImage getOverlayImage(TileType type, String id, float scale) {
+ public static BufferedImage getOverlayImage(TileType type, String id,
+ Dimension size) {
String prefix = "image.tileoverlay." + type.getId();
- ArrayList keys = ResourceManager.getImageKeys(prefix);
- return getRandomizedImage(keys, id, scale);
+ List keys = ResourceManager.getImageKeys(prefix);
+ return getRandomizedImage(keys, id, size);
}
public static Set createOverlayCache() {
@@ -533,33 +548,32 @@ public final class ImageLibrary {
}
public BufferedImage getOverlayImage(Tile tile, Set overlayCache) {
- return getOverlayImage(tile.getType(), tile.getId(), scalingFactor,
+ return getOverlayImage(tile.getType(), tile.getId(), tileOverlaySize,
overlayCache);
}
- public static BufferedImage getOverlayImage(TileType type, String id, float scale,
- Set overlayCache) {
- String prefix = "image.tileoverlay." + type.getId() + ".r";
- ArrayList keys = new ArrayList<>();
- for (String key : overlayCache) {
- if (key.startsWith(prefix)) {
- keys.add(key);
- }
- }
- return getRandomizedImage(keys, id, scale);
+ public static BufferedImage getOverlayImage(TileType type, String id,
+ Dimension size,
+ Set overlayCache) {
+ final String prefix = "image.tileoverlay." + type.getId() + ".r";
+ final List keys = overlayCache.stream()
+ .filter(k -> k.startsWith(prefix))
+ .collect(Collectors.toList());
+ return getRandomizedImage(keys, id, size);
}
- private static BufferedImage getRandomizedImage(ArrayList keys, String id, float scale) {
+ private static BufferedImage getRandomizedImage(List keys,
+ String id, Dimension size) {
int count = keys.size();
switch(count) {
case 0:
return null;
case 1:
- return ResourceManager.getImage(keys.get(0), scale);
+ return ResourceManager.getImage(keys.get(0), size);
default:
Collections.sort(keys);
return ResourceManager.getImage(
- keys.get(Math.abs(id.hashCode() % count)), scale);
+ keys.get(Math.abs(id.hashCode() % count)), size);
}
}
@@ -614,29 +628,19 @@ public final class ImageLibrary {
* @return The image with the given style.
*/
public BufferedImage getRiverImage(TileImprovementStyle style) {
- return getRiverImage(style, scalingFactor);
+ return getRiverImage(style.getString(), tileSize);
}
/**
* Returns the river image with the given style.
*
- * @param style a TileImprovementStyle
value
- * @param scale a double
value
+ * @param style the style code
+ * @param size the image size
* @return The image with the given style.
*/
- public static BufferedImage getRiverImage(TileImprovementStyle style, float scale) {
- return getRiverImage(style.getString(), scale);
- }
-
- /**
- * Returns the river image with the given style.
- *
- * @param style a String
value
- * @param scale a double
value
- * @return The image with the given style.
- */
- public static BufferedImage getRiverImage(String style, float scale) {
- return ResourceManager.getImage("image.tile.model.improvement.river.s" + style, scale);
+ public static BufferedImage getRiverImage(String style, Dimension size) {
+ return ResourceManager.getImage(
+ "image.tile.model.improvement.river.s" + style, size);
}
/**
@@ -654,11 +658,11 @@ public final class ImageLibrary {
int x, int y) {
String key = "image.tile.model.tile.delta." + direction
+ (magnitude == 1 ? ".small" : ".large");
- return ResourceManager.getImage(key, scalingFactor);
+ return ResourceManager.getImage(key, tileSize);
}
public BufferedImage getSmallSettlementImage(Settlement settlement) {
- return getSettlementImage(settlement, scalingFactor * 0.75f);
+ return getSettlementImage(settlement, scaleFactor * 0.75f);
}
/**
@@ -668,7 +672,7 @@ public final class ImageLibrary {
* @return The graphics that will represent the given settlement.
*/
public BufferedImage getSettlementImage(Settlement settlement) {
- return getSettlementImage(settlement, scalingFactor);
+ return getSettlementImage(settlement, scaleFactor);
}
/**
@@ -694,7 +698,7 @@ public final class ImageLibrary {
* @return The graphics that will represent the given settlement.
*/
public BufferedImage getSettlementImage(SettlementType settlementType) {
- return getSettlementImage(settlementType, scalingFactor);
+ return getSettlementImage(settlementType, scaleFactor);
}
public static BufferedImage getSettlementImage(SettlementType settlementType,
@@ -703,19 +707,6 @@ public final class ImageLibrary {
scale);
}
- /**
- * Get a tile size for displaying the colony tiles.
- *
- * @param tile The Tile
to get the size for.
- * @return The tile size.
- */
- public Dimension calculateTileSize(Tile tile) {
- final TileType tileType = tile.getType();
- final BufferedImage image = getTerrainImage(tileType,
- tile.getX(), tile.getY());
- return new Dimension(image.getWidth(), image.getHeight());
- }
-
/**
* Returns the terrain-image for the given type.
*
@@ -727,38 +718,39 @@ public final class ImageLibrary {
* @return The terrain-image at the given index.
*/
public BufferedImage getTerrainImage(TileType type, int x, int y) {
- return getTerrainImage(type, x, y, scalingFactor);
+ return getTerrainImage(type, x, y, tileSize);
}
- public static BufferedImage getTerrainImage(TileType type, int x, int y, float scale) {
+ public static BufferedImage getTerrainImage(TileType type, int x, int y,
+ Dimension size) {
String key = (type == null) ? "model.tile.unexplored" : type.getId();
return ResourceManager.getImage("image.tile." + key + ".center.r"
- + (isEven(x, y) ? "0" : "1"), scale);
+ + (isEven(x, y) ? "0" : "1"), size);
}
public BufferedImage getSmallerUnitImage(Unit unit) {
return getUnitImage(unit.getType(), unit.getRole().getId(),
- unit.hasNativeEthnicity(), false, scalingFactor * 0.5f);
+ unit.hasNativeEthnicity(), false, scaleFactor * 0.5f);
}
public BufferedImage getSmallUnitImage(Unit unit) {
return getUnitImage(unit.getType(), unit.getRole().getId(),
- unit.hasNativeEthnicity(), false, scalingFactor * 0.75f);
+ unit.hasNativeEthnicity(), false, scaleFactor * 0.75f);
}
public BufferedImage getSmallUnitImage(Unit unit, boolean grayscale) {
return getUnitImage(unit.getType(), unit.getRole().getId(),
- unit.hasNativeEthnicity(), grayscale, scalingFactor * 0.75f);
+ unit.hasNativeEthnicity(), grayscale, scaleFactor * 0.75f);
}
public BufferedImage getUnitImage(Unit unit) {
return getUnitImage(unit.getType(), unit.getRole().getId(),
- unit.hasNativeEthnicity(), false, scalingFactor);
+ unit.hasNativeEthnicity(), false, scaleFactor);
}
public BufferedImage getUnitImage(Unit unit, boolean grayscale) {
return getUnitImage(unit.getType(), unit.getRole().getId(),
- unit.hasNativeEthnicity(), grayscale, scalingFactor);
+ unit.hasNativeEthnicity(), grayscale, scaleFactor);
}
public static BufferedImage getUnitImage(Unit unit, float scale) {
@@ -768,38 +760,38 @@ public final class ImageLibrary {
public BufferedImage getTinyUnitImage(UnitType unitType) {
return getUnitImage(unitType, unitType.getDisplayRoleId(),
- false, false, scalingFactor * 0.25f);
+ false, false, scaleFactor * 0.25f);
}
public BufferedImage getTinyUnitImage(UnitType unitType, boolean grayscale) {
return getUnitImage(unitType, unitType.getDisplayRoleId(),
- false, grayscale, scalingFactor * 0.25f);
+ false, grayscale, scaleFactor * 0.25f);
}
public BufferedImage getSmallerUnitImage(UnitType unitType) {
return getUnitImage(unitType, unitType.getDisplayRoleId(),
- false, false, scalingFactor * 0.5f);
+ false, false, scaleFactor * 0.5f);
}
public BufferedImage getSmallUnitImage(UnitType unitType) {
return getUnitImage(unitType, unitType.getDisplayRoleId(),
- false, false, scalingFactor * 0.75f);
+ false, false, scaleFactor * 0.75f);
}
public BufferedImage getSmallUnitImage(UnitType unitType, boolean grayscale) {
return getUnitImage(unitType, unitType.getDisplayRoleId(),
- false, grayscale, scalingFactor * 0.75f);
+ false, grayscale, scaleFactor * 0.75f);
}
public BufferedImage getSmallUnitImage(UnitType unitType, String roleId,
boolean grayscale) {
return getUnitImage(unitType, roleId,
- false, grayscale, scalingFactor * 0.75f);
+ false, grayscale, scaleFactor * 0.75f);
}
public BufferedImage getUnitImage(UnitType unitType) {
return getUnitImage(unitType, unitType.getDisplayRoleId(),
- false, false, scalingFactor);
+ false, false, scaleFactor);
}
public static BufferedImage getUnitImage(UnitType unitType, float scale) {
@@ -890,10 +882,7 @@ public final class ImageLibrary {
JComponent c, Insets insets) {
int width = c.getWidth();
int height = c.getHeight();
- BufferedImage image = ResourceManager.hasImageResource(resource)
- ? ResourceManager.getImage(resource) : null;
- int dx, dy, xmin, ymin;
-
+ int xmin, ymin;
if (insets == null) {
xmin = 0;
ymin = 0;
@@ -903,11 +892,13 @@ public final class ImageLibrary {
width -= insets.left + insets.right;
height -= insets.top + insets.bottom;
}
- if (image != null && (dx = image.getWidth()) > 0
- && (dy = image.getHeight()) > 0) {
- int xmax, ymax;
- xmax = xmin + width;
- ymax = ymin + height;
+
+ if (ResourceManager.hasImageResource(resource)) {
+ BufferedImage image = ResourceManager.getImage(resource);
+ int dx = image.getWidth();
+ int dy = image.getHeight();
+ int xmax = xmin + width;
+ int ymax = ymin + height;
for (int x = xmin; x < xmax; x += dx) {
for (int y = ymin; y < ymax; y += dy) {
g.drawImage(image, x, y, null);
@@ -1020,9 +1011,9 @@ public final class ImageLibrary {
private BufferedImage createChip(Graphics2D g, String text, Color border,
Color background, Color foreground) {
Font font = FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.TINY, Font.BOLD, scalingFactor);
+ FontLibrary.FontSize.TINY, Font.BOLD, scaleFactor);
FontMetrics fm = g.getFontMetrics(font);
- int padding = (int)(6 * scalingFactor);
+ int padding = (int)(6 * scaleFactor);
BufferedImage bi = new BufferedImage(fm.stringWidth(text) + padding,
fm.getMaxAscent() + fm.getMaxDescent() + padding,
BufferedImage.TYPE_INT_ARGB);
@@ -1057,9 +1048,9 @@ public final class ImageLibrary {
double amount, Color fill,
Color foreground) {
Font font = FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.TINY, Font.BOLD, scalingFactor);
+ FontLibrary.FontSize.TINY, Font.BOLD, scaleFactor);
FontMetrics fm = g.getFontMetrics(font);
- int padding = (int)(6 * scalingFactor);
+ int padding = (int)(6 * scaleFactor);
BufferedImage bi = new BufferedImage(fm.stringWidth(text) + padding,
fm.getMaxAscent() + fm.getMaxDescent() + padding,
BufferedImage.TYPE_INT_ARGB);
diff --git a/src/net/sf/freecol/client/gui/LoadingSavegameInfo.java b/src/net/sf/freecol/client/gui/LoadingSavegameInfo.java
new file mode 100644
index 000000000..7beb3f8ff
--- /dev/null
+++ b/src/net/sf/freecol/client/gui/LoadingSavegameInfo.java
@@ -0,0 +1,64 @@
+/**
+ * Copyright (C) 2002-2015 The FreeCol Team
+ *
+ * This file is part of FreeCol.
+ *
+ * FreeCol is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * FreeCol is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with FreeCol. If not, see .
+ */
+
+package net.sf.freecol.client.gui;
+
+/**
+ * Used for transferring data for the savegame to be loaded.
+*/
+public class LoadingSavegameInfo {
+
+ private final boolean singlePlayer;
+ private final int port;
+ private final String serverName;
+
+ public LoadingSavegameInfo(boolean singlePlayer, int port, String serverName) {
+ this.singlePlayer=singlePlayer;
+ this.port=port;
+ this.serverName=serverName;
+ }
+
+ /**
+ * Is a single player game selected?
+ *
+ * @return True if single player is selected.
+ */
+ public boolean isSinglePlayer() {
+ return singlePlayer;
+ }
+
+ /**
+ * Get the selected port number.
+ *
+ * @return The port number.
+ */
+ public int getPort() {
+ return port;
+ }
+
+ /**
+ * Get the specified server name.
+ *
+ * @return The server name.
+ */
+ public String getServerName() {
+ return serverName;
+ }
+
+}
diff --git a/src/net/sf/freecol/client/gui/MapViewer.java b/src/net/sf/freecol/client/gui/MapViewer.java
index 183856961..b5dedd737 100644
--- a/src/net/sf/freecol/client/gui/MapViewer.java
+++ b/src/net/sf/freecol/client/gui/MapViewer.java
@@ -19,20 +19,16 @@
package net.sf.freecol.client.gui;
-import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
-import java.awt.Composite;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics2D;
-import java.awt.Image;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
@@ -40,13 +36,11 @@ import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
+import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
@@ -55,42 +49,34 @@ import javax.swing.JLayeredPane;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.common.debug.DebugUtils;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.BuildableType;
import net.sf.freecol.common.model.Colony;
-import net.sf.freecol.common.model.ColonyTile;
-import net.sf.freecol.common.model.Game;
-import net.sf.freecol.common.model.GameOptions;
-import net.sf.freecol.common.model.IndianSettlement;
-import net.sf.freecol.common.model.LostCityRumour;
-import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Direction;
+import net.sf.freecol.common.model.FreeColGameObject;
+import net.sf.freecol.common.model.Game;
+import net.sf.freecol.common.model.IndianSettlement;
+import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.PathNode;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Region;
-import net.sf.freecol.common.model.Resource;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Tile;
-import net.sf.freecol.common.model.TileImprovement;
-import net.sf.freecol.common.model.TileItem;
-import net.sf.freecol.common.model.TileType;
import net.sf.freecol.common.model.Turn;
import net.sf.freecol.common.model.Unit;
-import net.sf.freecol.common.resources.ResourceManager;
-import net.sf.freecol.common.util.Utils;
import static net.sf.freecol.common.util.StringUtils.*;
/**
+ * MapViewer is a private helper class of Canvas and SwingGUI.
+ *
* This class is responsible for drawing the map/background on the
* Canvas
.
- *
* In addition, the graphical state of the map (focus, active unit..)
- * is also a responsibility of this class.
+ * is currently handled by this class.
*/
public final class MapViewer {
@@ -98,7 +84,6 @@ public final class MapViewer {
private static enum BorderType { COUNTRY, REGION }
-
private static class TextSpecification {
public final String text;
@@ -110,67 +95,24 @@ public final class MapViewer {
}
}
- private static class SortableImage implements Comparable {
-
- public final Image image;
- public final int index;
-
- public SortableImage(Image image, int index) {
- this.image = image;
- this.index = index;
- }
-
- // Implement Comparable
-
- @Override
- public int compareTo(SortableImage other) {
- return other.index - this.index;
- }
-
- // Override Object
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean equals(Object other) {
- if (other instanceof SortableImage) {
- return this.compareTo((SortableImage)other) == 0;
- }
- return super.equals(other);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int hashCode() {
- int hash = super.hashCode();
- hash = 37 * hash + Utils.hashCode(image);
- return 37 * hash + index;
- }
- }
private final FreeColClient freeColClient;
- private final GUI gui;
+ private final SwingGUI gui;
private Dimension size;
/** Scaled ImageLibrary only used for map painting. */
private ImageLibrary lib;
- private RoadPainter rp;
+ private final TileViewer tv;
private TerrainCursor cursor;
- private volatile boolean blinkingMarqueeEnabled;
private Tile selectedTile;
private Tile focus = null;
private Unit activeUnit;
- private Unit savedActiveUnit;
-
/** The view mode in use. */
private int viewMode = 0;
@@ -180,7 +122,6 @@ public final class MapViewer {
/** A path for a current goto order. */
private PathNode gotoPath = null;
private boolean gotoStarted = false;
- private Point gotoDragPoint;
// Helper variables for displaying the map.
private int tileHeight, tileWidth, halfHeight, halfWidth,
@@ -221,19 +162,11 @@ public final class MapViewer {
// The height offset to paint a Unit at (in pixels).
private static final int UNIT_OFFSET = 20,
- STATE_OFFSET_X = 25,
- STATE_OFFSET_Y = 10,
OTHER_UNITS_OFFSET_X = -5, // Relative to the state indicator.
OTHER_UNITS_OFFSET_Y = 1,
OTHER_UNITS_WIDTH = 3,
MAX_OTHER_UNITS = 10;
- public static final int OVERLAY_INDEX = 100;
- public static final int FOREST_INDEX = 200;
-
- private GeneralPath gridPath = null;
- private final GeneralPath fog = new GeneralPath();
-
private final java.util.Map unitsOutForAnimation;
private final java.util.Map unitsOutForAnimationLabels;
@@ -256,19 +189,28 @@ public final class MapViewer {
*/
MapViewer(FreeColClient freeColClient) {
this.freeColClient = freeColClient;
- this.gui = freeColClient.getGUI();
+ this.gui = (SwingGUI)freeColClient.getGUI();
this.size = null;
+ tv = new TileViewer(freeColClient);
setImageLibraryAndUpdateData(new ImageLibrary());
cursor = null;
- blinkingMarqueeEnabled = false;
unitsOutForAnimation = new HashMap<>();
unitsOutForAnimationLabels = new HashMap<>();
}
+ /**
+ * Gets the contained ImageLibrary
.
+ *
+ * @return The image library;
+ */
+ ImageLibrary getImageLibrary() {
+ return lib;
+ }
+
/**
* Get the view mode.
*
@@ -295,51 +237,20 @@ public final class MapViewer {
logger.fine("Changed to " + ((newViewMode == GUI.MOVE_UNITS_MODE)
? "Move Units" : "View Terrain") + " mode");
viewMode = newViewMode;
+ if(viewMode == GUI.MOVE_UNITS_MODE)
+ restartBlinking();
+ else
+ stopBlinking();
+ if(activeUnit != null) {
+ Tile tile = activeUnit.getTile();
+ if(isTileVisible(tile))
+ gui.refreshTile(tile);
+ if(selectedTile != tile && isTileVisible(selectedTile))
+ gui.refreshTile(selectedTile);
+ } else if(isTileVisible(selectedTile))
+ gui.refreshTile(selectedTile);
+ gui.updateMapControls();
}
-
- switch (viewMode) {
- case GUI.MOVE_UNITS_MODE:
- if (getActiveUnit() == null) setActiveUnit(savedActiveUnit);
- savedActiveUnit = null;
- break;
- case GUI.VIEW_TERRAIN_MODE:
- savedActiveUnit = activeUnit;
- setActiveUnit(null);
- break;
- default:
- break;
- }
- }
-
-
- /**
- * Get the current active unit path.
- *
- * @return The current PathNode
.
- */
- PathNode getCurrentPath() {
- return this.currentPath;
- }
-
- /**
- * Set the current active unit path.
- *
- * @param path The current PathNode
.
- */
- void setCurrentPath(PathNode path) {
- this.currentPath = path;
- }
-
- /**
- * Sets the path of the active unit to display it.
- */
- void updateCurrentPathForActiveUnit() {
- setCurrentPath((activeUnit == null
- || activeUnit.getDestination() == null
- || Map.isSameLocation(activeUnit.getLocation(),
- activeUnit.getDestination()))
- ? null
- : activeUnit.findPath(activeUnit.getDestination()));
}
/**
@@ -347,7 +258,7 @@ public final class MapViewer {
*/
void centerActiveUnit() {
if (activeUnit != null && activeUnit.getTile() != null) {
- setFocus(activeUnit.getTile());
+ gui.setFocus(activeUnit.getTile());
}
}
@@ -460,215 +371,6 @@ public final class MapViewer {
}
-
- private int calculateHeightForTileWithOverlayAndForest(
- TileType tileType, int height, Image overlayImage) {
- int compoundHeight = height;
- if (tileType != null) {
- int tmpHeight;
- if (overlayImage != null) {
- tmpHeight = overlayImage.getHeight(null);
- if(tmpHeight > compoundHeight)
- compoundHeight = tmpHeight;
- }
- if (tileType.isForested()) {
- tmpHeight = lib.getForestImage(tileType).getHeight(null);
- if(tmpHeight > compoundHeight)
- compoundHeight = tmpHeight;
- }
- }
- return compoundHeight;
- }
-
- /**
- * Displays the given Tile onto the given Graphics2D object at the
- * location specified by the coordinates. Draws the terrain and
- * improvements. Doesn't draw settlements, lost city rumours, fog
- * of war, optional values neither units.
- *
- * The same as calling displayTile(g, map, tile, x, y, true);
.
- *
- * @param tile The Tile to draw.
- * @return The image.
- */
- public BufferedImage createTileImageWithBeachBorderAndItems(Tile tile) {
- final TileType tileType = tile.getType();
- final Image terrain = lib.getTerrainImage(
- tileType, tile.getX(), tile.getY());
- Image overlayImage = lib.getOverlayImage(tile);
- final int width = terrain.getWidth(null);
- final int height = terrain.getHeight(null);
- final int compoundHeight = calculateHeightForTileWithOverlayAndForest(
- tileType, height, overlayImage);
- BufferedImage image = new BufferedImage(
- width, compoundHeight, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = image.createGraphics();
- g.translate(0, compoundHeight - height);
- displayTileWithBeachAndBorder(g, lib, tile, true);
- displayTileItems(g, tile, overlayImage);
- g.dispose();
- return image;
- }
-
- /**
- * Returns the scaled terrain-image for a terrain type (and position 0, 0).
- *
- * @param type The type of the terrain-image to return.
- * @param scale The scale of the terrain image to return.
- * @return The terrain-image
- */
- public static Image createTileImageWithOverlayAndForest(TileType type, float scale) {
- Image terrainImage = ImageLibrary.getTerrainImage(type, 0, 0, scale);
- Image overlayImage = ImageLibrary.getOverlayImage(type, type.getId(), scale);
- Image forestImage = type.isForested() ? ImageLibrary.getForestImage(type, scale) : null;
- if (overlayImage == null && forestImage == null) {
- return terrainImage;
- } else {
- int width = terrainImage.getWidth(null);
- int height = terrainImage.getHeight(null);
- if (overlayImage != null) {
- height = Math.max(height, overlayImage.getHeight(null));
- }
- if (forestImage != null) {
- height = Math.max(height, forestImage.getHeight(null));
- }
- BufferedImage compositeImage = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = compositeImage.createGraphics();
- g.drawImage(terrainImage, 0, height - terrainImage.getHeight(null), null);
- if (overlayImage != null) {
- g.drawImage(overlayImage, 0, height - overlayImage.getHeight(null), null);
- }
- if (forestImage != null) {
- g.drawImage(forestImage, 0, height - forestImage.getHeight(null), null);
- }
- g.dispose();
- return compositeImage;
- }
- }
-
- /**
- * Create a BufferedImage
and draw a Tile
on it.
- * The visualization of the Tile
also includes information
- * from the corresponding ColonyTile
of the given
- * Colony
.
- *
- * @param tile The Tile
to draw.
- * @param colony The Colony
to create the visualization
- * of the Tile
for. This object is also used to
- * get the ColonyTile
for the given Tile
.
- * @return The image.
- */
- public BufferedImage createColonyTileImage(Tile tile, Colony colony) {
- final TileType tileType = tile.getType();
- final Image terrain = lib.getTerrainImage(
- tileType, tile.getX(), tile.getY());
- final int width = terrain.getWidth(null);
- final int height = terrain.getHeight(null);
- Image overlayImage = lib.getOverlayImage(tile);
- final int compoundHeight = calculateHeightForTileWithOverlayAndForest(
- tileType, height, overlayImage);
- BufferedImage image = new BufferedImage(
- width, compoundHeight, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = image.createGraphics();
- g.translate(0, compoundHeight - height);
- displayColonyTile(g, tile, colony, overlayImage);
- g.dispose();
- return image;
- }
-
- /**
- * Displays the 3x3 tiles for the TilesPanel in ColonyPanel.
- *
- * @param g The Graphics2D
object on which to draw
- * the Tile
.
- * @param tiles The array containing the Tile
objects to draw.
- * @param colony The Colony
to create the visualization
- * of the Tile
objects for.
- */
- public void displayColonyTiles(Graphics2D g, Tile[][] tiles, Colony colony) {
- Set overlayCache = ImageLibrary.createOverlayCache();
- final Tile tile = colony.getTile();
- Dimension tileSize = lib.calculateTileSize(tile);
- for (int x = 0; x < 3; x++) {
- for (int y = 0; y < 3; y++) {
- if (tiles[x][y] != null) {
- int xx = (((2 - x) + y) * tileSize.width) / 2;
- int yy = ((x + y) * tileSize.height) / 2;
- g.translate(xx, yy);
- Image overlayImage = lib.getOverlayImage(tiles[x][y], overlayCache);
- displayColonyTile(g, tiles[x][y], colony, overlayImage);
- g.translate(-xx, -yy);
- }
- }
- }
- }
-
- /**
- * Displays the given Tile
onto the given
- * Graphics2D
object at the location specified
- * by the coordinates. The visualization of the Tile
- * also includes information from the corresponding
- * ColonyTile
from the given Colony
.
- *
- * @param g The Graphics2D
object on which to draw
- * the Tile
.
- * @param tile The Tile
to draw.
- * @param colony The Colony
to create the visualization
- * of the Tile
for. This object is also used to
- * get the ColonyTile
for the given Tile
.
- * @param overlayImage The Image for the tile overlay.
- */
- private void displayColonyTile(Graphics2D g, Tile tile, Colony colony,
- Image overlayImage) {
- boolean tileCannotBeWorked = false;
- Unit unit = null;
- int price = 0;
- if (colony != null) {
- ColonyTile colonyTile = colony.getColonyTile(tile);
- unit = colonyTile.getOccupyingUnit();
- price = colony.getOwner().getLandPrice(tile);
- switch (colonyTile.getNoWorkReason()) {
- case NONE: case COLONY_CENTER: case CLAIM_REQUIRED:
- break;
- default:
- tileCannotBeWorked = true;
- }
- }
-
- displayTileWithBeachAndBorder(g, lib, tile, false);
- if (tile != null && tile.isExplored()) {
- displayTileItems(g, tile, overlayImage);
- displaySettlementWithChipsOrPopulationNumber(freeColClient, lib,
- g, tile, tileWidth, tileHeight, false);
- displayFogOfWar(freeColClient, fog, g, tile);
- displayOptionalTileTextAndRegionBorder(g, tile);
- }
-
- if (tileCannotBeWorked) {
- g.drawImage(lib.getMiscImage(ImageLibrary.TILE_TAKEN),
- 0, 0, null);
- }
-
- if (price > 0 && tile != null && !tile.hasSettlement()) {
- Image image = lib.getMiscImage(ImageLibrary.TILE_OWNED_BY_INDIANS);
- displayCenteredImage(g, image, tileWidth, tileHeight);
- }
-
- if (unit != null) {
- BufferedImage image = lib.getSmallerUnitImage(unit);
- g.drawImage(image,
- tileWidth/4 - image.getWidth() / 2,
- halfHeight - image.getHeight() / 2, null);
- // Draw an occupation and nation indicator.
- Player owner = freeColClient.getMyPlayer();
- String text = Messages.message(unit.getOccupationLabel(owner, false));
- g.drawImage(lib.getOccupationIndicatorChip(g, unit, text),
- (int)(STATE_OFFSET_X * lib.getScalingFactor()),
- 0, null);
- }
- }
-
/**
* Run some code with the given unit made invisible. You can nest
* several of these method calls in order to hide multiple
@@ -680,8 +382,8 @@ public final class MapViewer {
* @param r The code to be executed.
*/
void executeWithUnitOutForAnimation(final Unit unit,
- final Tile sourceTile,
- final OutForAnimationCallback r) {
+ final Tile sourceTile,
+ final OutForAnimationCallback r) {
final JLabel unitLabel = enterUnitOutForAnimation(unit, sourceTile);
try {
r.executeWithUnitOutForAnimation(unitLabel);
@@ -690,92 +392,76 @@ public final class MapViewer {
}
}
- /**
- * Force the next screen repaint to reposition the tiles on the window.
- */
- void forceReposition() {
- bottomRow = -1;
+ private JLabel enterUnitOutForAnimation(final Unit unit,
+ final Tile sourceTile) {
+ Integer i = unitsOutForAnimation.get(unit);
+ if (i == null) {
+ final JLabel unitLabel = createUnitLabel(unit);
+
+ i = 1;
+ unitLabel.setLocation(calculateUnitLabelPositionInTile(
+ unitLabel.getWidth(), unitLabel.getHeight(),
+ calculateTilePosition(sourceTile)));
+ unitsOutForAnimationLabels.put(unit, unitLabel);
+ gui.getCanvas().add(unitLabel, JLayeredPane.DEFAULT_LAYER);
+ } else {
+ i++;
+ }
+ unitsOutForAnimation.put(unit, i);
+ return unitsOutForAnimationLabels.get(unit);
+ }
+
+ private void releaseUnitOutForAnimation(final Unit unit) {
+ Integer i = unitsOutForAnimation.get(unit);
+ if (i == null) {
+ throw new IllegalStateException("Tried to release unit that was not out for animation");
+ }
+ if (i == 1) {
+ unitsOutForAnimation.remove(unit);
+ gui.getCanvas().removeFromCanvas(unitsOutForAnimationLabels.remove(unit));
+ } else {
+ i--;
+ unitsOutForAnimation.put(unit, i);
+ }
}
/**
- * Gets the active unit.
+ * Returns true if the given Unit is being animated.
*
- * @return The Unit
.
- * @see #setActiveUnit
+ * @param unit an Unit
+ * @return a boolean
*/
- Unit getActiveUnit() {
- return activeUnit;
- }
-
- TerrainCursor getCursor() {
- return cursor;
+ private boolean isOutForAnimation(final Unit unit) {
+ return unitsOutForAnimation.containsKey(unit);
}
/**
- * Gets the point at which the map was clicked for a drag.
+ * Draw the unit's image and occupation indicator in one JLabel object.
*
- * @return The Point where the mouse was initially clicked.
+ * @param unit The unit to be drawn
+ * @return A JLabel object with the unit's image.
*/
- Point getDragPoint() {
- return gotoDragPoint;
- }
+ private JLabel createUnitLabel(Unit unit) {
+ final BufferedImage unitImg = lib.getUnitImage(unit);
+ final int width = halfWidth + unitImg.getWidth()/2;
+ final int height = unitImg.getHeight();
- /**
- * Gets the focus of the map. That is the center tile of the displayed
- * map.
- *
- * @return The center tile of the displayed map
- * @see #setFocus(Tile)
- */
- Tile getFocus() {
- return focus;
- }
+ BufferedImage img = new BufferedImage(width, height,
+ BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = img.createGraphics();
- /**
- * Gets the path to be drawn on the map.
- *
- * @return The path that should be drawn on the map or
- * null
if no path should be drawn.
- */
- PathNode getGotoPath() {
- return gotoPath;
- }
+ final int unitX = (width - unitImg.getWidth()) / 2;
+ g.drawImage(unitImg, unitX, 0, null);
- /**
- * Gets the contained ImageLibrary
.
- *
- * @return The image library;
- */
- public ImageLibrary getImageLibrary() {
- return lib;
- }
+ Player player = freeColClient.getMyPlayer();
+ String text = Messages.message(unit.getOccupationLabel(player, false));
+ g.drawImage(lib.getOccupationIndicatorChip(g, unit, text), 0, 0, null);
- /**
- * Get the current scale of the map.
- *
- * @return The current map scale.
- */
- public float getMapScale() {
- return lib.getScalingFactor();
- }
+ final JLabel label = new JLabel(new ImageIcon(img));
+ label.setSize(width, height);
- /**
- * Get the size of this GUI.
- *
- * @return The size of this GUI.
- */
- Dimension getSize() {
- return size;
- }
-
- /**
- * Gets the selected tile.
- *
- * @return The Tile
selected.
- * @see #setSelectedTile(Tile, boolean)
- */
- Tile getSelectedTile() {
- return selectedTile;
+ g.dispose();
+ return label;
}
/**
@@ -821,45 +507,32 @@ public final class MapViewer {
return new Point(x, y);
}
- /**
- * Get the ratio of width/height of tiles on the map.
- *
- * @return The ratio.
- */
- double getTileWidthHeightRatio() {
- return tileWidth / (double)tileHeight;
+ int getTileWidth() {
+ return tileWidth;
}
/**
* Gets the position where a unitLabel located at tile should be drawn.
*
- * @param unitLabel The unit label with the unit's image and
- * occupation indicator drawn.
+ * @param labelWidth The width of the unit label.
+ * @param labelHeight The width of the unit label.
* @param tileP The position of the Tile on the screen.
* @return The position where to put the label, null if tileP is null.
*/
- Point calculateUnitLabelPositionInTile(JLabel unitLabel, Point tileP) {
+ Point calculateUnitLabelPositionInTile(int labelWidth,int labelHeight,
+ Point tileP) {
if (tileP != null) {
int labelX = tileP.x + tileWidth
- / 2 - unitLabel.getWidth() / 2;
+ / 2 - labelWidth / 2;
int labelY = tileP.y + tileHeight
- / 2 - unitLabel.getHeight() / 2
- - (int) (UNIT_OFFSET * lib.getScalingFactor());
+ / 2 - labelHeight / 2
+ - (int) (UNIT_OFFSET * lib.getScaleFactor());
return new Point(labelX, labelY);
} else {
return null;
}
}
- /**
- * Checks if there is currently a goto operation on the mapboard.
- *
- * @return True if a goto operation is in progress.
- */
- boolean isGotoStarted() {
- return gotoStarted;
- }
-
/**
* Checks if the Tile/Units at the given coordinates are displayed
* on the screen (or, if the map is already displayed and the focus
@@ -879,92 +552,38 @@ public final class MapViewer {
&& (tileToCheck.getX() + 2 < rightColumn || alignedRight);
}
+ /**
+ * Starts the unit-selection-cursor blinking animation.
+ */
+ void startCursorBlinking() {
+ cursor = new TerrainCursor();
+ cursor.addActionListener((ActionEvent ae) -> {
+ Unit unit = activeUnit;
+ if (unit != null) {
+ Tile tile = unit.getTile();
+ if (isTileVisible(tile)) gui.refreshTile(tile);
+ }
+ });
+ cursor.startBlinking();
+ }
+
+ void stopBlinking() {
+ cursor.stopBlinking();
+ }
+
void restartBlinking() {
- blinkingMarqueeEnabled = true;
+ cursor.startBlinking();
}
/**
- * Scroll the map in the given direction.
+ * Gets the focus of the map. That is the center tile of the displayed
+ * map.
*
- * @param direction The Direction
to scroll in.
- * @return True if scrolling occurred.
+ * @return The center tile of the displayed map
+ * @see #setFocus(Tile)
*/
- boolean scrollMap(Direction direction) {
- Tile t = getFocus();
- if (t == null) return false;
- int fx = t.getX(), fy = t.getY();
- if ((t = t.getNeighbourOrNull(direction)) == null) return false;
- int tx = t.getX(), ty = t.getY();
- int x, y;
-
- // When already close to an edge, resist moving the focus closer,
- // but if moving away immediately jump out of the `nearTo' area.
- if (isMapNearTop(ty) && isMapNearTop(fy)) {
- y = (ty <= fy) ? fy : topRows;
- } else if (isMapNearBottom(ty) && isMapNearBottom(fy)) {
- y = (ty >= fy) ? fy : freeColClient.getGame().getMap().getWidth()
- - bottomRows;
- } else {
- y = ty;
- }
- if (isMapNearLeft(tx, ty) && isMapNearLeft(fx, fy)) {
- x = (tx <= fx) ? fx : getLeftColumns(ty);
- } else if (isMapNearRight(tx, ty) && isMapNearRight(fx, fy)) {
- x = (tx >= fx) ? fx : freeColClient.getGame().getMap().getWidth()
- - getRightColumns(ty);
- } else {
- x = tx;
- }
-
- if (x == fx && y == fy) return false;
- setFocus(freeColClient.getGame().getMap().getTile(x,y));
- return true;
- }
-
- /**
- * Sets the active unit.
- *
- * Invokes {@link #setSelectedTile(Tile, boolean)} if the selected
- * tile is another tile than where the activeUnit
is located.
- *
- * @param activeUnit The new active Unit
.
- * @return True if the focus was set.
- * @see #setSelectedTile(Tile, boolean)
- */
- boolean setActiveUnit(Unit activeUnit) {
- // Don't select a unit with zero moves left. -sjm
- // The user might what to check the status of a unit - SG
- Tile tile = (activeUnit == null) ? null : activeUnit.getTile();
- this.activeUnit = activeUnit;
-
- // The user activated a unit
- if (getViewMode() == GUI.VIEW_TERRAIN_MODE && activeUnit != null) {
- changeViewMode(GUI.MOVE_UNITS_MODE);
- }
-
- if (activeUnit == null || tile == null) {
- gui.getCanvas().stopGoto();
- freeColClient.updateActions();
- } else {
- updateCurrentPathForActiveUnit();
- if (!setSelectedTile(tile, false)
- || freeColClient.getClientOptions()
- .getBoolean(ClientOptions.JUMP_TO_ACTIVE_UNIT)) {
- setFocus(tile);
- return true;
- }
- }
- return false;
- }
-
- /**
- * Sets the point at which the map was clicked for a drag.
- *
- * @param x The mouse's x position.
- * @param y The mouse's y position.
- */
- void setDragPoint(int x, int y) {
- gotoDragPoint = new Point(x, y);
+ Tile getFocus() {
+ return focus;
}
/**
@@ -976,33 +595,6 @@ public final class MapViewer {
*/
void setFocus(Tile focus) {
this.focus = focus;
-
- gui.refresh();
- }
-
- /**
- * Sets the focus of the map and repaints the screen immediately.
- *
- * @param focus The Position
of the center tile of the
- * displayed map.
- * @see #getFocus
- */
- void setFocusImmediately(Tile focus) {
- this.focus = focus;
-
- forceReposition();
- }
-
- /**
- * Sets the path to be drawn on the map.
- *
- * Dont use this directly, call the method in canvas!
- *
- * @param gotoPath The path that should be drawn on the map
- * or null
if no path should be drawn.
- */
- void setGotoPath(PathNode gotoPath) {
- this.gotoPath = gotoPath;
forceReposition();
}
@@ -1024,7 +616,7 @@ public final class MapViewer {
final int tx = tile.getX(), ty = tile.getY(),
width = rightColumn - leftColumn;
int moveX = -1;
- setFocus(tile);
+ gui.setFocus(tile);
positionMap(tile);
if (leftColumn <= 0) { // At left edge already
if (tx <= width / 4) {
@@ -1050,1556 +642,21 @@ public final class MapViewer {
}
if (moveX >= 0) {
Tile other = map.getTile(moveX, ty);
- setFocus(other);
+ gui.setFocus(other);
positionMap(other);
}
return where;
}
/**
- * Selects the tile at the specified position. There are three
- * possible cases:
- *
- *
- * - If there is a {@link Colony} on the {@link Tile} the
- * {@link Canvas#showColonyPanel} will be invoked.
- *
- If the tile contains a unit that can become active, then
- * that unit will be set as the active unit, and clear their
- * goto orders if clearGoToOrders is
true
- * - If the two conditions above do not match, then the
- *
selectedTile
will become the map focus.
- *
- *
- * If a unit is active and is located on the selected tile,
- * then nothing (except perhaps a map reposition) will happen.
- *
- * @param newTile The Tile
, the tile to be selected
- * @param clearGoToOrders Use true
to clear goto
- * orders of the unit which is activated
- * @return True if the focus was set.
- * @see #getSelectedTile
- * @see #setActiveUnit
- * @see #setFocus(Tile)
+ * Force the next screen repaint to reposition the tiles on the window.
*/
- boolean setSelectedTile(Tile newTile, boolean clearGoToOrders) {
- Tile oldTile = this.selectedTile;
- boolean ret = false;
- selectedTile = newTile;
-
- if (getViewMode() == GUI.MOVE_UNITS_MODE) {
- if (isNoActiveUnitAt(newTile)) {
- if (newTile != null && newTile.hasSettlement()) {
- gui.showSettlement(newTile.getSettlement());
- return false;
- }
-
- // else, just select a unit on the selected tile
- Unit unitInFront = findUnitInFront(newTile);
- if (unitInFront != null) {
- ret = setActiveUnit(unitInFront);
- updateCurrentPathForActiveUnit();
- } else {
- setFocus(newTile);
- ret = true;
- }
- } else {
- // Clear goto order when unit is already active
- if (clearGoToOrders) {
- freeColClient.getInGameController().clearGotoOrders(activeUnit);
- updateCurrentPathForActiveUnit();
- }
- }
- }
-
- freeColClient.updateActions();
- gui.updateMenuBar();
-
- gui.updateMapControls();
-
- // Check for refocus
- if (!onScreen(newTile)
- || freeColClient.getClientOptions().getBoolean(ClientOptions.ALWAYS_CENTER)) {
- setFocus(newTile);
- ret = true;
- } else {
- if (oldTile != null) {
- gui.refreshTile(oldTile);
- }
-
- if (newTile != null) {
- gui.refreshTile(newTile);
- }
- }
- return ret;
+ void forceReposition() {
+ bottomRow = -1;
}
- void setSize(Dimension size) {
- this.size = size;
- updateMapDisplayVariables();
- }
-
- /**
- * Starts the unit-selection-cursor blinking animation.
- */
- void startCursorBlinking() {
- blinkingMarqueeEnabled = true;
-
- ActionListener taskPerformer = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (!blinkingMarqueeEnabled) return;
- Unit unit = getActiveUnit();
- if (unit != null) {
- Tile tile = unit.getTile();
- if (isTileVisible(tile)) {
- gui.refreshTile(tile);
- }
- }
- }
- };
-
- cursor = new net.sf.freecol.client.gui.TerrainCursor();
- cursor.addActionListener(taskPerformer);
- cursor.startBlinking();
- }
-
- /**
- * Starts a goto operation on the mapboard.
- *
- * Dont use this directly, call the method in canvas!
- */
- void startGoto() {
- gotoStarted = true;
- setGotoPath(null);
- }
-
- void stopBlinking() {
- blinkingMarqueeEnabled = false;
- }
-
- /**
- * Stops any ongoing goto operation on the mapboard.
- *
- * Dont use this directly, call the method in canvas!
- */
- void stopGoto() {
- setGotoPath(null);
- updateCurrentPathForActiveUnit();
- gotoStarted = false;
- }
-
- /**
- * Reset the scale of the map to the default.
- */
- void resetMapScale() {
- setImageLibraryAndUpdateData(new ImageLibrary());
- updateMapDisplayVariables();
- }
-
- boolean isAtMaxMapScale() {
- return lib.getScalingFactor() == MAP_SCALE_MAX;
- }
-
- boolean isAtMinMapScale() {
- return lib.getScalingFactor() == MAP_SCALE_MIN;
- }
-
- void increaseMapScale() {
- float newScale = lib.getScalingFactor() + MAP_SCALE_STEP;
- if (newScale >= MAP_SCALE_MAX)
- newScale = MAP_SCALE_MAX;
- setImageLibraryAndUpdateData(new ImageLibrary(newScale));
- updateMapDisplayVariables();
- }
-
- void decreaseMapScale() {
- float newScale = lib.getScalingFactor() - MAP_SCALE_STEP;
- if (newScale <= MAP_SCALE_MIN)
- newScale = MAP_SCALE_MIN;
- setImageLibraryAndUpdateData(new ImageLibrary(newScale));
- updateMapDisplayVariables();
- }
-
- /**
- * Centers the given Image on the tile.
- *
- * @param g a Graphics2D
- * @param image an Image
- */
- private static void displayCenteredImage(Graphics2D g, Image image,
- int tileWidth, int tileHeight) {
- g.drawImage(image,
- (tileWidth - image.getWidth(null))/2,
- (tileHeight - image.getHeight(null))/2,
- null);
- }
-
- /**
- * Draws the pentagram indicating a native capital.
- */
- private static BufferedImage createCapitalLabel(int extent, int padding,
- Color backgroundColor) {
- // create path
- double deg2rad = Math.PI/180.0;
- double angle = -90.0 * deg2rad;
- double offset = extent * 0.5;
- double size1 = (extent - padding - padding) * 0.5;
-
- GeneralPath path = new GeneralPath();
- path.moveTo(Math.cos(angle) * size1 + offset, Math.sin(angle) * size1 + offset);
- for (int i = 0; i < 4; i++) {
- angle += 144 * deg2rad;
- path.lineTo(Math.cos(angle) * size1 + offset, Math.sin(angle) * size1 + offset);
- }
- path.closePath();
-
- // draw everything
- BufferedImage bi = new BufferedImage(extent, extent, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = bi.createGraphics();
- g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.setColor(backgroundColor);
- g.fill(new RoundRectangle2D.Float(0, 0, extent, extent, padding, padding));
- g.setColor(Color.BLACK);
- g.setStroke(new BasicStroke(2.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
- g.draw(path);
- g.setColor(Color.WHITE);
- g.fill(path);
- g.dispose();
- return bi;
- }
-
-
- /**
- * Creates an BufferedImage that shows the given text centred on a
- * translucent rounded rectangle with the given color.
- *
- * @param g a Graphics2D
- * @param text a String
- * @param font a Font
- * @param backgroundColor a Color
- * @return an BufferedImage
- */
- private BufferedImage createLabel(Graphics2D g, String text, Font font,
- Color backgroundColor) {
- TextSpecification[] specs = new TextSpecification[1];
- specs[0] = new TextSpecification(text, font);
- return createLabel(g, specs, backgroundColor);
- }
-
- /**
- * Creates an BufferedImage that shows the given text centred on a
- * translucent rounded rectangle with the given color.
- *
- * @param g a Graphics2D
- * @param textSpecs a TextSpecification
array
- * @param backgroundColor a Color
- * @return a BufferedImage
- */
- private BufferedImage createLabel(Graphics2D g, TextSpecification[] textSpecs,
- Color backgroundColor) {
- int hPadding = 15;
- int vPadding = 10;
- int linePadding = 5;
- int width = 0;
- int height = vPadding;
- int i;
-
- TextSpecification spec;
- TextLayout[] labels = new TextLayout[textSpecs.length];
- TextLayout label;
-
- for (i = 0; i < textSpecs.length; i++) {
- spec = textSpecs[i];
- label = new TextLayout(spec.text, spec.font, g.getFontRenderContext());
- labels[i] = label;
- Rectangle textRectangle = label.getPixelBounds(null, 0, 0);
- width = Math.max(width, textRectangle.width + hPadding);
- if (i > 0) height += linePadding;
- height += (int) (label.getAscent() + label.getDescent());
- }
-
- int radius = Math.min(hPadding, vPadding);
-
- BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g2 = bi.createGraphics();
- g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
- g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
-
- g2.setColor(backgroundColor);
- g2.fill(new RoundRectangle2D.Float(0, 0, width, height, radius, radius));
- g2.setColor(ImageLibrary.getForegroundColor(backgroundColor));
- float y = vPadding / 2;
- for (i = 0; i < labels.length; i++) {
- Rectangle textRectangle = labels[i].getPixelBounds(null, 0, 0);
- float x = (width - textRectangle.width) / 2;
- y += labels[i].getAscent();
- labels[i].draw(g2, x, y);
- y += labels[i].getDescent() + linePadding;
- }
- g2.dispose();
- return bi;
- }
-
- /**
- * Draws a cross indicating a religious mission is present in the
- * native village.
- */
- private static BufferedImage createReligiousMissionLabel(int extent,
- int padding, Color backgroundColor, boolean expertMissionary) {
- // create path
- double offset = extent * 0.5;
- double size1 = extent - padding - padding;
- double bar = size1 / 3.0;
- double inset = 0.0;
- double kludge = 0.0;
-
- GeneralPath circle = new GeneralPath();
- GeneralPath cross = new GeneralPath();
- if (expertMissionary) {
- // this is meant to represent the eucharist (the -1, +1 thing is a nasty kludge)
- circle.append(new Ellipse2D.Double(padding-1, padding-1, size1+1, size1+1), false);
- inset = 4.0;
- bar = (size1 - inset - inset) / 3.0;
- // more nasty -1, +1 kludges
- kludge = 1.0;
- }
- offset -= 1.0;
- cross.moveTo(offset, padding + inset - kludge);
- cross.lineTo(offset, extent - padding - inset);
- cross.moveTo(offset - bar, padding + bar + inset);
- cross.lineTo(offset + bar + 1, padding + bar + inset);
-
- // draw everything
- BufferedImage bi = new BufferedImage(extent, extent, BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = bi.createGraphics();
- g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
- g.setColor(backgroundColor);
- g.fill(new RoundRectangle2D.Float(0, 0, extent, extent, padding, padding));
- g.setColor(ImageLibrary.getForegroundColor(backgroundColor));
- if (expertMissionary) {
- g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
- g.draw(circle);
- g.setStroke(new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
- } else {
- g.setStroke(new BasicStroke(2.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
- }
- g.draw(cross);
- g.dispose();
- return bi;
- }
-
- /**
- * Displays the given Tile onto the given Graphics2D object at the
- * location specified by the coordinates. Only base terrain will be drawn.
- *
- * @param g The Graphics2D object on which to draw the Tile.
- * @param library The ImageLibrary
to use.
- * @param tile The Tile to draw.
- * @param drawUnexploredBorders If true; draws border between explored and
- * unexplored terrain.
- */
- private static void displayTileWithBeachAndBorder(Graphics2D g,
- ImageLibrary library,
- Tile tile,
- boolean drawUnexploredBorders) {
- if (tile != null) {
- int x = tile.getX();
- int y = tile.getY();
- // ATTENTION: we assume that all base tiles have the same size
- g.drawImage(library.getTerrainImage(tile.getType(), x, y),
- 0, 0, null);
- if (tile.isExplored()) {
- if (!tile.isLand() && tile.getStyle() > 0) {
- int edgeStyle = tile.getStyle() >> 4;
- if (edgeStyle > 0) {
- g.drawImage(library.getBeachEdgeImage(edgeStyle, x, y),
- 0, 0, null);
- }
- int cornerStyle = tile.getStyle() & 15;
- if (cornerStyle > 0) {
- g.drawImage(library.getBeachCornerImage(cornerStyle, x, y),
- 0, 0, null);
- }
- }
-
- List imageBorders = new ArrayList<>(8);
- SortableImage si;
- for (Direction direction : Direction.values()) {
- Tile borderingTile = tile.getNeighbourOrNull(direction);
- if (borderingTile != null) {
-
- if (!drawUnexploredBorders && !borderingTile.isExplored() &&
- (direction == Direction.SE || direction == Direction.S ||
- direction == Direction.SW)) {
- continue;
- }
-
- if (tile.getType() == borderingTile.getType()) {
- // Equal tiles, no need to draw border
- } else if (tile.isLand() && !borderingTile.isLand()) {
- // The beach borders are drawn on the side of water tiles only
- } else if (!tile.isLand() && borderingTile.isLand() && borderingTile.isExplored()) {
- // If there is a Coast image (eg. beach) defined, use it, otherwise skip
- // Draw the grass from the neighboring tile, spilling over on the side of this tile
- si = new SortableImage(library.getBorderImage(borderingTile.getType(), direction, x, y),
- borderingTile.getType().getIndex());
- imageBorders.add(si);
- TileImprovement river = borderingTile.getRiver();
- if (river != null && river.isConnectedTo(direction.getReverseDirection())) {
- si = new SortableImage(library.getRiverMouthImage(direction, borderingTile
- .getRiver().getMagnitude(), x, y),
- -1);
- imageBorders.add(si);
- }
- } else if (borderingTile.isExplored()) {
- if (library.getTerrainImage(tile.getType(), 0, 0)
- .equals(library.getTerrainImage(borderingTile.getType(), 0, 0))) {
- // Do not draw limit between tile that share same graphics (ocean & great river)
- } else if (borderingTile.getType().getIndex() < tile.getType().getIndex()) {
- // Draw land terrain with bordering land type, or ocean/high seas limit
- si = new SortableImage(library.getBorderImage(borderingTile.getType(), direction,
- x, y), borderingTile.getType().getIndex());
- imageBorders.add(si);
- }
- }
- }
- }
- Collections.sort(imageBorders);
- for (SortableImage sorted : imageBorders) {
- g.drawImage(sorted.image, 0, 0, null);
- }
- }
- }
- }
-
- /**
- * Displays the given Tile onto the given Graphics2D object at the
- * location specified by the coordinates. Fog of war will be
- * drawn.
- *
- * @param g The Graphics2D
object on which to draw
- * the Tile
.
- * @param tile The Tile
to draw.
- */
- private static void displayFogOfWar(FreeColClient freeColClient,
- GeneralPath fog, Graphics2D g, Tile tile) {
- if (freeColClient.getGame() != null
- && freeColClient.getGame().getSpecification()
- .getBoolean(GameOptions.FOG_OF_WAR)
- && freeColClient.getMyPlayer() != null
- && !freeColClient.getMyPlayer().canSee(tile)) {
- g.setColor(Color.BLACK);
- Composite oldComposite = g.getComposite();
- g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
- 0.2f));
- g.fill(fog);
- g.setComposite(oldComposite);
- }
- }
-
-
- /**
- * Display a path.
- *
- * @param g The Graphics2D
to display on.
- * @param path The PathNode
to display.
- */
- private void displayPath(Graphics2D g, PathNode path) {
- final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor());
- final boolean debug = FreeColDebugger
- .isInDebugMode(FreeColDebugger.DebugMode.PATHS);
-
- for (PathNode p = path; p != null; p = p.next) {
- Tile tile = p.getTile();
- if (tile == null) continue;
- Point point = calculateTilePosition(tile);
- if (point == null) continue;
-
- Image image = (p.isOnCarrier())
- ? ImageLibrary.getPathImage(ImageLibrary.PathType.NAVAL)
- : (activeUnit != null)
- ? ImageLibrary.getPathImage(activeUnit)
- : null;
-
- Image turns = (p.getTurns() <= 0) ? null
- : lib.getStringImage(g, Integer.toString(p.getTurns()),
- Color.WHITE, font);
- g.setColor((turns == null) ? Color.GREEN : Color.RED);
-
- if (debug) { // More detailed display
- if (activeUnit != null) {
- image = ImageLibrary.getPathNextTurnImage(activeUnit);
- }
- turns = lib.getStringImage(g, Integer.toString(p.getTurns())
- + "/" + Integer.toString(p.getMovesLeft()),
- Color.WHITE, font);
- }
-
- g.translate(point.x, point.y);
- if (image == null) {
- g.fillOval(halfWidth, halfHeight, 10, 10);
- g.setColor(Color.BLACK);
- g.drawOval(halfWidth, halfHeight, 10, 10);
- } else {
- displayCenteredImage(g, image, tileWidth, tileHeight);
- if (turns != null)
- displayCenteredImage(g, turns, tileWidth, tileHeight);
- }
- g.translate(-point.x, -point.y);
- }
- }
-
- /**
- * Displays the Map onto the given Graphics2D object. The Tile at
- * location (x, y) is displayed in the center.
- *
- * @param g The Graphics2D object on which to draw the Map.
- */
- void displayMap(Graphics2D g) {
- final ClientOptions options = freeColClient.getClientOptions();
- final Player player = freeColClient.getMyPlayer();
- AffineTransform originTransform = g.getTransform();
- Rectangle clipBounds = g.getClipBounds();
- Map map = freeColClient.getGame().getMap();
- FontLibrary fontLibrary = new FontLibrary(lib.getScalingFactor());
-
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_ON);
-
- /*
- PART 1
- ======
- Position the map if it is not positioned yet.
- */
-
- repositionMapIfNeeded();
-
- /*
- PART 1a
- =======
- Determine which tiles need to be redrawn.
- */
- int firstRow = (clipBounds.y - topRowY) / (halfHeight) - 1;
- int clipTopY = topRowY + firstRow * (halfHeight);
- firstRow = topRow + firstRow;
-
- int firstColumn = (clipBounds.x - leftColumnX) / tileWidth - 1;
- int clipLeftX = leftColumnX + firstColumn * tileWidth;
- firstColumn = leftColumn + firstColumn;
-
- int lastRow = (clipBounds.y + clipBounds.height - topRowY)
- / (halfHeight);
- lastRow = topRow + lastRow;
-
- int lastColumn = (clipBounds.x + clipBounds.width - leftColumnX)
- / tileWidth;
- lastColumn = leftColumn + lastColumn;
-
- /*
- PART 1b
- =======
- Create a GeneralPath to draw the grid with, if needed.
- */
- if (options.getBoolean(ClientOptions.DISPLAY_GRID)) {
- gridPath = new GeneralPath();
- gridPath.moveTo(0, 0);
- int nextX = halfWidth;
- int nextY = -halfHeight;
-
- for (int i = 0; i <= ((lastColumn - firstColumn) * 2 + 1); i++) {
- gridPath.lineTo(nextX, nextY);
- nextX += halfWidth;
- nextY = (nextY == 0 ? -halfHeight : 0);
- }
- }
-
- /*
- PART 2
- ======
- Display the Tiles and the Units.
- */
-
- g.setColor(Color.black);
- g.fillRect(clipBounds.x, clipBounds.y,
- clipBounds.width, clipBounds.height);
-
- /*
- PART 2a
- =======
- Display the base Tiles
- */
- g.translate(clipLeftX, clipTopY);
- AffineTransform baseTransform = g.getTransform();
- AffineTransform rowTransform = null;
-
- // Row per row; start with the top modified row
- for (int row = firstRow; row <= lastRow; row++) {
- rowTransform = g.getTransform();
- if ((row & 1) == 1) {
- g.translate(halfWidth, 0);
- }
-
- // Column per column; start at the left side to display the tiles.
- for (int column = firstColumn; column <= lastColumn; column++) {
- Tile tile = map.getTile(column, row);
- displayTileWithBeachAndBorder(g, lib, tile, true);
- g.translate(tileWidth, 0);
- }
- g.setTransform(rowTransform);
- g.translate(0, halfHeight);
- }
- g.setTransform(baseTransform);
-
- /*
- PART 2b
- =======
- Display the Tile overlays and Units
- */
-
- List units = new ArrayList<>();
- List unitTransforms = new ArrayList<>();
- List settlements = new ArrayList<>();
- List settlementTransforms = new ArrayList<>();
- Set overlayCache = ImageLibrary.createOverlayCache();
-
- int colonyLabels = options.getInteger(ClientOptions.COLONY_LABELS);
- boolean withNumbers = colonyLabels == ClientOptions.COLONY_LABELS_CLASSIC;
- // Row per row; start with the top modified row
- for (int row = firstRow; row <= lastRow; row++) {
- rowTransform = g.getTransform();
- if ((row & 1) == 1) {
- g.translate(halfWidth, 0);
- }
-
- if (options.getBoolean(ClientOptions.DISPLAY_GRID)) {
- // Display the grid.
- g.translate(0, halfHeight);
- g.setStroke(gridStroke);
- g.setColor(Color.BLACK);
- g.draw(gridPath);
- g.translate(0, -halfHeight);
- }
-
- // Column per column; start at the left side to display the tiles.
- for (int column = firstColumn; column <= lastColumn; column++) {
- Tile tile = map.getTile(column, row);
-
- // paint full borders
- displayTerritorialBorders(g, tile, BorderType.COUNTRY, true);
- // Display the Tile overlays:
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_OFF);
- if (tile != null && tile.isExplored()) {
- for (Direction direction : Direction.values()) {
- Tile borderingTile = tile.getNeighbourOrNull(direction);
- if (borderingTile != null && !borderingTile.isExplored()) {
- g.drawImage(lib.getBorderImage(
- null, direction, tile.getX(), tile.getY()),
- 0, 0, null);
- }
- }
- Image overlayImage = lib.getOverlayImage(tile, overlayCache);
- displayTileItems(g, tile, overlayImage);
- displaySettlementWithChipsOrPopulationNumber(freeColClient,
- lib, g, tile, tileWidth, tileHeight, withNumbers);
- displayFogOfWar(freeColClient, fog, g, tile);
- displayOptionalTileTextAndRegionBorder(g, tile);
- }
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
- RenderingHints.VALUE_ANTIALIAS_ON);
- // paint transparent borders
- displayTerritorialBorders(g, tile, BorderType.COUNTRY, false);
-
- if (shouldDisplayTileCursor(tile)) {
- displayCursor(g);
- }
- // check for units
- if (tile != null) {
- Unit unitInFront = findUnitInFront(tile);
- if (unitInFront != null && !isOutForAnimation(unitInFront)) {
- units.add(unitInFront);
- unitTransforms.add(g.getTransform());
- }
- // check for settlements
- Settlement settlement = tile.getSettlement();
- if (settlement != null) {
- settlements.add(settlement);
- settlementTransforms.add(g.getTransform());
- }
- }
- g.translate(tileWidth, 0);
- }
-
- g.setTransform(rowTransform);
- g.translate(0, halfHeight);
- }
- g.setTransform(baseTransform);
-
- /*
- PART 2c
- =======
- Display units
- */
- if (!units.isEmpty()) {
- g.setColor(Color.BLACK);
- Image darkness = null;
- for (int index = 0; index < units.size(); index++) {
- final Unit unit = units.get(index);
- g.setTransform(unitTransforms.get(index));
- if (unit.isUndead()) {
- if(darkness == null) {
- // Rescale dark halo only in rare case its needed!
- darkness = lib.getMiscImage(ImageLibrary.DARKNESS);
- }
- // display darkness
- displayCenteredImage(g, darkness, tileWidth, tileHeight);
- }
- displayUnit(g, unit);
- }
- g.setTransform(baseTransform);
- }
-
- /*
- PART 3
- ======
- Display the colony names.
- */
- if (!settlements.isEmpty()
- && colonyLabels != ClientOptions.COLONY_LABELS_NONE) {
- for (int index = 0; index < settlements.size(); index++) {
- final Settlement settlement = settlements.get(index);
- if (settlement.isDisposed()) {
- logger.warning("Settlement display race detected: "
- + settlement.getName());
- continue;
- }
- String name
- = Messages.message(settlement.getLocationLabelFor(player));
- if (name == null) continue;
- Color backgroundColor = settlement.getOwner().getNationColor();
- if (backgroundColor == null) backgroundColor = Color.WHITE;
- Font font = fontLibrary.createScaledFont(FontLibrary.FontType.NORMAL, FontLibrary.FontSize.SMALLER, Font.BOLD);
- Font italicFont = fontLibrary.createScaledFont(FontLibrary.FontType.NORMAL, FontLibrary.FontSize.SMALLER, Font.BOLD | Font.ITALIC);
- Font productionFont = fontLibrary.createScaledFont(FontLibrary.FontType.NORMAL, FontLibrary.FontSize.TINY, Font.BOLD);
- // int yOffset = lib.getSettlementImage(settlement).getHeight(null) + 1;
- int yOffset = tileHeight;
- g.setTransform(settlementTransforms.get(index));
- switch (colonyLabels) {
- case ClientOptions.COLONY_LABELS_CLASSIC:
- Image img = lib.getStringImage(g, name, backgroundColor, font);
- g.drawImage(img, (tileWidth - img.getWidth(null))/2 + 1,
- yOffset, null);
- break;
- case ClientOptions.COLONY_LABELS_MODERN:
- default:
- backgroundColor = new Color(backgroundColor.getRed(),
- backgroundColor.getGreen(),
- backgroundColor.getBlue(), 128);
- TextSpecification[] specs = new TextSpecification[1];
- if (settlement instanceof Colony
- && settlement.getOwner() == player) {
- Colony colony = (Colony) settlement;
- BuildableType buildable = colony.getCurrentlyBuilding();
- if (buildable != null) {
- specs = new TextSpecification[2];
- String t = Messages.getName(buildable)
- + " " + Turn.getTurnsText(colony.getTurnsToComplete(buildable));
- specs[1] = new TextSpecification(t, productionFont);
- }
- }
- specs[0] = new TextSpecification(name, font);
-
- Image nameImage = createLabel(g, specs, backgroundColor);
- if (nameImage != null) {
- int spacing = 3;
- Image leftImage = null;
- Image rightImage = null;
- if (settlement instanceof Colony) {
- Colony colony = (Colony)settlement;
- String string = Integer.toString(colony.getDisplayUnitCount());
- leftImage = createLabel(g, string,
- ((colony.getPreferredSizeChange() > 0) ? italicFont : font),
- backgroundColor);
- if (player.owns(settlement)) {
- int bonusProduction = colony.getProductionBonus();
- if (bonusProduction != 0) {
- String bonus = (bonusProduction > 0)
- ? "+" + bonusProduction
- : Integer.toString(bonusProduction);
- rightImage = createLabel(g, bonus, font,
- backgroundColor);
- }
- }
- } else if (settlement instanceof IndianSettlement) {
- IndianSettlement is = (IndianSettlement) settlement;
- if (is.getType().isCapital()) {
- leftImage = createCapitalLabel(nameImage.getHeight(null), 5, backgroundColor);
- }
-
- Unit missionary = is.getMissionary();
- if (missionary != null) {
- boolean expert = missionary.hasAbility(Ability.EXPERT_MISSIONARY);
- backgroundColor = missionary.getOwner().getNationColor();
- backgroundColor = new Color(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), 128);
- rightImage = createReligiousMissionLabel(nameImage.getHeight(null), 5, backgroundColor, expert);
- }
- }
-
- int width = (int)((nameImage.getWidth(null)
- * lib.getScalingFactor())
- + ((leftImage != null)
- ? (leftImage.getWidth(null)
- * lib.getScalingFactor()) + spacing
- : 0)
- + ((rightImage != null)
- ? (rightImage.getWidth(null)
- * lib.getScalingFactor()) + spacing
- : 0));
- int labelOffset = (tileWidth - width)/2;
- yOffset -= (nameImage.getHeight(null)
- * lib.getScalingFactor())/2;
- if (leftImage != null) {
- g.drawImage(leftImage, labelOffset, yOffset, null);
- labelOffset += (leftImage.getWidth(null)
- * lib.getScalingFactor()) + spacing;
- }
- g.drawImage(nameImage, labelOffset, yOffset, null);
- if (rightImage != null) {
- labelOffset += (nameImage.getWidth(null)
- * lib.getScalingFactor()) + spacing;
- g.drawImage(rightImage, labelOffset, yOffset, null);
- }
- break;
- }
- }
- }
- }
- g.setTransform(originTransform);
-
- /*
- PART 4
- ======
- Display goto path
- */
- if (currentPath != null) {
- displayPath(g, currentPath);
- }
- if (gotoPath != null) {
- displayPath(g, gotoPath);
- }
-
- }
-
- /**
- * Displays the given Tile onto the given Graphics2D object at the
- * location specified by the coordinates. Show tile names,
- * coordinates and colony values.
- *
- * @param g The Graphics2D object on which to draw the Tile.
- * @param tile The Tile to draw.
- */
- private void displayOptionalTileTextAndRegionBorder(Graphics2D g, Tile tile) {
- String text = null;
- int op = freeColClient.getClientOptions()
- .getInteger(ClientOptions.DISPLAY_TILE_TEXT);
- switch (op) {
- case ClientOptions.DISPLAY_TILE_TEXT_NAMES:
- text = Messages.getName(tile);
- break;
- case ClientOptions.DISPLAY_TILE_TEXT_OWNERS:
- if (tile.getOwner() != null) {
- text = Messages.message(tile.getOwner().getNationName());
- }
- break;
- case ClientOptions.DISPLAY_TILE_TEXT_REGIONS:
- if (tile.getRegion() != null) {
- if (FreeColDebugger.isInDebugMode(FreeColDebugger.DebugMode.MENUS)
- && tile.getRegion().getName() == null) {
- text = tile.getRegion().getSuffix();
- } else {
- text = Messages.message(tile.getRegion().getLabel());
- }
- }
- displayTerritorialBorders(g, tile, BorderType.REGION, true);
- break;
- case ClientOptions.DISPLAY_TILE_TEXT_EMPTY:
- break;
- default:
- logger.warning("displayTileText option " + op + " out of range");
- break;
- }
-
- g.setColor(Color.BLACK);
- g.setFont(FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor()));
- if (text != null) {
- int b = getBreakingPoint(text);
- if (b == -1) {
- g.drawString(text,
- (tileWidth - g.getFontMetrics().stringWidth(text)) / 2,
- (tileHeight - g.getFontMetrics().getAscent()) / 2);
- } else {
- g.drawString(text.substring(0, b),
- (tileWidth - g.getFontMetrics().stringWidth(text.substring(0, b)))/2,
- halfHeight - (g.getFontMetrics().getAscent()*2)/3);
- g.drawString(text.substring(b+1),
- (tileWidth - g.getFontMetrics().stringWidth(text.substring(b+1)))/2,
- halfHeight + (g.getFontMetrics().getAscent()*2)/3);
- }
- }
-
- if (FreeColDebugger.debugDisplayCoordinates()) {
- String posString = tile.getX() + ", " + tile.getY();
- if (tile.getHighSeasCount() >= 0) {
- posString += "/" + Integer.toString(tile.getHighSeasCount());
- }
- g.drawString(posString,
- (tileWidth - g.getFontMetrics().stringWidth(posString)) / 2,
- (tileHeight - g.getFontMetrics().getAscent()) / 2);
- }
- String value = DebugUtils.getColonyValue(tile);
- if (value != null) {
- g.drawString(value,
- (tileWidth - g.getFontMetrics().stringWidth(value)) / 2,
- (tileHeight - g.getFontMetrics().getAscent()) / 2);
- }
- }
-
- /**
- * Displays the given Tile onto the given Graphics2D object at the
- * location specified by the coordinates. Settlements and Lost
- * City Rumours will be shown.
- *
- * @param g The Graphics2D object on which to draw the Tile.
- * @param tile The Tile to draw.
- * @param withNumber Whether to display the number of units present.
- */
- private static void displaySettlementWithChipsOrPopulationNumber(
- FreeColClient freeColClient, ImageLibrary lib, Graphics2D g,
- Tile tile, int tileWidth, int tileHeight, boolean withNumber) {
- final Player player = freeColClient.getMyPlayer();
- final Settlement settlement = tile.getSettlement();
-
- if (settlement != null) {
- if (settlement instanceof Colony) {
- Colony colony = (Colony)settlement;
-
- // Draw image of colony in center of the tile.
- Image colonyImage = lib.getSettlementImage(settlement);
- displayCenteredImage(g, colonyImage, tileWidth, tileHeight);
-
- if (withNumber) {
- String populationString = Integer.toString(
- colony.getDisplayUnitCount());
- int bonus = colony.getProductionBonus();
- Color theColor = ResourceManager.getColor(
- "color.map.productionBonus." + bonus);
- // if government admits even more units, use
- // italic and bigger number icon
- Font font = (colony.getPreferredSizeChange() > 0)
- ? FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.SMALLER, Font.BOLD | Font.ITALIC,
- lib.getScalingFactor())
- : FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.TINY, Font.BOLD,
- lib.getScalingFactor());
- Image stringImage = lib.getStringImage(g,
- populationString, theColor, font);
- displayCenteredImage(g, stringImage, tileWidth, tileHeight);
- }
-
- } else if (settlement instanceof IndianSettlement) {
- IndianSettlement is = (IndianSettlement)settlement;
- Image settlementImage = lib.getSettlementImage(settlement);
-
- // Draw image of indian settlement in center of the tile.
- displayCenteredImage(g, settlementImage, tileWidth, tileHeight);
-
- Image chip;
- float xOffset = STATE_OFFSET_X * lib.getScalingFactor();
- float yOffset = STATE_OFFSET_Y * lib.getScalingFactor();
- final int colonyLabels = freeColClient.getClientOptions()
- .getInteger(ClientOptions.COLONY_LABELS);
- if (colonyLabels != ClientOptions.COLONY_LABELS_MODERN) {
- // Draw the settlement chip
- chip = lib.getIndianSettlementChip(g, is);
- g.drawImage(chip, (int)xOffset, (int)yOffset, null);
- xOffset += chip.getWidth(null) + 2;
-
- // Draw the mission chip if needed.
- Unit missionary = is.getMissionary();
- if (missionary != null) {
- boolean expert
- = missionary.hasAbility(Ability.EXPERT_MISSIONARY);
- g.drawImage(lib.getMissionChip(g, missionary.getOwner(),
- expert),
- (int)xOffset, (int)yOffset, null);
- xOffset += chip.getWidth(null) + 2;
- }
- }
-
- // Draw the alarm chip if needed.
- if ((chip = lib.getAlarmChip(g, is, player)) != null) {
- g.drawImage(chip, (int)xOffset, (int)yOffset, null);
- }
- } else {
- logger.warning("Bogus settlement: " + settlement);
- }
- }
- }
-
- /**
- * Displays the given Tile onto the given Graphics2D object at the
- * location specified by the coordinates. Addtions and
- * improvements to Tile will be drawn.
- *
- * @param g The Graphics2D object on which to draw the Tile.
- * @param tile The Tile to draw.
- * @param overlayImage The Image for the tile overlay.
- */
- private void displayTileItems(Graphics2D g, Tile tile, Image overlayImage) {
- // ATTENTION: we assume that only overlays and forests
- // might be taller than a tile.
- if (!tile.isExplored()) {
- g.drawImage(lib.getTerrainImage(null, tile.getX(), tile.getY()), 0, 0, null);
- } else {
- // layer additions and improvements according to zIndex
- List tileItems = (tile.getTileItemContainer() != null)
- ? tile.getTileItemContainer().getTileItems()
- : new ArrayList();
- int startIndex = 0;
- for (int index = startIndex; index < tileItems.size(); index++) {
- if (tileItems.get(index).getZIndex() < OVERLAY_INDEX) {
- displayTileItem(g, tile, tileItems.get(index));
- startIndex = index + 1;
- } else {
- startIndex = index;
- break;
- }
- }
- // Tile Overlays (eg. hills and mountains)
- if (overlayImage != null) {
- g.drawImage(overlayImage, 0, (tileHeight - overlayImage.getHeight(null)), null);
- }
- for (int index = startIndex; index < tileItems.size(); index++) {
- if (tileItems.get(index).getZIndex() < FOREST_INDEX) {
- displayTileItem(g, tile, tileItems.get(index));
- startIndex = index + 1;
- } else {
- startIndex = index;
- break;
- }
- }
- // Forest
- if (tile.isForested()) {
- Image forestImage = lib.getForestImage(tile.getType(), tile.getRiverStyle());
- g.drawImage(forestImage, 0, (tileHeight - forestImage.getHeight(null)), null);
- }
-
- // draw all remaining items
- for (TileItem ti : tileItems.subList(startIndex, tileItems.size())) {
- displayTileItem(g, tile, ti);
- }
- }
- }
-
- /**
- * Displays the given Unit onto the given Graphics2D object at the
- * location specified by the coordinates.
- *
- * @param g The Graphics2D object on which to draw the Unit.
- * @param unit The Unit to draw.
- */
- private void displayUnit(Graphics2D g, Unit unit) {
- final Player player = freeColClient.getMyPlayer();
-
- // Draw the 'selected unit' image if needed.
- //if ((unit == getActiveUnit()) && cursor) {
- if (shouldDisplayUnitCursor(unit)) displayCursor(g);
-
- // Draw the unit.
- // If unit is sentry, draw in grayscale
- boolean fade = (unit.getState() == Unit.UnitState.SENTRY)
- || (unit.hasTile()
- && player != null && !player.canSee(unit.getTile()));
- Image image = lib.getUnitImage(unit, fade);
- Point p = calculateUnitImagePositionInTile(image);
- g.drawImage(image, p.x, p.y, null);
-
- // Draw an occupation and nation indicator.
- String text = Messages.message(unit.getOccupationLabel(player, false));
- g.drawImage(lib.getOccupationIndicatorChip(g, unit, text),
- (int)(STATE_OFFSET_X * lib.getScalingFactor()), 0,
- null);
-
- // Draw one small line for each additional unit (like in civ3).
- int unitsOnTile = 0;
- if (unit.hasTile()) {
- // When a unit is moving from tile to tile, it is
- // removed from the source tile. So the unit stack
- // indicator cannot be drawn during the movement see
- // UnitMoveAnimation.animate() for details
- unitsOnTile = unit.getTile().getTotalUnitCount();
- }
- if (unitsOnTile > 1) {
- g.setColor(Color.WHITE);
- int unitLinesY = OTHER_UNITS_OFFSET_Y;
- int x1 = (int)((STATE_OFFSET_X + OTHER_UNITS_OFFSET_X)
- * lib.getScalingFactor());
- int x2 = (int)((STATE_OFFSET_X + OTHER_UNITS_OFFSET_X
- + OTHER_UNITS_WIDTH) * lib.getScalingFactor());
- for (int i = 0; i < unitsOnTile && i < MAX_OTHER_UNITS; i++) {
- g.drawLine(x1, unitLinesY, x2, unitLinesY);
- unitLinesY += 2;
- }
- }
-
- // FOR DEBUGGING
- net.sf.freecol.server.ai.AIUnit au;
- if (FreeColDebugger.isInDebugMode(FreeColDebugger.DebugMode.MENUS)
- && player != null
- && !player.owns(unit)
- && unit.getOwner().isAI()
- && freeColClient.getFreeColServer() != null
- && (au = freeColClient.getFreeColServer().getAIMain()
- .getAIUnit(unit)) != null) {
- if (FreeColDebugger.debugShowMission()) {
- g.setColor(Color.WHITE);
- g.drawString((!au.hasMission()) ? "No mission"
- : lastPart(au.getMission().getClass().toString(), "."),
- 0, 0);
- }
- if (FreeColDebugger.debugShowMissionInfo() && au.hasMission()) {
- g.setColor(Color.WHITE);
- g.drawString(au.getMission().toString(), 0, 25);
- }
- }
- }
-
- private void displayCursor(Graphics2D g) {
- Image cursorImage = lib.getMiscImage(ImageLibrary.UNIT_SELECT);
- g.drawImage(cursorImage, 0, 0, null);
- }
-
- /**
- * Draws the given TileItem on the given Tile.
- */
- private void displayTileItem(Graphics2D g, Tile tile, TileItem item) {
- if (item instanceof Resource) {
- displayResourceTileItem(g, lib, (Resource) item, tileWidth, tileHeight);
- } else if (item instanceof LostCityRumour) {
- displayLostCityRumour(g, lib, tileWidth, tileHeight);
- } else {
- displayTileImprovement(g, lib, rp, tile, (TileImprovement)item);
- }
- }
-
- private static void displayResourceTileItem(Graphics2D g, ImageLibrary lib,
- Resource item,
- int tileWidth, int tileHeight) {
- Image bonusImage = lib.getMiscImage("image.tileitem." + item.getType().getId());
- displayCenteredImage(g, bonusImage, tileWidth, tileHeight);
- }
-
- private static void displayLostCityRumour(Graphics2D g, ImageLibrary lib,
- int tileWidth, int tileHeight) {
- displayCenteredImage(g, lib.getMiscImage(ImageLibrary.LOST_CITY_RUMOUR),
- tileWidth, tileHeight);
- }
-
- private static void displayTileImprovement(Graphics2D g, ImageLibrary lib,
- RoadPainter rp,
- Tile tile, TileImprovement ti) {
- if (ti.isComplete()) {
- if (ti.isRoad()) {
- rp.displayRoad(g, tile);
- } else if (ti.isRiver()
- && ti.getMagnitude() < TileImprovement.FJORD_RIVER) {
- // @compat 0.10.5
- // America_large had some bogus rivers in 0.10.5
- if (ti.getStyle() != null)
- // end @compat 0.10.5
- g.drawImage(lib.getRiverImage(ti.getStyle()), 0, 0, null);
- } else {
- String key = "image.tile." + ti.getType().getId();
- if (ResourceManager.hasImageResource(key)) {
- // Has its own Overlay Image in Misc, use it
- Image overlay = ResourceManager.getImage(key,
- lib.getScalingFactor());
- g.drawImage(overlay, 0, 0, null);
- }
- }
- }
- }
-
- private JLabel enterUnitOutForAnimation(final Unit unit,
- final Tile sourceTile) {
- Integer i = unitsOutForAnimation.get(unit);
- if (i == null) {
- final JLabel unitLabel = createUnitLabel(unit);
-
- i = 1;
- unitLabel.setLocation(calculateUnitLabelPositionInTile(unitLabel,
- calculateTilePosition(sourceTile)));
- unitsOutForAnimationLabels.put(unit, unitLabel);
- gui.getCanvas().add(unitLabel, JLayeredPane.DEFAULT_LAYER);
- } else {
- i++;
- }
- unitsOutForAnimation.put(unit, i);
- return unitsOutForAnimationLabels.get(unit);
- }
-
- /**
- * Returns the amount of columns that are to the left of the Tile
- * that is displayed in the center of the Map.
- *
- * @return The amount of columns that are to the left of the Tile
- * that is displayed in the center of the Map.
- */
- private int getLeftColumns() {
- return getLeftColumns(focus.getY());
- }
-
- /**
- * Returns the amount of columns that are to the left of the Tile
- * with the given y-coordinate.
- *
- * @param y The y-coordinate of the Tile in question.
- * @return The amount of columns that are to the left of the Tile
- * with the given y-coordinate.
- */
- private int getLeftColumns(int y) {
- int leftColumns = leftSpace / tileWidth + 1;
-
- if ((y & 1) == 0) {
- if ((leftSpace % tileWidth) > 32) {
- leftColumns++;
- }
- } else {
- if ((leftSpace % tileWidth) == 0) {
- leftColumns--;
- }
- }
-
- return leftColumns;
- }
-
- /**
- * Returns the amount of columns that are to the right of the Tile
- * that is displayed in the center of the Map.
- *
- * @return The amount of columns that are to the right of the Tile
- * that is displayed in the center of the Map.
- */
- private int getRightColumns() {
- return getRightColumns(focus.getY());
- }
-
- /**
- * Returns the amount of columns that are to the right of the Tile
- * with the given y-coordinate.
- *
- * @param y The y-coordinate of the Tile in question.
- * @return The amount of columns that are to the right of the Tile
- * with the given y-coordinate.
- */
- private int getRightColumns(int y) {
- int rightColumns = rightSpace / tileWidth + 1;
-
- if ((y & 1) == 0) {
- if ((rightSpace % tileWidth) == 0) {
- rightColumns--;
- }
- } else {
- if ((rightSpace % tileWidth) > 32) {
- rightColumns++;
- }
- }
-
- return rightColumns;
- }
-
- /**
- * Gets the coordinates to draw a unit in a given tile.
- *
- * @param unitImage The unit's image
- * @return The coordinates where the unit should be drawn onscreen
- */
- private Point calculateUnitImagePositionInTile(Image unitImage) {
- int unitX = (tileWidth - unitImage.getWidth(null)) / 2;
- int unitY = (tileHeight - unitImage.getHeight(null)) / 2 -
- (int) (UNIT_OFFSET * lib.getScalingFactor());
-
- return new Point(unitX, unitY);
- }
-
- /**
- * Gets the unit that should be displayed on the given tile.
- *
- * @param unitTile The Tile
to check.
- * @return The Unit
to display or null if none found.
- */
- private Unit findUnitInFront(Tile unitTile) {
- Unit result;
-
- if (unitTile == null || unitTile.isEmpty()) {
- result = null;
-
- } else if (activeUnit != null && activeUnit.getTile() == unitTile) {
- result = activeUnit;
-
- } else if (unitTile.hasSettlement()) {
- result = null;
-
- } else if (activeUnit != null && activeUnit.isOffensiveUnit()) {
- result = unitTile.getDefendingUnit(activeUnit);
-
- } else {
- // Find the unit with the most moves left, preferring
- // active units.
- List units = unitTile.getUnitList();
- result = units.remove(0);
- int best = result.getMovesLeft();
- boolean carrier,
- active = result.getState() == Unit.UnitState.ACTIVE;
- for (Unit u : units) {
- carrier = false;
- if (active) {
- if (u.getState() == Unit.UnitState.ACTIVE) {
- if (best < u.getMovesLeft()) {
- best = u.getMovesLeft();
- result = u;
- }
- } else {
- carrier = !u.isEmpty();
- }
- } else if (u.getState() == Unit.UnitState.ACTIVE) {
- active = true;
- best = u.getMovesLeft();
- result = u;
- } else {
- if (best < u.getMovesLeft()) {
- best = u.getMovesLeft();
- result = u;
- }
- carrier = !u.isEmpty();
- }
- if (carrier) {
- // Check for active units on carriers. Usually the
- // carrier takes precedence.
- for (Unit c : u.getUnitList()) {
- if (active) {
- if (best < c.getMovesLeft()) {
- best = c.getMovesLeft();
- result = c;
- }
- } else if (c.getState() == Unit.UnitState.ACTIVE) {
- active = true;
- best = c.getMovesLeft();
- result = c;
- }
- }
- }
- }
- }
- return result;
- }
-
- /**
- * Draw the unit's image and occupation indicator in one JLabel object.
- *
- * @param unit The unit to be drawn
- * @return A JLabel object with the unit's image.
- */
- private JLabel createUnitLabel(Unit unit) {
- final Image unitImg = lib.getUnitImage(unit);
- final int width = halfWidth + unitImg.getWidth(null)/2;
- final int height = unitImg.getHeight(null);
-
- BufferedImage img = new BufferedImage(width, height,
- BufferedImage.TYPE_INT_ARGB);
- Graphics2D g = img.createGraphics();
-
- final int unitX = (width - unitImg.getWidth(null)) / 2;
- g.drawImage(unitImg, unitX, 0, null);
-
- Player player = freeColClient.getMyPlayer();
- String text = Messages.message(unit.getOccupationLabel(player, false));
- g.drawImage(lib.getOccupationIndicatorChip(g, unit, text), 0, 0, null);
-
- final JLabel label = new JLabel(new ImageIcon(img));
- label.setSize(width, height);
-
- g.dispose();
- return label;
- }
-
- /**
- * Is a y-coordinate near the bottom?
- *
- * @param y The y-coordinate.
- * @return True if near the bottom.
- */
- private boolean isMapNearBottom(int y) {
- return y >= freeColClient.getGame().getMap().getHeight() - bottomRows;
- }
-
- /**
- * Is an x,y coordinate near the left?
- *
- * @param x The x-coordinate.
- * @param y The y-coordinate.
- * @return True if near the left.
- */
- private boolean isMapNearLeft(int x, int y) {
- return x < getLeftColumns(y);
- }
-
- /**
- * Is an x,y coordinate near the right?
- *
- * @param x The x-coordinate.
- * @param y The y-coordinate.
- * @return True if near the right.
- */
- private boolean isMapNearRight(int x, int y) {
- return x >= freeColClient.getGame().getMap().getWidth()
- - getRightColumns(y);
- }
-
- /**
- * Is a y-coordinate near the top?
- *
- * @param y The y-coordinate.
- * @return True if near the top.
- */
- private boolean isMapNearTop(int y) {
- return y < topRows;
- }
-
- /**
- * Returns true if the given Unit is being animated.
- *
- * @param unit an Unit
- * @return a boolean
- */
- private boolean isOutForAnimation(final Unit unit) {
- return unitsOutForAnimation.containsKey(unit);
- }
-
- private boolean isTileVisible(Tile tile) {
- if (tile == null) return false;
- return tile.getY() >= topRow && tile.getY() <= bottomRow
- && tile.getX() >= leftColumn && tile.getX() <= rightColumn;
- }
-
- private boolean isNoActiveUnitAt(Tile tile) {
- return activeUnit == null || activeUnit.getTile() != tile;
- }
-
- /**
- * Draws the borders of a territory on the given Tile. The
- * territory is either a country or a region.
- *
- * @param g a Graphics2D
- * @param tile a Tile
- * @param type a BorderType
- * @param opaque a boolean
- */
- private void displayTerritorialBorders(Graphics2D g, Tile tile, BorderType type, boolean opaque) {
- if (tile == null ||
- (type == BorderType.COUNTRY
- && !freeColClient.getClientOptions().getBoolean(ClientOptions.DISPLAY_BORDERS))) {
- return;
- }
- Player owner = tile.getOwner();
- Region region = tile.getRegion();
- if ((type == BorderType.COUNTRY && owner != null)
- || (type == BorderType.REGION && region != null)) {
- Stroke oldStroke = g.getStroke();
- g.setStroke(borderStroke);
- Color oldColor = g.getColor();
- Color newColor = Color.WHITE;
- if (type == BorderType.COUNTRY) {
- Color c = owner.getNationColor();
- if (c != null) {
- newColor = new Color(c.getRed(), c.getGreen(), c.getBlue(),
- (opaque) ? 255 : 100);
- }
- }
- g.setColor(newColor);
- GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
- path.moveTo(borderPoints.get(Direction.longSides.get(0)).x,
- borderPoints.get(Direction.longSides.get(0)).y);
- for (Direction d : Direction.longSides) {
- Tile otherTile = tile.getNeighbourOrNull(d);
- Direction next = d.getNextDirection();
- Direction next2 = next.getNextDirection();
- if (otherTile == null
- || (type == BorderType.COUNTRY && !owner.owns(otherTile))
- || (type == BorderType.REGION && otherTile.getRegion() != region)) {
- Tile tile1 = tile.getNeighbourOrNull(next);
- Tile tile2 = tile.getNeighbourOrNull(next2);
- if (tile2 == null
- || (type == BorderType.COUNTRY && !owner.owns(tile2))
- || (type == BorderType.REGION && tile2.getRegion() != region)) {
- // small corner
- path.lineTo(borderPoints.get(next).x,
- borderPoints.get(next).y);
- path.quadTo(controlPoints.get(next).x,
- controlPoints.get(next).y,
- borderPoints.get(next2).x,
- borderPoints.get(next2).y);
- } else {
- int dx = 0, dy = 0;
- switch(d) {
- case NW: dx = halfWidth; dy = -halfHeight; break;
- case NE: dx = halfWidth; dy = halfHeight; break;
- case SE: dx = -halfWidth; dy = halfHeight; break;
- case SW: dx = -halfWidth; dy = -halfHeight; break;
- default: break;
- }
- if (tile1 != null
- && ((type == BorderType.COUNTRY && owner.owns(tile1))
- || (type == BorderType.REGION && tile1.getRegion() == region))) {
- // short straight line
- path.lineTo(borderPoints.get(next).x,
- borderPoints.get(next).y);
- // big corner
- Direction previous = d.getPreviousDirection();
- Direction previous2 = previous.getPreviousDirection();
- int ddx = 0, ddy = 0;
- switch(d) {
- case NW: ddy = -tileHeight; break;
- case NE: ddx = tileWidth; break;
- case SE: ddy = tileHeight; break;
- case SW: ddx = -tileWidth; break;
- default: break;
- }
- path.quadTo(controlPoints.get(previous).x + dx,
- controlPoints.get(previous).y + dy,
- borderPoints.get(previous2).x + ddx,
- borderPoints.get(previous2).y + ddy);
- } else {
- // straight line
- path.lineTo(borderPoints.get(d).x + dx,
- borderPoints.get(d).y + dy);
- }
- }
- } else {
- path.moveTo(borderPoints.get(next2).x,
- borderPoints.get(next2).y);
- }
- }
- g.draw(path);
- g.setColor(oldColor);
- g.setStroke(oldStroke);
- }
+ private void repositionMapIfNeeded() {
+ if (bottomRow < 0 && focus != null) positionMap(focus);
}
/**
@@ -2700,22 +757,474 @@ public final class MapViewer {
}
}
- private void releaseUnitOutForAnimation(final Unit unit) {
- Integer i = unitsOutForAnimation.get(unit);
- if (i == null) {
- throw new IllegalStateException("Tried to release unit that was not out for animation");
- }
- if (i == 1) {
- unitsOutForAnimation.remove(unit);
- gui.getCanvas().removeFromCanvas(unitsOutForAnimationLabels.remove(unit));
+ /**
+ * Scroll the map in the given direction.
+ *
+ * @param direction The Direction
to scroll in.
+ * @return True if scrolling occurred.
+ */
+ boolean scrollMap(Direction direction) {
+ Tile t = focus;
+ if (t == null) return false;
+ int fx = t.getX(), fy = t.getY();
+ if ((t = t.getNeighbourOrNull(direction)) == null) return false;
+ int tx = t.getX(), ty = t.getY();
+ int x, y;
+
+ // When already close to an edge, resist moving the focus closer,
+ // but if moving away immediately jump out of the `nearTo' area.
+ if (isMapNearTop(ty) && isMapNearTop(fy)) {
+ y = (ty <= fy) ? fy : topRows;
+ } else if (isMapNearBottom(ty) && isMapNearBottom(fy)) {
+ y = (ty >= fy) ? fy : freeColClient.getGame().getMap().getWidth()
+ - bottomRows;
} else {
- i--;
- unitsOutForAnimation.put(unit, i);
+ y = ty;
}
+ if (isMapNearLeft(tx, ty) && isMapNearLeft(fx, fy)) {
+ x = (tx <= fx) ? fx : getLeftColumns(ty);
+ } else if (isMapNearRight(tx, ty) && isMapNearRight(fx, fy)) {
+ x = (tx >= fx) ? fx : freeColClient.getGame().getMap().getWidth()
+ - getRightColumns(ty);
+ } else {
+ x = tx;
+ }
+
+ if (x == fx && y == fy) return false;
+ gui.setFocus(freeColClient.getGame().getMap().getTile(x,y));
+ return true;
}
- private void repositionMapIfNeeded() {
- if (bottomRow < 0 && focus != null) positionMap(focus);
+ /**
+ * Is a y-coordinate near the bottom?
+ *
+ * @param y The y-coordinate.
+ * @return True if near the bottom.
+ */
+ private boolean isMapNearBottom(int y) {
+ return y >= freeColClient.getGame().getMap().getHeight() - bottomRows;
+ }
+
+ /**
+ * Is an x,y coordinate near the left?
+ *
+ * @param x The x-coordinate.
+ * @param y The y-coordinate.
+ * @return True if near the left.
+ */
+ private boolean isMapNearLeft(int x, int y) {
+ return x < getLeftColumns(y);
+ }
+
+ /**
+ * Is an x,y coordinate near the right?
+ *
+ * @param x The x-coordinate.
+ * @param y The y-coordinate.
+ * @return True if near the right.
+ */
+ private boolean isMapNearRight(int x, int y) {
+ return x >= freeColClient.getGame().getMap().getWidth()
+ - getRightColumns(y);
+ }
+
+ /**
+ * Returns the amount of columns that are to the left of the Tile
+ * that is displayed in the center of the Map.
+ *
+ * @return The amount of columns that are to the left of the Tile
+ * that is displayed in the center of the Map.
+ */
+ private int getLeftColumns() {
+ return getLeftColumns(focus.getY());
+ }
+
+ /**
+ * Returns the amount of columns that are to the left of the Tile
+ * with the given y-coordinate.
+ *
+ * @param y The y-coordinate of the Tile in question.
+ * @return The amount of columns that are to the left of the Tile
+ * with the given y-coordinate.
+ */
+ private int getLeftColumns(int y) {
+ int leftColumns = leftSpace / tileWidth + 1;
+
+ if ((y & 1) == 0) {
+ if ((leftSpace % tileWidth) > 32) {
+ leftColumns++;
+ }
+ } else {
+ if ((leftSpace % tileWidth) == 0) {
+ leftColumns--;
+ }
+ }
+
+ return leftColumns;
+ }
+
+ /**
+ * Returns the amount of columns that are to the right of the Tile
+ * that is displayed in the center of the Map.
+ *
+ * @return The amount of columns that are to the right of the Tile
+ * that is displayed in the center of the Map.
+ */
+ private int getRightColumns() {
+ return getRightColumns(focus.getY());
+ }
+
+ /**
+ * Returns the amount of columns that are to the right of the Tile
+ * with the given y-coordinate.
+ *
+ * @param y The y-coordinate of the Tile in question.
+ * @return The amount of columns that are to the right of the Tile
+ * with the given y-coordinate.
+ */
+ private int getRightColumns(int y) {
+ int rightColumns = rightSpace / tileWidth + 1;
+
+ if ((y & 1) == 0) {
+ if ((rightSpace % tileWidth) == 0) {
+ rightColumns--;
+ }
+ } else {
+ if ((rightSpace % tileWidth) > 32) {
+ rightColumns++;
+ }
+ }
+
+ return rightColumns;
+ }
+
+ /**
+ * Is a y-coordinate near the top?
+ *
+ * @param y The y-coordinate.
+ * @return True if near the top.
+ */
+ private boolean isMapNearTop(int y) {
+ return y < topRows;
+ }
+
+ private boolean isTileVisible(Tile tile) {
+ if (tile == null) return false;
+ return tile.getY() >= topRow && tile.getY() <= bottomRow
+ && tile.getX() >= leftColumn && tile.getX() <= rightColumn;
+ }
+
+ /**
+ * Gets the selected tile.
+ *
+ * @return The Tile
selected.
+ */
+ Tile getSelectedTile() {
+ return selectedTile;
+ }
+
+ /**
+ * Selects the tile at the specified position. There are two
+ * possible cases:
+ *
+ *
+ * - If the tile contains a unit that can become active, then
+ * that unit will be set as the active unit.
+ *
- If not, the
selectedTile
will become the map focus.
+ *
+ *
+ * If a unit is active and is located on the selected tile,
+ * then nothing (except perhaps a map reposition) will happen.
+ *
+ * @param newTile The Tile
, the tile to be selected
+ * @return True if the focus was set.
+ * @see #getSelectedTile
+ * @see #setActiveUnit
+ * @see #setFocus(Tile)
+ */
+ boolean setSelectedTile(Tile newTile) {
+ Tile oldTile = this.selectedTile;
+ boolean ret = false;
+ selectedTile = newTile;
+
+ if (viewMode == GUI.MOVE_UNITS_MODE) {
+ if (activeUnit == null || activeUnit.getTile() != newTile) {
+ // select a unit on the selected tile
+ Unit unitInFront = findUnitInFront(newTile);
+ if (unitInFront != null) {
+ ret = gui.setActiveUnit(unitInFront);
+ updateCurrentPathForActiveUnit();
+ } else {
+ gui.setFocus(newTile);
+ ret = true;
+ }
+ }
+ }
+
+ // Check for refocus
+ if (!onScreen(newTile)
+ || freeColClient.getClientOptions().getBoolean(ClientOptions.ALWAYS_CENTER)) {
+ gui.setFocus(newTile);
+ ret = true;
+ } else {
+ if (oldTile != null) {
+ gui.refreshTile(oldTile);
+ }
+
+ if (newTile != null) {
+ gui.refreshTile(newTile);
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Gets the unit that should be displayed on the given tile.
+ *
+ * @param unitTile The Tile
to check.
+ * @return The Unit
to display or null if none found.
+ */
+ private Unit findUnitInFront(Tile unitTile) {
+ Unit result;
+
+ if (unitTile == null || unitTile.isEmpty()) {
+ result = null;
+
+ } else if (activeUnit != null && activeUnit.getTile() == unitTile) {
+ result = activeUnit;
+
+ } else if (unitTile.hasSettlement()) {
+ result = null;
+
+ } else if (activeUnit != null && activeUnit.isOffensiveUnit()) {
+ result = unitTile.getDefendingUnit(activeUnit);
+
+ } else {
+ // Find the unit with the most moves left, preferring
+ // active units.
+ List units = unitTile.getUnitList();
+ result = units.remove(0);
+ int best = result.getMovesLeft();
+ boolean carrier,
+ active = result.getState() == Unit.UnitState.ACTIVE;
+ for (Unit u : units) {
+ carrier = false;
+ if (active) {
+ if (u.getState() == Unit.UnitState.ACTIVE) {
+ if (best < u.getMovesLeft()) {
+ best = u.getMovesLeft();
+ result = u;
+ }
+ } else {
+ carrier = !u.isEmpty();
+ }
+ } else if (u.getState() == Unit.UnitState.ACTIVE) {
+ active = true;
+ best = u.getMovesLeft();
+ result = u;
+ } else {
+ if (best < u.getMovesLeft()) {
+ best = u.getMovesLeft();
+ result = u;
+ }
+ carrier = !u.isEmpty();
+ }
+ if (carrier) {
+ // Check for active units on carriers. Usually the
+ // carrier takes precedence.
+ for (Unit c : u.getUnitList()) {
+ if (active) {
+ if (best < c.getMovesLeft()) {
+ best = c.getMovesLeft();
+ result = c;
+ }
+ } else if (c.getState() == Unit.UnitState.ACTIVE) {
+ active = true;
+ best = c.getMovesLeft();
+ result = c;
+ }
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Gets the active unit.
+ *
+ * @return The Unit
.
+ * @see #setActiveUnit
+ */
+ Unit getActiveUnit() {
+ return activeUnit;
+ }
+
+ /**
+ * Sets the active unit.
+ *
+ * @param activeUnit The new active Unit
.
+ * @return True if the focus was set.
+ */
+ boolean setActiveUnit(Unit activeUnit) {
+ // Don't select a unit with zero moves left. -sjm
+ // The user might what to check the status of a unit - SG
+ Tile tile = (activeUnit == null) ? null : activeUnit.getTile();
+ this.activeUnit = activeUnit;
+
+ // The user activated a unit
+ if (viewMode == GUI.VIEW_TERRAIN_MODE && activeUnit != null) {
+ changeViewMode(GUI.MOVE_UNITS_MODE);
+ }
+
+ if (activeUnit == null || tile == null) {
+ gui.getCanvas().stopGoto();
+ } else {
+ updateCurrentPathForActiveUnit();
+ if (!gui.setSelectedTile(tile)
+ || freeColClient.getClientOptions()
+ .getBoolean(ClientOptions.JUMP_TO_ACTIVE_UNIT)) {
+ gui.setFocus(tile);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Checks if there is currently a goto operation on the mapboard.
+ *
+ * @return True if a goto operation is in progress.
+ */
+ boolean isGotoStarted() {
+ return gotoStarted;
+ }
+
+ /**
+ * Starts a goto operation on the mapboard.
+ *
+ * Dont use this directly, call the method in canvas!
+ */
+ void startGoto() {
+ gotoStarted = true;
+ setGotoPath(null);
+ }
+
+ /**
+ * Stops any ongoing goto operation on the mapboard.
+ *
+ * Dont use this directly, call the method in canvas!
+ */
+ void stopGoto() {
+ setGotoPath(null);
+ updateCurrentPathForActiveUnit();
+ gotoStarted = false;
+ }
+
+ /**
+ * Gets the path to be drawn on the map.
+ *
+ * @return The path that should be drawn on the map or
+ * null
if no path should be drawn.
+ */
+ PathNode getGotoPath() {
+ return gotoPath;
+ }
+
+ /**
+ * Sets the path to be drawn on the map.
+ *
+ * Dont use this directly, call the method in canvas!
+ *
+ * @param gotoPath The path that should be drawn on the map
+ * or null
if no path should be drawn.
+ */
+ void setGotoPath(PathNode gotoPath) {
+ this.gotoPath = gotoPath;
+ forceReposition();
+ }
+
+ /**
+ * Sets the path of the active unit to display it.
+ */
+ void updateCurrentPathForActiveUnit() {
+ PathNode path;
+ if (activeUnit == null
+ || activeUnit.getDestination() == null
+ || ((FreeColGameObject)activeUnit.getDestination()).isDisposed()
+ || Map.isSameLocation(activeUnit.getLocation(),
+ activeUnit.getDestination())) {
+ path = null;
+ } else {
+ try {
+ path = activeUnit.findPath(activeUnit.getDestination());
+ } catch (Exception e) {
+ logger.log(Level.WARNING, "Path fail", e);
+ path = null;
+ activeUnit.setDestination(null);
+ }
+ }
+ setCurrentPath(path);
+ }
+
+ /**
+ * Set the current active unit path.
+ *
+ * @param path The current PathNode
.
+ */
+ void setCurrentPath(PathNode path) {
+ this.currentPath = path;
+ }
+
+ void setSize(Dimension size) {
+ this.size = size;
+ updateMapDisplayVariables();
+ }
+
+ /**
+ * Reset the scale of the map to the default.
+ */
+ void resetMapScale() {
+ setImageLibraryAndUpdateData(new ImageLibrary());
+ updateMapDisplayVariables();
+ }
+
+ boolean isAtMaxMapScale() {
+ return lib.getScaleFactor() == MAP_SCALE_MAX;
+ }
+
+ boolean isAtMinMapScale() {
+ return lib.getScaleFactor() == MAP_SCALE_MIN;
+ }
+
+ void increaseMapScale() {
+ float newScale = lib.getScaleFactor() + MAP_SCALE_STEP;
+ if (newScale >= MAP_SCALE_MAX)
+ newScale = MAP_SCALE_MAX;
+ setImageLibraryAndUpdateData(new ImageLibrary(newScale));
+ updateMapDisplayVariables();
+ }
+
+ void decreaseMapScale() {
+ float newScale = lib.getScaleFactor() - MAP_SCALE_STEP;
+ if (newScale <= MAP_SCALE_MIN)
+ newScale = MAP_SCALE_MIN;
+ setImageLibraryAndUpdateData(new ImageLibrary(newScale));
+ updateMapDisplayVariables();
+ }
+
+ private void updateMapDisplayVariables() {
+ // Calculate the amount of rows that will be drawn above the
+ // central Tile
+ topSpace = (size.height - tileHeight) / 2;
+ if ((topSpace % (halfHeight)) != 0) {
+ topRows = topSpace / (halfHeight) + 2;
+ } else {
+ topRows = topSpace / (halfHeight) + 1;
+ }
+ bottomRows = topRows;
+ leftSpace = (size.width - tileWidth) / 2;
+ rightSpace = leftSpace;
}
/**
@@ -2726,12 +1235,12 @@ public final class MapViewer {
*/
private void setImageLibraryAndUpdateData(ImageLibrary lib) {
this.lib = lib;
- rp = new RoadPainter(lib);
+ tv.setImageLibraryAndUpdateData(lib);
// ATTENTION: we assume that all base tiles have the same size
- Image unexplored = lib.getTerrainImage(null, 0, 0);
- tileHeight = unexplored.getHeight(null);
+ Dimension tileSize = lib.tileSize;
+ tileHeight = tileSize.height;
+ tileWidth = tileSize.width;
halfHeight = tileHeight/2;
- tileWidth = unexplored.getWidth(null);
halfWidth = tileWidth/2;
int dx = tileWidth/16;
@@ -2760,38 +1269,815 @@ public final class MapViewer {
borderPoints.put(Direction.W, new Point2D.Float(dx + ddx, halfHeight + ddy));
borderStroke = new BasicStroke(dy);
- gridStroke = new BasicStroke(lib.getScalingFactor());
-
- fog.reset();
- fog.moveTo(halfWidth, 0);
- fog.lineTo(tileWidth, halfHeight);
- fog.lineTo(halfWidth, tileHeight);
- fog.lineTo(0, halfHeight);
- fog.closePath();
+ gridStroke = new BasicStroke(lib.getScaleFactor());
}
- private void updateMapDisplayVariables() {
- // Calculate the amount of rows that will be drawn above the
- // central Tile
- topSpace = (size.height - tileHeight) / 2;
- if ((topSpace % (halfHeight)) != 0) {
- topRows = topSpace / (halfHeight) + 2;
- } else {
- topRows = topSpace / (halfHeight) + 1;
+ /**
+ * Displays the Map.
+ *
+ * @param g The Graphics2D object on which to draw the Map.
+ */
+ void displayMap(Graphics2D g) {
+ final ClientOptions options = freeColClient.getClientOptions();
+ Game game = freeColClient.getGame();
+ Map map = game.getMap();
+
+ // Remember transform
+ AffineTransform originTransform = g.getTransform();
+ Rectangle clipBounds = g.getClipBounds();
+
+ // Position the map if it is not positioned yet
+ repositionMapIfNeeded();
+
+ // Determine which tiles need to be redrawn
+ int firstRow = (clipBounds.y - topRowY) / (halfHeight) - 1;
+ int clipTopY = topRowY + firstRow * (halfHeight);
+ firstRow = topRow + firstRow;
+
+ int firstColumn = (clipBounds.x - leftColumnX) / tileWidth - 1;
+ int clipLeftX = leftColumnX + firstColumn * tileWidth;
+ firstColumn = leftColumn + firstColumn;
+
+ int lastRow = (clipBounds.y + clipBounds.height - topRowY)
+ / (halfHeight);
+ lastRow = topRow + lastRow;
+
+ int lastColumn = (clipBounds.x + clipBounds.width - leftColumnX)
+ / tileWidth;
+ lastColumn = leftColumn + lastColumn;
+
+ // Clear background
+ g.setColor(Color.black);
+ g.fillRect(clipBounds.x, clipBounds.y,
+ clipBounds.width, clipBounds.height);
+
+ // Set and remember transform for upper left corner
+ g.translate(clipLeftX, clipTopY);
+ AffineTransform baseTransform = g.getTransform();
+
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+
+ // Display the base Tiles
+ final int x0 = firstColumn;
+ final int y0 = firstRow;
+ map.forSubMap(x0, y0, lastColumn-firstColumn+1, lastRow-firstRow+1,
+ (Tile tile) -> {
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+
+ tv.displayTileWithBeachAndBorder(g, tile);
+ tv.displayUnknownTileBorder(g, tile);
+
+ g.translate(-xt, -yt);
+ });
+
+ // Draw the grid, if needed
+ if (options.getBoolean(ClientOptions.DISPLAY_GRID)) {
+ // Generate a zigzag GeneralPath
+ GeneralPath gridPath = new GeneralPath();
+ gridPath.moveTo(0, 0);
+ int nextX = halfWidth;
+ int nextY = -halfHeight;
+ for (int i = 0; i <= ((lastColumn - firstColumn) * 2 + 1); i++) {
+ gridPath.lineTo(nextX, nextY);
+ nextX += halfWidth;
+ nextY = (nextY == 0 ? -halfHeight : 0);
+ }
+
+ // Display the grid
+ g.setStroke(gridStroke);
+ g.setColor(Color.BLACK);
+ for (int row = firstRow; row <= lastRow; row++) {
+ g.translate(0, halfHeight);
+ AffineTransform rowTransform = g.getTransform();
+ if ((row & 1) == 1) {
+ g.translate(halfWidth, 0);
+ }
+ g.draw(gridPath);
+ g.setTransform(rowTransform);
+ }
+ g.setTransform(baseTransform);
+ }
+
+ // Paint full region borders
+ if (options.getInteger(ClientOptions.DISPLAY_TILE_TEXT) ==
+ ClientOptions.DISPLAY_TILE_TEXT_REGIONS) {
+ map.forSubMap(x0, y0-1, lastColumn-firstColumn+1, lastRow-firstRow+1+1,
+ (Tile tile) -> {
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+ displayTerritorialBorders(g, tile, BorderType.REGION, true);
+ g.translate(-xt, -yt);
+ });
+ }
+
+ // Paint full country borders
+ if (options.getBoolean(ClientOptions.DISPLAY_BORDERS)) {
+ map.forSubMap(x0, y0-1, lastColumn-firstColumn+1, lastRow-firstRow+1+1,
+ (Tile tile) -> {
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+ displayTerritorialBorders(g, tile, BorderType.COUNTRY, true);
+ g.translate(-xt, -yt);
+ });
+ }
+
+ // Display the Tile overlays
+ Set overlayCache = ImageLibrary.createOverlayCache();
+ int colonyLabels = options.getInteger(ClientOptions.COLONY_LABELS);
+ boolean withNumbers = colonyLabels == ClientOptions.COLONY_LABELS_CLASSIC;
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_OFF);
+ map.forSubMap(x0, y0, lastColumn-firstColumn+1, lastRow-firstRow+1,
+ (Tile tile) -> {
+ if (!tile.isExplored())
+ return;
+
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+
+ BufferedImage overlayImage = lib.getOverlayImage(tile, overlayCache);
+ tv.displayTileItems(g, tile, overlayImage);
+ tv.displaySettlementWithChipsOrPopulationNumber(
+ g, tile, withNumbers);
+ tv.displayFogOfWar(g, tile);
+ tv.displayOptionalTileText(g, tile);
+
+ g.translate(-xt, -yt);
+ });
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
+
+ // Paint transparent region borders
+ if (options.getInteger(ClientOptions.DISPLAY_TILE_TEXT) ==
+ ClientOptions.DISPLAY_TILE_TEXT_REGIONS) {
+ map.forSubMap(x0, y0-1, lastColumn-firstColumn+1, lastRow-firstRow+1+1,
+ (Tile tile) -> {
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+ displayTerritorialBorders(g, tile, BorderType.REGION, false);
+ g.translate(-xt, -yt);
+ });
+ }
+
+ // Paint transparent country borders
+ if (options.getBoolean(ClientOptions.DISPLAY_BORDERS)) {
+ map.forSubMap(x0, y0-1, lastColumn-firstColumn+1, lastRow-firstRow+1+1,
+ (Tile tile) -> {
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+ displayTerritorialBorders(g, tile, BorderType.COUNTRY, false);
+ g.translate(-xt, -yt);
+ });
+ }
+
+ // Display cursor for selected tile or active unit
+ Tile cursorTile = null;
+ switch (viewMode) {
+ case GUI.MOVE_UNITS_MODE:
+ if (activeUnit != null &&
+ (cursor.isActive() || activeUnit.getMovesLeft() <= 0))
+ cursorTile = activeUnit.getTile();
+ break;
+ case GUI.VIEW_TERRAIN_MODE:
+ if (selectedTile != null)
+ cursorTile = selectedTile;
+ }
+ if (cursorTile != null) {
+ final int x = cursorTile.getX();
+ final int y = cursorTile.getY();
+ if(x >= x0 && y >= y0 && x <= lastColumn && y <= lastRow) {
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+ displayCursor(g);
+ g.translate(-xt, -yt);
+ }
+ }
+
+ // Display units
+ g.setColor(Color.BLACK);
+ if(!game.isInRevengeMode()) {
+ map.forSubMap(x0, y0, lastColumn-firstColumn+1, lastRow-firstRow+1,
+ (Tile tile) -> {
+ // check for units
+ Unit unit = findUnitInFront(tile);
+ if (unit == null || isOutForAnimation(unit))
+ return;
+
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+
+ displayUnit(g, unit);
+
+ g.translate(-xt, -yt);
+ });
+ } else {
+ /* Add extra rows and colums, as the dark halo is huge to enable
+ a very slow fade into transparency, see BR#2580 */
+ map.forSubMap(x0-2, y0-4, lastColumn-firstColumn+1+4, lastRow-firstRow+1+8,
+ (Tile tile) -> {
+ // check for units
+ Unit unit = findUnitInFront(tile);
+ if (unit == null)
+ return;
+
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+
+ if (unit.isUndead()) {
+ // Rescale dark halo only in rare case its needed!
+ BufferedImage darkness = lib.getMiscImage(ImageLibrary.DARKNESS);
+ tv.displayCenteredImage(g, darkness);
+ }
+ if (!isOutForAnimation(unit))
+ displayUnit(g, unit);
+
+ g.translate(-xt, -yt);
+ });
+ }
+
+ // Display the colony names, if needed
+ if (colonyLabels != ClientOptions.COLONY_LABELS_NONE) {
+ final Player player = freeColClient.getMyPlayer();
+ FontLibrary fontLibrary = new FontLibrary(lib.getScaleFactor());
+ Font font = fontLibrary.createScaledFont(
+ FontLibrary.FontType.NORMAL, FontLibrary.FontSize.SMALLER,
+ Font.BOLD);
+ Font italicFont = fontLibrary.createScaledFont(
+ FontLibrary.FontType.NORMAL, FontLibrary.FontSize.SMALLER,
+ Font.BOLD | Font.ITALIC);
+ Font productionFont = fontLibrary.createScaledFont(
+ FontLibrary.FontType.NORMAL, FontLibrary.FontSize.TINY,
+ Font.BOLD);
+
+ /* For settlement names and territorial borders 1 extra row needs
+ to be drawn in north to prevent missing parts on partial redraws,
+ as they can reach below their tiles, see BR#2580 */
+ map.forSubMap(x0, y0-1, lastColumn-firstColumn+1, lastRow-firstRow+1+1,
+ (Tile tile) -> {
+ Settlement settlement = tile.getSettlement();
+ if(settlement == null)
+ return;
+
+ final int x = tile.getX();
+ final int y = tile.getY();
+ final int xt = (x-x0) * tileWidth + (y&1) * halfWidth;
+ final int yt = (y-y0) * halfHeight;
+ g.translate(xt, yt);
+
+ displaySettlementLabels(g, settlement, player, colonyLabels,
+ font, italicFont, productionFont);
+
+ g.translate(-xt, -yt);
+ });
+ }
+
+ // Restore original transform to allow for more drawing
+ g.setTransform(originTransform);
+
+ // Display goto path
+ if (currentPath != null) {
+ displayPath(g, currentPath);
+ }
+ if (gotoPath != null) {
+ displayPath(g, gotoPath);
}
- bottomRows = topRows;
- leftSpace = (size.width - tileWidth) / 2;
- rightSpace = leftSpace;
}
- private boolean shouldDisplayTileCursor(Tile tile) {
- return viewMode == GUI.VIEW_TERRAIN_MODE
- && tile != null && tile.equals(selectedTile);
+ private void displaySettlementLabels(Graphics2D g, Settlement settlement,
+ Player player, int colonyLabels,
+ Font font, Font italicFont,
+ Font productionFont) {
+ if (settlement.isDisposed()) {
+ logger.warning("Settlement display race detected: "
+ + settlement.getName());
+ return;
+ }
+ String name = Messages.message(settlement.getLocationLabelFor(player));
+ if (name == null) return;
+
+ Color backgroundColor = settlement.getOwner().getNationColor();
+ if (backgroundColor == null) backgroundColor = Color.WHITE;
+ // int yOffset = lib.getSettlementImage(settlement).getHeight() + 1;
+ int yOffset = tileHeight;
+ switch (colonyLabels) {
+ case ClientOptions.COLONY_LABELS_CLASSIC:
+ BufferedImage img = lib.getStringImage(g, name, backgroundColor, font);
+ g.drawImage(img, (tileWidth - img.getWidth())/2 + 1,
+ yOffset, null);
+ break;
+
+ case ClientOptions.COLONY_LABELS_MODERN:
+ default:
+ backgroundColor = new Color(backgroundColor.getRed(),
+ backgroundColor.getGreen(),
+ backgroundColor.getBlue(), 128);
+ TextSpecification[] specs = new TextSpecification[1];
+ if (settlement instanceof Colony
+ && settlement.getOwner() == player) {
+ Colony colony = (Colony) settlement;
+ BuildableType buildable = colony.getCurrentlyBuilding();
+ if (buildable != null) {
+ specs = new TextSpecification[2];
+ String t = Messages.getName(buildable) + " " +
+ Turn.getTurnsText(colony.getTurnsToComplete(buildable));
+ specs[1] = new TextSpecification(t, productionFont);
+ }
+ }
+ specs[0] = new TextSpecification(name, font);
+
+ BufferedImage nameImage = createLabel(g, specs, backgroundColor);
+ if (nameImage != null) {
+ int spacing = 3;
+ BufferedImage leftImage = null;
+ BufferedImage rightImage = null;
+ if (settlement instanceof Colony) {
+ Colony colony = (Colony)settlement;
+ String string = Integer.toString(
+ colony.getDisplayUnitCount());
+ leftImage = createLabel(g, string,
+ ((colony.getPreferredSizeChange() > 0)
+ ? italicFont : font),
+ backgroundColor);
+ if (player.owns(settlement)) {
+ int bonusProduction = colony.getProductionBonus();
+ if (bonusProduction != 0) {
+ String bonus = (bonusProduction > 0)
+ ? "+" + bonusProduction
+ : Integer.toString(bonusProduction);
+ rightImage = createLabel(g, bonus, font,
+ backgroundColor);
+ }
+ }
+ } else if (settlement instanceof IndianSettlement) {
+ IndianSettlement is = (IndianSettlement) settlement;
+ if (is.getType().isCapital()) {
+ leftImage = createCapitalLabel(
+ nameImage.getHeight(), 5, backgroundColor);
+ }
+
+ Unit missionary = is.getMissionary();
+ if (missionary != null) {
+ boolean expert = missionary.hasAbility(
+ Ability.EXPERT_MISSIONARY);
+ backgroundColor = missionary.getOwner()
+ .getNationColor();
+ backgroundColor = new Color(
+ backgroundColor.getRed(),
+ backgroundColor.getGreen(),
+ backgroundColor.getBlue(), 128);
+ rightImage = createReligiousMissionLabel(
+ nameImage.getHeight(), 5,
+ backgroundColor, expert);
+ }
+ }
+
+ int width = (int)((nameImage.getWidth()
+ * lib.getScaleFactor())
+ + ((leftImage != null)
+ ? (leftImage.getWidth()
+ * lib.getScaleFactor()) + spacing
+ : 0)
+ + ((rightImage != null)
+ ? (rightImage.getWidth()
+ * lib.getScaleFactor()) + spacing
+ : 0));
+ int labelOffset = (tileWidth - width)/2;
+ yOffset -= (nameImage.getHeight()
+ * lib.getScaleFactor())/2;
+ if (leftImage != null) {
+ g.drawImage(leftImage, labelOffset, yOffset, null);
+ labelOffset += (leftImage.getWidth()
+ * lib.getScaleFactor()) + spacing;
+ }
+ g.drawImage(nameImage, labelOffset, yOffset, null);
+ if (rightImage != null) {
+ labelOffset += (nameImage.getWidth()
+ * lib.getScaleFactor()) + spacing;
+ g.drawImage(rightImage, labelOffset, yOffset, null);
+ }
+ break;
+ }
+ }
}
- private boolean shouldDisplayUnitCursor(Unit unit) {
- return viewMode == GUI.MOVE_UNITS_MODE
- && unit == activeUnit
- && (cursor.isActive() || unit.getMovesLeft() <= 0);
+ /**
+ * Draws the pentagram indicating a native capital.
+ */
+ private static BufferedImage createCapitalLabel(int extent, int padding,
+ Color backgroundColor) {
+ // create path
+ double deg2rad = Math.PI/180.0;
+ double angle = -90.0 * deg2rad;
+ double offset = extent * 0.5;
+ double size1 = (extent - padding - padding) * 0.5;
+
+ GeneralPath path = new GeneralPath();
+ path.moveTo(Math.cos(angle) * size1 + offset, Math.sin(angle) * size1 + offset);
+ for (int i = 0; i < 4; i++) {
+ angle += 144 * deg2rad;
+ path.lineTo(Math.cos(angle) * size1 + offset, Math.sin(angle) * size1 + offset);
+ }
+ path.closePath();
+
+ // draw everything
+ BufferedImage bi = new BufferedImage(extent, extent, BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = bi.createGraphics();
+ g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g.setColor(backgroundColor);
+ g.fill(new RoundRectangle2D.Float(0, 0, extent, extent, padding, padding));
+ g.setColor(Color.BLACK);
+ g.setStroke(new BasicStroke(2.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ g.draw(path);
+ g.setColor(Color.WHITE);
+ g.fill(path);
+ g.dispose();
+ return bi;
}
+
+ /**
+ * Creates an BufferedImage that shows the given text centred on a
+ * translucent rounded rectangle with the given color.
+ *
+ * @param g a Graphics2D
+ * @param text a String
+ * @param font a Font
+ * @param backgroundColor a Color
+ * @return an BufferedImage
+ */
+ private static BufferedImage createLabel(Graphics2D g, String text,
+ Font font, Color backgroundColor) {
+ TextSpecification[] specs = new TextSpecification[1];
+ specs[0] = new TextSpecification(text, font);
+ return createLabel(g, specs, backgroundColor);
+ }
+
+ /**
+ * Creates an BufferedImage that shows the given text centred on a
+ * translucent rounded rectangle with the given color.
+ *
+ * @param g a Graphics2D
+ * @param textSpecs a TextSpecification
array
+ * @param backgroundColor a Color
+ * @return a BufferedImage
+ */
+ private static BufferedImage createLabel(Graphics2D g,
+ TextSpecification[] textSpecs,
+ Color backgroundColor) {
+ int hPadding = 15;
+ int vPadding = 10;
+ int linePadding = 5;
+ int width = 0;
+ int height = vPadding;
+ int i;
+
+ TextSpecification spec;
+ TextLayout[] labels = new TextLayout[textSpecs.length];
+ TextLayout label;
+
+ for (i = 0; i < textSpecs.length; i++) {
+ spec = textSpecs[i];
+ label = new TextLayout(spec.text, spec.font, g.getFontRenderContext());
+ labels[i] = label;
+ Rectangle textRectangle = label.getPixelBounds(null, 0, 0);
+ width = Math.max(width, textRectangle.width + hPadding);
+ if (i > 0) height += linePadding;
+ height += (int) (label.getAscent() + label.getDescent());
+ }
+
+ int radius = Math.min(hPadding, vPadding);
+
+ BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g2 = bi.createGraphics();
+ g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
+ g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g2.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
+
+ g2.setColor(backgroundColor);
+ g2.fill(new RoundRectangle2D.Float(0, 0, width, height, radius, radius));
+ g2.setColor(ImageLibrary.getForegroundColor(backgroundColor));
+ float y = vPadding / 2;
+ for (i = 0; i < labels.length; i++) {
+ Rectangle textRectangle = labels[i].getPixelBounds(null, 0, 0);
+ float x = (width - textRectangle.width) / 2;
+ y += labels[i].getAscent();
+ labels[i].draw(g2, x, y);
+ y += labels[i].getDescent() + linePadding;
+ }
+ g2.dispose();
+ return bi;
+ }
+
+ /**
+ * Draws a cross indicating a religious mission is present in the
+ * native village.
+ */
+ private static BufferedImage createReligiousMissionLabel(int extent,
+ int padding, Color backgroundColor, boolean expertMissionary) {
+ // create path
+ double offset = extent * 0.5;
+ double size1 = extent - padding - padding;
+ double bar = size1 / 3.0;
+ double inset = 0.0;
+ double kludge = 0.0;
+
+ GeneralPath circle = new GeneralPath();
+ GeneralPath cross = new GeneralPath();
+ if (expertMissionary) {
+ // this is meant to represent the eucharist (the -1, +1 thing is a nasty kludge)
+ circle.append(new Ellipse2D.Double(padding-1, padding-1, size1+1, size1+1), false);
+ inset = 4.0;
+ bar = (size1 - inset - inset) / 3.0;
+ // more nasty -1, +1 kludges
+ kludge = 1.0;
+ }
+ offset -= 1.0;
+ cross.moveTo(offset, padding + inset - kludge);
+ cross.lineTo(offset, extent - padding - inset);
+ cross.moveTo(offset - bar, padding + bar + inset);
+ cross.lineTo(offset + bar + 1, padding + bar + inset);
+
+ // draw everything
+ BufferedImage bi = new BufferedImage(extent, extent, BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = bi.createGraphics();
+ g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g.setColor(backgroundColor);
+ g.fill(new RoundRectangle2D.Float(0, 0, extent, extent, padding, padding));
+ g.setColor(ImageLibrary.getForegroundColor(backgroundColor));
+ if (expertMissionary) {
+ g.setStroke(new BasicStroke(2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ g.draw(circle);
+ g.setStroke(new BasicStroke(1.6f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ } else {
+ g.setStroke(new BasicStroke(2.4f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND));
+ }
+ g.draw(cross);
+ g.dispose();
+ return bi;
+ }
+
+
+ /**
+ * Display a path.
+ *
+ * @param g The Graphics2D
to display on.
+ * @param path The PathNode
to display.
+ */
+ private void displayPath(Graphics2D g, PathNode path) {
+ final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
+ FontLibrary.FontSize.TINY, lib.getScaleFactor());
+ final boolean debug = FreeColDebugger
+ .isInDebugMode(FreeColDebugger.DebugMode.PATHS);
+
+ for (PathNode p = path; p != null; p = p.next) {
+ Tile tile = p.getTile();
+ if (tile == null) continue;
+ Point point = calculateTilePosition(tile);
+ if (point == null) continue;
+
+ BufferedImage image = (p.isOnCarrier())
+ ? ImageLibrary.getPathImage(ImageLibrary.PathType.NAVAL)
+ : (activeUnit != null)
+ ? ImageLibrary.getPathImage(activeUnit)
+ : null;
+
+ BufferedImage turns = (p.getTurns() <= 0) ? null
+ : lib.getStringImage(g, Integer.toString(p.getTurns()),
+ Color.WHITE, font);
+ g.setColor((turns == null) ? Color.GREEN : Color.RED);
+
+ if (debug) { // More detailed display
+ if (activeUnit != null) {
+ image = ImageLibrary.getPathNextTurnImage(activeUnit);
+ }
+ turns = lib.getStringImage(g, Integer.toString(p.getTurns())
+ + "/" + Integer.toString(p.getMovesLeft()),
+ Color.WHITE, font);
+ }
+
+ g.translate(point.x, point.y);
+ if (image == null) {
+ g.fillOval(halfWidth, halfHeight, 10, 10);
+ g.setColor(Color.BLACK);
+ g.drawOval(halfWidth, halfHeight, 10, 10);
+ } else {
+ tv.displayCenteredImage(g, image);
+ if (turns != null) {
+ tv.displayCenteredImage(g, turns);
+ }
+ }
+ g.translate(-point.x, -point.y);
+ }
+ }
+
+ /**
+ * Displays the given Unit onto the given Graphics2D object at the
+ * location specified by the coordinates.
+ *
+ * @param g The Graphics2D object on which to draw the Unit.
+ * @param unit The Unit to draw.
+ */
+ private void displayUnit(Graphics2D g, Unit unit) {
+ final Player player = freeColClient.getMyPlayer();
+
+ // Draw the unit.
+ // If unit is sentry, draw in grayscale
+ boolean fade = (unit.getState() == Unit.UnitState.SENTRY)
+ || (unit.hasTile()
+ && player != null && !player.canSee(unit.getTile()));
+ BufferedImage image = lib.getUnitImage(unit, fade);
+ Point p = calculateUnitImagePositionInTile(image);
+ g.drawImage(image, p.x, p.y, null);
+
+ // Draw an occupation and nation indicator.
+ String text = Messages.message(unit.getOccupationLabel(player, false));
+ g.drawImage(lib.getOccupationIndicatorChip(g, unit, text),
+ (int)(TileViewer.STATE_OFFSET_X * lib.getScaleFactor()), 0,
+ null);
+
+ // Draw one small line for each additional unit (like in civ3).
+ int unitsOnTile = 0;
+ if (unit.hasTile()) {
+ // When a unit is moving from tile to tile, it is
+ // removed from the source tile. So the unit stack
+ // indicator cannot be drawn during the movement see
+ // UnitMoveAnimation.animate() for details
+ unitsOnTile = unit.getTile().getTotalUnitCount();
+ }
+ if (unitsOnTile > 1) {
+ g.setColor(Color.WHITE);
+ int unitLinesY = OTHER_UNITS_OFFSET_Y;
+ int x1 = (int)((TileViewer.STATE_OFFSET_X + OTHER_UNITS_OFFSET_X)
+ * lib.getScaleFactor());
+ int x2 = (int)((TileViewer.STATE_OFFSET_X + OTHER_UNITS_OFFSET_X
+ + OTHER_UNITS_WIDTH) * lib.getScaleFactor());
+ for (int i = 0; i < unitsOnTile && i < MAX_OTHER_UNITS; i++) {
+ g.drawLine(x1, unitLinesY, x2, unitLinesY);
+ unitLinesY += 2;
+ }
+ }
+
+ // FOR DEBUGGING
+ net.sf.freecol.server.ai.AIUnit au;
+ if (FreeColDebugger.isInDebugMode(FreeColDebugger.DebugMode.MENUS)
+ && player != null
+ && !player.owns(unit)
+ && unit.getOwner().isAI()
+ && freeColClient.getFreeColServer() != null
+ && (au = freeColClient.getFreeColServer().getAIMain()
+ .getAIUnit(unit)) != null) {
+ if (FreeColDebugger.debugShowMission()) {
+ g.setColor(Color.WHITE);
+ g.drawString((!au.hasMission()) ? "No mission"
+ : lastPart(au.getMission().getClass().toString(), "."),
+ 0, 0);
+ }
+ if (FreeColDebugger.debugShowMissionInfo() && au.hasMission()) {
+ g.setColor(Color.WHITE);
+ g.drawString(au.getMission().toString(), 0, 25);
+ }
+ }
+ }
+
+ /**
+ * Gets the coordinates to draw a unit in a given tile.
+ *
+ * @param unitImage The unit's image
+ * @return The coordinates where the unit should be drawn onscreen
+ */
+ private Point calculateUnitImagePositionInTile(BufferedImage unitImage) {
+ int unitX = (tileWidth - unitImage.getWidth()) / 2;
+ int unitY = (tileHeight - unitImage.getHeight()) / 2 -
+ (int) (UNIT_OFFSET * lib.getScaleFactor());
+
+ return new Point(unitX, unitY);
+ }
+
+ private void displayCursor(Graphics2D g) {
+ BufferedImage cursorImage = lib.getMiscImage(ImageLibrary.UNIT_SELECT);
+ g.drawImage(cursorImage, 0, 0, null);
+ }
+
+ /**
+ * Draws the borders of a territory on the given Tile. The
+ * territory is either a country or a region.
+ *
+ * @param g a Graphics2D
+ * @param tile a Tile
+ * @param type a BorderType
+ * @param opaque a boolean
+ */
+ private void displayTerritorialBorders(Graphics2D g, Tile tile, BorderType type, boolean opaque) {
+ Player owner = tile.getOwner();
+ Region region = tile.getRegion();
+ if ((type == BorderType.COUNTRY && owner != null)
+ || (type == BorderType.REGION && region != null)) {
+ Stroke oldStroke = g.getStroke();
+ g.setStroke(borderStroke);
+ Color oldColor = g.getColor();
+ Color c = null;
+ if (type == BorderType.COUNTRY)
+ c = owner.getNationColor();
+ if (c == null)
+ c = Color.WHITE;
+ Color newColor = new Color(c.getRed(), c.getGreen(), c.getBlue(),
+ (opaque) ? 255 : 100);
+ g.setColor(newColor);
+ GeneralPath path = new GeneralPath(GeneralPath.WIND_EVEN_ODD);
+ path.moveTo(borderPoints.get(Direction.longSides.get(0)).x,
+ borderPoints.get(Direction.longSides.get(0)).y);
+ for (Direction d : Direction.longSides) {
+ Tile otherTile = tile.getNeighbourOrNull(d);
+ Direction next = d.getNextDirection();
+ Direction next2 = next.getNextDirection();
+ if (otherTile == null
+ || (type == BorderType.COUNTRY && !owner.owns(otherTile))
+ || (type == BorderType.REGION && otherTile.getRegion() != region)) {
+ Tile tile1 = tile.getNeighbourOrNull(next);
+ Tile tile2 = tile.getNeighbourOrNull(next2);
+ if (tile2 == null
+ || (type == BorderType.COUNTRY && !owner.owns(tile2))
+ || (type == BorderType.REGION && tile2.getRegion() != region)) {
+ // small corner
+ path.lineTo(borderPoints.get(next).x,
+ borderPoints.get(next).y);
+ path.quadTo(controlPoints.get(next).x,
+ controlPoints.get(next).y,
+ borderPoints.get(next2).x,
+ borderPoints.get(next2).y);
+ } else {
+ int dx = 0, dy = 0;
+ switch(d) {
+ case NW: dx = halfWidth; dy = -halfHeight; break;
+ case NE: dx = halfWidth; dy = halfHeight; break;
+ case SE: dx = -halfWidth; dy = halfHeight; break;
+ case SW: dx = -halfWidth; dy = -halfHeight; break;
+ default: break;
+ }
+ if (tile1 != null
+ && ((type == BorderType.COUNTRY && owner.owns(tile1))
+ || (type == BorderType.REGION && tile1.getRegion() == region))) {
+ // short straight line
+ path.lineTo(borderPoints.get(next).x,
+ borderPoints.get(next).y);
+ // big corner
+ Direction previous = d.getPreviousDirection();
+ Direction previous2 = previous.getPreviousDirection();
+ int ddx = 0, ddy = 0;
+ switch(d) {
+ case NW: ddy = -tileHeight; break;
+ case NE: ddx = tileWidth; break;
+ case SE: ddy = tileHeight; break;
+ case SW: ddx = -tileWidth; break;
+ default: break;
+ }
+ path.quadTo(controlPoints.get(previous).x + dx,
+ controlPoints.get(previous).y + dy,
+ borderPoints.get(previous2).x + ddx,
+ borderPoints.get(previous2).y + ddy);
+ } else {
+ // straight line
+ path.lineTo(borderPoints.get(d).x + dx,
+ borderPoints.get(d).y + dy);
+ }
+ }
+ } else {
+ path.moveTo(borderPoints.get(next2).x,
+ borderPoints.get(next2).y);
+ }
+ }
+ g.draw(path);
+ g.setColor(oldColor);
+ g.setStroke(oldStroke);
+ }
+ }
+
}
diff --git a/src/net/sf/freecol/client/gui/OutForAnimationCallback.java b/src/net/sf/freecol/client/gui/OutForAnimationCallback.java
index 2abfde808..3dc72f17f 100644
--- a/src/net/sf/freecol/client/gui/OutForAnimationCallback.java
+++ b/src/net/sf/freecol/client/gui/OutForAnimationCallback.java
@@ -30,9 +30,9 @@ public interface OutForAnimationCallback {
/**
* The code to be executed when a unit is out for animation.
+ *
* @param unitLabel A JLabel
with an image of
- * the unit provided as a parameter to
- * {@link MapViewer#executeWithUnitOutForAnimation(net.sf.freecol.common.model.Unit, net.sf.freecol.common.model.Tile, OutForAnimationCallback)}.
+ * the unit to animate.
*/
- public void executeWithUnitOutForAnimation(JLabel unitLabel);
+ void executeWithUnitOutForAnimation(JLabel unitLabel);
}
diff --git a/src/net/sf/freecol/client/gui/RoadPainter.java b/src/net/sf/freecol/client/gui/RoadPainter.java
index 1d4fc61ef..1ffdba487 100644
--- a/src/net/sf/freecol/client/gui/RoadPainter.java
+++ b/src/net/sf/freecol/client/gui/RoadPainter.java
@@ -21,8 +21,8 @@ package net.sf.freecol.client.gui;
import java.awt.BasicStroke;
import java.awt.Color;
+import java.awt.Dimension;
import java.awt.Graphics2D;
-import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
@@ -31,8 +31,10 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
+import java.util.stream.Collectors;
import net.sf.freecol.common.model.Direction;
+import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.TileImprovement;
import net.sf.freecol.common.resources.ResourceManager;
@@ -52,12 +54,10 @@ public final class RoadPainter {
new EnumMap<>(Direction.class);
private Stroke roadStroke = new BasicStroke(2);
- public RoadPainter(ImageLibrary lib) {
- // ATTENTION: we assume that all base tiles have the same size
- Image unexplored = lib.getTerrainImage(null, 0, 0);
- tileHeight = unexplored.getHeight(null);
+ public RoadPainter(Dimension tileSize) {
+ tileHeight = tileSize.height;
+ tileWidth = tileSize.width;
halfHeight = tileHeight/2;
- tileWidth = unexplored.getWidth(null);
halfWidth = tileWidth/2;
int dy = tileHeight/16;
@@ -97,20 +97,23 @@ public final class RoadPainter {
Color oldColor = g.getColor();
g.setColor(ResourceManager.getColor("color.map.road"));
g.setStroke(roadStroke);
- g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+ g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
+ RenderingHints.VALUE_ANTIALIAS_ON);
GeneralPath path = new GeneralPath();
+ Map map = tile.getMap();
+ int x = tile.getX();
+ int y = tile.getY();
List points = new ArrayList<>(8);
- List directions = new ArrayList<>(8);
- for (Direction direction : Direction.values()) {
- Tile borderingTile = tile.getNeighbourOrNull(direction);
- TileImprovement r;
- if (borderingTile != null
- && (r = borderingTile.getRoad()) != null
- && r.isComplete()) {
- points.add(corners.get(direction));
- directions.add(direction);
- }
- }
+ List directions = Direction.allDirections.stream()
+ .filter((Direction direction) -> {
+ Tile borderingTile = map.getTile(direction.step(x, y));
+ TileImprovement r;
+ return (borderingTile != null
+ && (r = borderingTile.getRoad()) != null
+ && r.isComplete());
+ })
+ .peek((Direction direction) -> points.add(corners.get(direction)))
+ .collect(Collectors.toList());
switch(points.size()) {
case 0:
diff --git a/src/net/sf/freecol/client/gui/ScrollThread.java b/src/net/sf/freecol/client/gui/ScrollThread.java
index 6e8069d3e..b885d50af 100644
--- a/src/net/sf/freecol/client/gui/ScrollThread.java
+++ b/src/net/sf/freecol/client/gui/ScrollThread.java
@@ -39,8 +39,8 @@ public class ScrollThread extends Thread {
/** Delay between scroll steps. */
private static final int SCROLL_DELAY = 100; // ms
- /** The map viewer to scroll. */
- private final MapViewer mapViewer;
+ /** The Canvas containing the map to scroll. */
+ private final Canvas canvas;
/** The direction to scroll in. */
private Direction direction = null;
@@ -49,12 +49,11 @@ public class ScrollThread extends Thread {
/**
* The constructor to use.
*
- * @param mapViewer The GUI that holds information such as screen
- * resolution.
+ * @param canvas The Canvas containing the map to scroll.
*/
- public ScrollThread(MapViewer mapViewer) {
+ public ScrollThread(Canvas canvas) {
super(FreeCol.CLIENT_THREAD + "Mouse scroller");
- this.mapViewer = mapViewer;
+ this.canvas = canvas;
}
/**
@@ -75,14 +74,9 @@ public class ScrollThread extends Thread {
public void run() {
while (direction != null) {
try {
- SwingUtilities.invokeAndWait(new Runnable() {
- @Override
- public void run() {
- if (!mapViewer.scrollMap(direction)) {
- direction = null;
- }
- }
- });
+ SwingUtilities.invokeAndWait(() -> {
+ if (!canvas.scrollMap(direction)) direction = null;
+ });
} catch (InvocationTargetException e) {
logger.log(Level.WARNING, "Scroll thread caught error", e);
break;
diff --git a/src/net/sf/freecol/client/gui/SwingGUI.java b/src/net/sf/freecol/client/gui/SwingGUI.java
index 14c27a3fb..772e5bce5 100644
--- a/src/net/sf/freecol/client/gui/SwingGUI.java
+++ b/src/net/sf/freecol/client/gui/SwingGUI.java
@@ -23,28 +23,29 @@ import java.awt.Component;
import java.awt.Dimension;
import java.awt.DisplayMode;
import java.awt.Font;
+import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
-import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Rectangle;
-import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
+import java.awt.image.BufferedImage;
import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
import java.io.File;
+import java.io.InputStream;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
+import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JWindow;
@@ -54,14 +55,11 @@ import javax.swing.filechooser.FileFilter;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.animation.Animations;
-import net.sf.freecol.client.gui.panel.ChoiceItem;
import net.sf.freecol.client.gui.panel.ColonyPanel;
import net.sf.freecol.client.gui.panel.ColorChooserPanel;
import net.sf.freecol.client.gui.panel.CornerMapControls;
-import net.sf.freecol.client.gui.panel.DialogHandler;
import net.sf.freecol.client.gui.panel.FreeColDialog;
import net.sf.freecol.client.gui.panel.LabourData.UnitData;
-import net.sf.freecol.client.gui.panel.LoadingSavegameDialog;
import net.sf.freecol.client.gui.panel.MapControls;
import net.sf.freecol.client.gui.panel.Parameters;
import net.sf.freecol.client.gui.panel.TradeRoutePanel;
@@ -86,12 +84,13 @@ import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Monarch.MonarchAction;
+import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.Player;
-import net.sf.freecol.common.model.Region;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
+import net.sf.freecol.common.model.TileType;
import net.sf.freecol.common.model.TradeRoute;
import net.sf.freecol.common.model.TypeCountMap;
import net.sf.freecol.common.model.Unit;
@@ -116,14 +115,14 @@ public class SwingGUI extends GUI {
private final GraphicsDevice graphicsDevice;
/**
- * This is the MapViewer instance used to paint the colony tiles
+ * This is the TileViewer instance used to paint the map tiles
* in the ColonyPanel and other panels. It should not be scaled
* along with the default MapViewer.
*/
- private MapViewer colonyTileMapViewer;
+ private TileViewer tileViewer;
/**
- * The MapViewer instance used to paint the main map.
+ * The MapViewer instance used by canvas to paint the main map.
* This does need to be scaled.
*/
private MapViewer mapViewer;
@@ -151,14 +150,12 @@ public class SwingGUI extends GUI {
// Simple accessors
- @Override
public Canvas getCanvas() {
return canvas;
}
- @Override
- public MapViewer getColonyTileMapViewer() {
- return colonyTileMapViewer;
+ public ImageLibrary getTileImageLibrary() {
+ return tileViewer.getImageLibrary();
}
@Override
@@ -178,7 +175,7 @@ public class SwingGUI extends GUI {
FreeColLookAndFeel fclaf = new FreeColLookAndFeel();
FreeColLookAndFeel.install(fclaf);
Font font = FontLibrary.createMainFont(
- fontName, imageLibrary.getScalingFactor());
+ fontName, imageLibrary.getScaleFactor());
FreeColLookAndFeel.installFont(font);
Utility.initStyleContext(font);
}
@@ -204,7 +201,7 @@ public class SwingGUI extends GUI {
canvas.initializeInGame();
enableMapControls(freeColClient.getClientOptions()
.getBoolean(ClientOptions.DISPLAY_MAP_CONTROLS));
- setSelectedTile(tile, false);
+ setSelectedTile(tile);
}
/**
@@ -218,15 +215,14 @@ public class SwingGUI extends GUI {
/**
* Display the splash screen.
*
- * @param splashFilename The name of the file to find the image in.
+ * @param splashStream A stream to read the splash image from.
*/
@Override
- public void displaySplashScreen(final String splashFilename) {
+ public void displaySplashScreen(final InputStream splashStream) {
splash = null;
- if (splashFilename == null)
- return;
+ if (splashStream == null) return;
try {
- Image im = Toolkit.getDefaultToolkit().getImage(splashFilename);
+ BufferedImage im = ImageIO.read(splashStream);
splash = new JWindow(graphicsDevice.getDefaultConfiguration());
splash.getContentPane().add(new JLabel(new ImageIcon(im)));
splash.pack();
@@ -309,7 +305,7 @@ public class SwingGUI extends GUI {
}
@Override
- public void actionPerformed(ActionEvent e8) {
+ public void actionPerformed(ActionEvent ae8) {
execute();
}
@@ -327,7 +323,7 @@ public class SwingGUI extends GUI {
if (t != null) {
t.stop();
}
- freeColClient.getSoundController().playSound("sound.intro.general");
+ playSound("sound.intro.general");
showMainPanel(userMsg);
}
}
@@ -401,55 +397,45 @@ public class SwingGUI extends GUI {
logger.info(pmoffscreen + " overrides client option: "
+ pmoffscreenValue);
}
- usePixmaps.addPropertyChangeListener(new PropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent e) {
- String newValue = e.getNewValue().toString();
- System.setProperty(pmoffscreen, newValue);
- logger.info("Set " + pmoffscreen + " to: " + newValue);
- }
+ usePixmaps.addPropertyChangeListener((PropertyChangeEvent e) -> {
+ String newValue = e.getNewValue().toString();
+ System.setProperty(pmoffscreen, newValue);
+ logger.info("Set " + pmoffscreen + " to: " + newValue);
});
this.mapViewer = new MapViewer(freeColClient);
- this.canvas = new Canvas(freeColClient, graphicsDevice,
+ this.canvas = new Canvas(freeColClient, graphicsDevice, this,
desiredWindowSize, mapViewer);
- this.colonyTileMapViewer = new MapViewer(freeColClient);
+ this.tileViewer = new TileViewer(freeColClient);
// Now that there is a canvas, prepare for language changes.
LanguageOption o = (LanguageOption)freeColClient.getClientOptions()
.getOption(ClientOptions.LANGUAGE);
- o.addPropertyChangeListener(new PropertyChangeListener() {
- @Override
- public void propertyChange(PropertyChangeEvent e) {
- Language language = (Language)e.getNewValue();
- logger.info("Set language to: " + language);
- if (Messages.AUTOMATIC.equalsIgnoreCase(language.getKey())) {
- showInformationMessage("info.autodetectLanguageSelected");
- } else {
- Locale l = language.getLocale();
- Messages.loadMessageBundle(l);
- Messages.loadModMessageBundle(l);
- showInformationMessage(StringTemplate
- .template("info.newLanguageSelected")
- .addName("%language%", l.getDisplayName()));
- }
+ o.addPropertyChangeListener((PropertyChangeEvent e) -> {
+ Language language = (Language)e.getNewValue();
+ logger.info("Set language to: " + language);
+ if (Messages.AUTOMATIC.equalsIgnoreCase(language.getKey())) {
+ showInformationMessage("info.autodetectLanguageSelected");
+ } else {
+ Locale l = language.getLocale();
+ Messages.loadMessageBundle(l);
+ Messages.loadModMessageBundle(l);
+ showInformationMessage(StringTemplate
+ .template("info.newLanguageSelected")
+ .addName("%language%", l.getDisplayName()));
}
});
- mapViewer.startCursorBlinking();
logger.info("GUI created.");
logger.info("Starting in Move Units View Mode");
}
/**
* Change the windowed mode.
- *
- * @param windowed Use true
for windowed mode
- * and false
for fullscreen mode.
*/
@Override
- public void changeWindowedMode(boolean windowed) {
- canvas.changeWindowedMode(windowed);
+ public void changeWindowedMode() {
+ canvas.changeWindowedMode();
}
/**
@@ -484,7 +470,7 @@ public class SwingGUI extends GUI {
// CanvasMouseMotionListener.
Point pt = canvas.getMousePosition();
if (pt != null) {
- Tile tile = mapViewer.convertToMapTile(pt.x, pt.y);
+ Tile tile = canvas.convertToMapTile(pt.x, pt.y);
if (tile != null && unit.getTile() != tile) {
canvas.setGotoPath(unit.findPath(tile));
}
@@ -502,7 +488,6 @@ public class SwingGUI extends GUI {
// Action should be disabled if there is no active unit, but make sure
if (unit == null) return;
canvas.stopGoto();
- refresh();
}
/**
@@ -535,7 +520,6 @@ public class SwingGUI extends GUI {
*
* @param tile The Tile
to refresh.
*/
- @Override
public void refreshTile(Tile tile) {
if (tile.getX() >= 0 && tile.getY() >= 0) {
canvas.repaint(mapViewer.calculateTileBounds(tile));
@@ -547,6 +531,7 @@ public class SwingGUI extends GUI {
*/
@Override
public void resetMenuBar() {
+ freeColClient.updateActions();
canvas.resetMenuBar();
}
@@ -585,28 +570,51 @@ public class SwingGUI extends GUI {
* Set the active unit.
*
* @param unit The Unit
to activate.
+ * @return True if the focus was set.
*/
@Override
- public void setActiveUnit(Unit unit) {
- mapViewer.setActiveUnit(unit);
+ public boolean setActiveUnit(Unit unit) {
+ boolean result = mapViewer.setActiveUnit(unit);
updateMapControls();
+ updateMenuBar();
if (unit != null && !freeColClient.getMyPlayer().owns(unit)) {
canvas.refresh();
}
- canvas.updateMenuBar();
+ return result;
}
/**
* Update the menu bar.
+ *
+ * Always update the actions first so that the enabled/disabled
+ * state is correct.
*/
@Override
public void updateMenuBar() {
+ freeColClient.updateActions();
canvas.updateMenuBar();
}
// Animation handling
+ /**
+ * Require the given tile to be in the onScreen()-area.
+ *
+ * @param tile The Tile
to check.
+ * @return True if the focus was set.
+ */
+ public boolean requireFocus(Tile tile) {
+ // Account for the ALWAYS_CENTER client option.
+ boolean required = freeColClient.getClientOptions()
+ .getBoolean(ClientOptions.ALWAYS_CENTER);
+ if ((required && tile != getFocus()) || !mapViewer.onScreen(tile)) {
+ setFocusImmediately(tile);
+ return true;
+ }
+ return false;
+ }
+
/**
* Animate a unit attack.
*
@@ -620,7 +628,8 @@ public class SwingGUI extends GUI {
public void animateUnitAttack(Unit attacker, Unit defender,
Tile attackerTile, Tile defenderTile,
boolean success) {
- Animations.unitAttack(this, attacker, defender,
+ requireFocus(attackerTile);
+ Animations.unitAttack(freeColClient, attacker, defender,
attackerTile, defenderTile, success);
}
@@ -633,7 +642,8 @@ public class SwingGUI extends GUI {
*/
@Override
public void animateUnitMove(Unit unit, Tile srcTile, Tile dstTile) {
- Animations.unitMove(this, unit, srcTile, dstTile);
+ requireFocus(srcTile);
+ Animations.unitMove(freeColClient, unit, srcTile, dstTile);
}
@@ -680,7 +690,6 @@ public class SwingGUI extends GUI {
if (mapControls != null) mapControls.update();
}
- @Override
public void updateMapControlsInCanvas() {
if (mapControls == null) return;
mapControls.removeFromComponent(canvas);
@@ -725,7 +734,7 @@ public class SwingGUI extends GUI {
// Dialogs that return values
/**
- * Simple confirmation dialog.
+ * Simple modal confirmation dialog.
*
* @param textKey A string to use as the message key.
* @param okKey A key for the "ok" button.
@@ -734,15 +743,13 @@ public class SwingGUI extends GUI {
*/
@Override
public boolean confirm(String textKey, String okKey, String cancelKey) {
- return canvas.showConfirmDialog(true, null,
- Messages.message(textKey), null,
- okKey, cancelKey);
+ return canvas.showConfirmDialog(null, Messages.message(textKey),
+ null, okKey, cancelKey);
}
/**
- * General confirmation dialog.
+ * General modal confirmation dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param template The StringTemplate
explaining the choice.
* @param okKey A key for the "ok" button.
@@ -750,54 +757,49 @@ public class SwingGUI extends GUI {
* @return True if the "ok" button was selected.
*/
@Override
- public boolean confirm(boolean modal, Tile tile,
- StringTemplate template,
+ public boolean confirm(Tile tile, StringTemplate template,
String okKey, String cancelKey) {
- return canvas.showConfirmDialog(modal, tile,
- Utility.localizedTextArea(template),
- null, okKey, cancelKey);
+ return canvas.showConfirmDialog(tile,
+ Utility.localizedTextArea(template), null, okKey, cancelKey);
}
/**
- * General confirmation dialog.
+ * General modal confirmation dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param template The StringTemplate
explaining the choice.
- * @param obj An optional unit to make an icon for the dialog from.
+ * @param unit An optional unit to make an icon for the dialog from.
* @param okKey A key for the "ok" button.
* @param cancelKey A key for the "cancel" button.
* @return True if the "ok" button was selected.
*/
@Override
- public boolean confirm(boolean modal, Tile tile,
- StringTemplate template, Unit obj,
+ public boolean confirm(Tile tile, StringTemplate template, Unit unit,
String okKey, String cancelKey) {
- return canvas.showConfirmDialog(modal, tile,
- Utility.localizedTextArea(template),
- (obj == null) ? null : new ImageIcon(
- imageLibrary.getUnitImage(obj)),
- okKey, cancelKey);
+ return canvas.showConfirmDialog(tile,
+ Utility.localizedTextArea(template),
+ new ImageIcon(imageLibrary.getUnitImage(unit)),
+ okKey, cancelKey);
}
- /**
- * General confirmation dialog.
- *
- * @param modal Is this a modal dialog?
- * @param tile An optional Tile
to expose.
- * @param template The StringTemplate
explaining the choice.
- * @param icon An optional icon for the dialog.
- * @param okKey A key for the "ok" button.
- * @param cancelKey A key for the "cancel" button.
- * @return True if the "ok" button was selected.
- */
@Override
- public boolean confirm(boolean modal, Tile tile,
- StringTemplate template, ImageIcon icon,
+ public boolean confirm(Tile tile, StringTemplate template,
+ Settlement settlement,
String okKey, String cancelKey) {
- return canvas.showConfirmDialog(modal, tile,
- Utility.localizedTextArea(template),
- icon, okKey, cancelKey);
+ return canvas.showConfirmDialog(tile,
+ Utility.localizedTextArea(template),
+ new ImageIcon(imageLibrary.getSettlementImage(settlement)),
+ okKey, cancelKey);
+ }
+
+ @Override
+ public boolean confirm(Tile tile, StringTemplate template,
+ GoodsType goodsType,
+ String okKey, String cancelKey) {
+ return canvas.showConfirmDialog(tile,
+ Utility.localizedTextArea(template),
+ new ImageIcon(imageLibrary.getIconImage(goodsType)),
+ okKey, cancelKey);
}
/**
@@ -811,29 +813,57 @@ public class SwingGUI extends GUI {
}
/**
- * General choice dialog.
+ * General modal choice dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param explain An object explaining the choice.
- * @param icon An optional icon for the dialog.
* @param cancelKey A key for the "cancel" button.
* @param choices A list a ChoiceItem
s to choose from.
* @return The selected value of the selected ChoiceItem
,
* or null if cancelled.
*/
@Override
- public T getChoice(boolean modal, Tile tile, Object explain,
- ImageIcon icon,
+ public T getChoice(Tile tile, Object explain,
String cancelKey, List> choices) {
- return canvas.showChoiceDialog(modal, tile, explain, icon,
- cancelKey, choices);
+ return canvas.showChoiceDialog(tile, explain,
+ null, cancelKey, choices);
+ }
+
+ @Override
+ public T getChoice(Tile tile, Object explain, Unit unit,
+ String cancelKey, List> choices) {
+ return canvas.showChoiceDialog(tile, explain,
+ new ImageIcon(imageLibrary.getUnitImage(unit)),
+ cancelKey, choices);
+ }
+
+ @Override
+ public T getChoice(Tile tile, Object explain, Settlement settlement,
+ String cancelKey, List> choices) {
+ return canvas.showChoiceDialog(tile, explain,
+ new ImageIcon(imageLibrary.getSettlementImage(settlement)),
+ cancelKey, choices);
+ }
+
+ @Override
+ public T getChoice(Tile tile, Object explain, GoodsType goodsType,
+ String cancelKey, List> choices) {
+ return canvas.showChoiceDialog(tile, explain,
+ new ImageIcon(imageLibrary.getIconImage(goodsType)),
+ cancelKey, choices);
+ }
+
+ @Override
+ public T getChoice(Tile tile, Object explain, Nation nation,
+ String cancelKey, List> choices) {
+ return canvas.showChoiceDialog(tile, explain,
+ new ImageIcon(imageLibrary.getMiscIconImage(nation)),
+ cancelKey, choices);
}
/**
- * General input dialog.
+ * General modal string input dialog.
*
- * @param modal Is this a modal dialog?
* @param tile An optional Tile
to expose.
* @param template A StringTemplate
explaining the choice.
* @param defaultValue The default value to show initially.
@@ -842,9 +872,10 @@ public class SwingGUI extends GUI {
* @return The chosen value.
*/
@Override
- public String getInput(boolean modal, Tile tile, StringTemplate template,
- String defaultValue, String okKey, String cancelKey) {
- return canvas.showInputDialog(modal, tile, template, defaultValue,
+ public String getInput(Tile tile, StringTemplate template,
+ String defaultValue,
+ String okKey, String cancelKey) {
+ return canvas.showInputDialog(tile, template, defaultValue,
okKey, cancelKey);
}
@@ -871,7 +902,6 @@ public class SwingGUI extends GUI {
return canvas.containsInGameComponents();
}
- @Override
public void dialogRemove(FreeColDialog> fcd) {
canvas.dialogRemove(fcd);
}
@@ -883,7 +913,6 @@ public class SwingGUI extends GUI {
*
* @param fco The FreeColObject
to display.
*/
- @Override
public void displayObject(FreeColObject fco) {
if (fco instanceof Colony) {
canvas.showColonyPanel((Colony)fco, null);
@@ -901,13 +930,13 @@ public class SwingGUI extends GUI {
displayObject((FreeColObject)loc);
}
} else if (fco instanceof WorkLocation) {
- displayObject(((WorkLocation)fco).getColony());
+ canvas.showColonyPanel(((WorkLocation)fco).getColony(), null);
}
}
@Override
- public LoadingSavegameDialog getLoadingSavegameDialog() {
- return canvas.getLoadingSavegameDialog();
+ public LoadingSavegameInfo getLoadingSavegameInfo() {
+ return canvas.getLoadingSavegameDialog().getInfo();
}
@Override
@@ -940,7 +969,6 @@ public class SwingGUI extends GUI {
canvas.refreshPlayersTable();
}
- @Override
public void removeFromCanvas(Component component) {
canvas.remove(component);
}
@@ -950,7 +978,6 @@ public class SwingGUI extends GUI {
canvas.removeInGameComponents();
}
- @Override
public void removeTradeRoutePanel(TradeRoutePanel panel) {
canvas.removeTradeRoutePanel(panel);
}
@@ -965,12 +992,10 @@ public class SwingGUI extends GUI {
return canvas.requestFocusInWindow();
}
- @Override
public void restoreSavedSize(Component comp, int w, int h) {
canvas.restoreSavedSize(comp, new Dimension(w, h));
}
- @Override
public void restoreSavedSize(Component comp, Dimension size) {
canvas.restoreSavedSize(comp, size);
}
@@ -978,7 +1003,7 @@ public class SwingGUI extends GUI {
@Override
public void returnToTitle() {
canvas.returnToTitle();
- freeColClient.getSoundController().playSound("sound.intro.general");
+ playSound("sound.intro.general");
}
@Override
@@ -986,26 +1011,18 @@ public class SwingGUI extends GUI {
canvas.showAboutPanel();
}
- @Override
public void showBuildQueuePanel(Colony colony) {
canvas.showBuildQueuePanel(colony);
}
- @Override
public void showBuildQueuePanel(Colony colony, Runnable callBack) {
canvas.showBuildQueuePanel(colony, callBack);
}
@Override
public void showCaptureGoodsDialog(final Unit unit, List gl,
- final String defenderId) {
- canvas.showCaptureGoodsDialog(unit, gl,
- new DialogHandler>() {
- @Override
- public void handle(List gl) {
- igc().lootCargo(unit, gl, defenderId);
- }
- });
+ DialogHandler> handler) {
+ canvas.showCaptureGoodsDialog(unit, gl, handler);
}
@Override
@@ -1014,21 +1031,24 @@ public class SwingGUI extends GUI {
}
@Override
- public void showChooseFoundingFatherDialog(final List ffs) {
- canvas.showChooseFoundingFatherDialog(ffs,
- new DialogHandler() {
- @Override
- public void handle(FoundingFather ff) {
- igc().chooseFoundingFather(ffs, ff);
- }
- });
+ public void showChooseFoundingFatherDialog(final List ffs,
+ DialogHandler handler) {
+ canvas.showChooseFoundingFatherDialog(ffs, handler);
}
@Override
- public OptionGroup showClientOptionsDialog() {
- OptionGroup group = canvas.showClientOptionsDialog();
+ public void showClientOptionsDialog() {
+ OptionGroup group = null;
+ try {
+ group = canvas.showClientOptionsDialog();
+ } finally {
+ if (group != null) {
+ resetMenuBar();
+ // Immediately redraw the minimap if that was updated.
+ updateMapControls();
+ }
+ }
if (!freeColClient.isInGame()) showMainPanel(null);
- return group;
}
@Override
@@ -1037,7 +1057,11 @@ public class SwingGUI extends GUI {
}
@Override
- public ColonyPanel showColonyPanel(Colony colony, Unit unit) {
+ public void showColonyPanel(Colony colony, Unit unit) {
+ canvas.showColonyPanel(colony, unit);
+ }
+
+ public ColonyPanel showColonyPanel2(Colony colony, Unit unit) {
return canvas.showColonyPanel(colony, unit);
}
@@ -1046,7 +1070,6 @@ public class SwingGUI extends GUI {
canvas.showColopediaPanel(nodeId);
}
- @Override
public ColorChooserPanel showColorChooserPanel(ActionListener al) {
return canvas.showColorChooserPanel(al);
}
@@ -1056,7 +1079,6 @@ public class SwingGUI extends GUI {
canvas.showCompactLabourReport();
}
- @Override
public void showCompactLabourReport(UnitData unitData) {
canvas.showCompactLabourReport(unitData);
}
@@ -1066,26 +1088,28 @@ public class SwingGUI extends GUI {
canvas.showDeclarationPanel();
}
+ /**
+ * Display a difficulty dialog allowing only viewing of game options.
+ *
+ * @return The resulting OptionGroup
.
+ */
@Override
public OptionGroup showDifficultyDialog() {
- return canvas.showDifficultyDialog();
+ Game game = freeColClient.getGame();
+ Specification spec = game.getSpecification();
+ return canvas.showDifficultyDialog(spec,
+ spec.getDifficultyOptionGroup(), false);
}
- @Override
public OptionGroup showDifficultyDialog(Specification spec,
OptionGroup group) {
- return canvas.showDifficultyDialog(spec, group);
+ return canvas.showDifficultyDialog(spec, group, group.isEditable());
}
@Override
- public void showDumpCargoDialog(Unit unit) {
- canvas.showDumpCargoDialog(unit,
- new DialogHandler>() {
- @Override
- public void handle(List goodsList) {
- for (Goods g : goodsList) igc().unloadCargo(g, true);
- }
- });
+ public void showDumpCargoDialog(Unit unit,
+ DialogHandler> handler) {
+ canvas.showDumpCargoDialog(unit, handler);
}
@Override
@@ -1094,31 +1118,16 @@ public class SwingGUI extends GUI {
}
@Override
- public void showEmigrationDialog(final Player player, final int n,
- final boolean fountainOfYouth) {
- canvas.showEmigrationDialog(player, fountainOfYouth,
- new DialogHandler() {
- @Override
- public void handle(Integer value) {
- // Value should be a valid slot
- igc().emigrate(player,
- Europe.MigrationType.convertToMigrantSlot(value));
- igc().emigrationLoop(player, n-1, fountainOfYouth);
- }
- });
+ public void showEmigrationDialog(final Player player,
+ final boolean fountainOfYouth,
+ DialogHandler handler) {
+ canvas.showEmigrationDialog(player, fountainOfYouth, handler);
}
@Override
- public void showEndTurnDialog(final List units) {
- canvas.showEndTurnDialog(units,
- new DialogHandler() {
- @Override
- public void handle(Boolean value) {
- if (value != null && value) {
- igc().endTurn(false);
- }
- }
- });
+ public void showEndTurnDialog(final List units,
+ DialogHandler handler) {
+ canvas.showEndTurnDialog(units, handler);
}
@Override
@@ -1227,10 +1236,9 @@ public class SwingGUI extends GUI {
@Override
public File showLoadDialog(File directory) {
- return canvas.showLoadDialog(directory);
+ return canvas.showLoadDialog(directory, null);
}
- @Override
public File showLoadDialog(File directory, FileFilter[] fileFilters) {
return canvas.showLoadDialog(directory, fileFilters);
}
@@ -1268,55 +1276,25 @@ public class SwingGUI extends GUI {
@Override
public void showMonarchDialog(final MonarchAction action,
- StringTemplate template, String monarchKey) {
- canvas.showMonarchDialog(action, template, monarchKey,
- new DialogHandler() {
- @Override
- public void handle(Boolean b) {
- igc().monarchAction(action, b);
- canvas.updateMenuBar();
- }
- });
+ StringTemplate template, String monarchKey,
+ DialogHandler handler) {
+ canvas.showMonarchDialog(action, template, monarchKey, handler);
}
@Override
- public void showNameNewLandDialog(String key, final String defaultName,
- final Unit unit) {
- canvas.showNameNewLandDialog(key, defaultName, unit,
- new DialogHandler() {
- @Override
- public void handle(String name) {
- if (name == null || name.isEmpty()) name = defaultName;
- igc().nameNewLand(unit, name);
- }
- });
- }
-
- @Override
- public void showNameNewRegionDialog(StringTemplate template,
- final String defaultName,
- final Unit unit, final Tile tile,
- final Region region) {
- canvas.showNameNewRegionDialog(template, defaultName, unit,
- new DialogHandler() {
- @Override
- public void handle(String name) {
- if (name == null || name.isEmpty()) name = defaultName;
- igc().nameNewRegion(tile, unit, region, name);
- }
- });
+ public void showNamingDialog(StringTemplate template,
+ final String defaultName,
+ final Unit unit,
+ DialogHandler handler) {
+ canvas.showNamingDialog(template, defaultName, unit, handler);
}
@Override
public void showFirstContactDialog(final Player player, final Player other,
- final Tile tile, int settlementCount) {
+ final Tile tile, int settlementCount,
+ DialogHandler handler) {
canvas.showFirstContactDialog(player, other, tile, settlementCount,
- new DialogHandler() {
- @Override
- public void handle(Boolean b) {
- igc().firstContact(player, other, tile, b);
- }
- });
+ handler);
}
@Override
@@ -1329,7 +1307,7 @@ public class SwingGUI extends GUI {
@Override
public void showNewPanel() {
- canvas.showNewPanel();
+ canvas.showNewPanel(null);
}
@Override
@@ -1354,12 +1332,10 @@ public class SwingGUI extends GUI {
return canvas.showPreCombatDialog(attacker, defender, tile);
}
- @Override
public void showPurchasePanel() {
canvas.showPurchasePanel();
}
- @Override
public void showRecruitPanel() {
canvas.showRecruitPanel();
}
@@ -1404,7 +1380,6 @@ public class SwingGUI extends GUI {
canvas.showReportIndianPanel();
}
- @Override
public void showReportLabourDetailPanel(UnitType unitType,
Map> data,
TypeCountMap unitCount, List colonies) {
@@ -1454,14 +1429,12 @@ public class SwingGUI extends GUI {
@Override
public File showSaveDialog(File directory, String defaultName) {
- return canvas.showSaveDialog(directory, defaultName);
+ return canvas.showSaveDialog(directory, null, defaultName);
}
- @Override
public File showSaveDialog(File directory, FileFilter[] fileFilters,
- String defaultName, String extension) {
- return canvas.showSaveDialog(directory, fileFilters, defaultName,
- extension);
+ String defaultName) {
+ return canvas.showSaveDialog(directory, fileFilters, defaultName);
}
@Override
@@ -1487,7 +1460,6 @@ public class SwingGUI extends GUI {
return canvas.showSelectDestinationDialog(unit);
}
- @Override
public void showServerListPanel(List serverList) {
canvas.showServerListPanel(serverList);
}
@@ -1508,16 +1480,15 @@ public class SwingGUI extends GUI {
canvas.showStatusPanel(message);
}
- @Override
public void showTilePanel(Tile tile) {
canvas.showTilePanel(tile);
}
@Override
public void showTilePopUpAtSelectedTile() {
- TerrainCursor cursor = mapViewer.getCursor();
- canvas.showTilePopup(mapViewer.getSelectedTile(),
- cursor.getCanvasX(), cursor.getCanvasY());
+ Tile tile = mapViewer.getSelectedTile();
+ Point point = mapViewer.calculateTilePosition(tile);
+ canvas.showTilePopup(tile, point.x+mapViewer.getTileWidth(), point.y);
}
@Override
@@ -1525,38 +1496,28 @@ public class SwingGUI extends GUI {
canvas.showTradeRoutePanel(unit);
}
- @Override
public void showTradeRouteInputPanel(TradeRoute newRoute,
Runnable callBack) {
canvas.showTradeRouteInputPanel(newRoute, callBack);
}
- @Override
public void showTrainPanel() {
canvas.showTrainPanel();
}
@Override
- public void showVictoryDialog() {
- canvas.showVictoryDialog(new DialogHandler() {
- @Override
- public void handle(Boolean result) {
- igc().victory(result);
- }
- });
+ public void showVictoryDialog(DialogHandler handler) {
+ canvas.showVictoryDialog(handler);
}
- @Override
public boolean showWarehouseDialog(Colony colony) {
return canvas.showWarehouseDialog(colony);
}
- @Override
public void showWorkProductionPanel(Unit unit) {
canvas.showWorkProductionPanel(unit);
}
- @Override
public void updateEuropeanSubpanels() {
canvas.updateEuropeanSubpanels();
}
@@ -1583,12 +1544,12 @@ public class SwingGUI extends GUI {
mapViewer.changeViewMode(newViewMode);
}
- @Override
- public Point calculateUnitLabelPositionInTile(JLabel unitLabel, Point tileP) {
- return mapViewer.calculateUnitLabelPositionInTile(unitLabel, tileP);
+ public Point calculateUnitLabelPositionInTile(int labelWidth,int labelHeight,
+ Point tileP) {
+ return mapViewer.calculateUnitLabelPositionInTile(
+ labelWidth, labelHeight, tileP);
}
- @Override
public void executeWithUnitOutForAnimation(final Unit unit,
final Tile sourceTile,
final OutForAnimationCallback r) {
@@ -1605,9 +1566,8 @@ public class SwingGUI extends GUI {
return mapViewer.getFocus();
}
- @Override
public float getMapScale() {
- return mapViewer.getMapScale();
+ return mapViewer.getImageLibrary().getScaleFactor();
}
@Override
@@ -1615,52 +1575,37 @@ public class SwingGUI extends GUI {
return mapViewer.getSelectedTile();
}
- @Override
public Rectangle getTileBounds(Tile tile) {
return mapViewer.calculateTileBounds(tile);
}
- @Override
public Point getTilePosition(Tile tile) {
return mapViewer.calculateTilePosition(tile);
}
- @Override
- public double getTileWidthHeightRatio() {
- return mapViewer.getTileWidthHeightRatio();
- }
-
@Override
public int getViewMode() {
return mapViewer.getViewMode();
}
- @Override
- public boolean onScreen(Tile tileToCheck) {
- return mapViewer.onScreen(tileToCheck);
- }
-
- @Override
- public void restartBlinking() {
- mapViewer.restartBlinking();
- }
-
@Override
public void setFocus(Tile tileToFocus) {
mapViewer.setFocus(tileToFocus);
+ canvas.refresh();
}
- @Override
public void setFocusImmediately(Tile tileToFocus) {
- mapViewer.setFocusImmediately(tileToFocus);
+ mapViewer.setFocus(tileToFocus);
Dimension size = canvas.getSize();
canvas.paintImmediately(0, 0, size.width, size.height);
}
@Override
- public boolean setSelectedTile(Tile newTileToSelect,
- boolean clearGoToOrders) {
- return mapViewer.setSelectedTile(newTileToSelect, clearGoToOrders);
+ public boolean setSelectedTile(Tile newTileToSelect) {
+ boolean result = mapViewer.setSelectedTile(newTileToSelect);
+ updateMapControls();
+ updateMenuBar();
+ return result;
}
@Override
@@ -1668,4 +1613,27 @@ public class SwingGUI extends GUI {
mapViewer.toggleViewMode();
}
+ // Forwarding to tileViewer
+
+ public static BufferedImage createTileImageWithOverlayAndForest(
+ TileType type, Dimension size) {
+ return TileViewer.createTileImageWithOverlayAndForest(type, size);
+ }
+
+ public BufferedImage createTileImageWithBeachBorderAndItems(Tile tile) {
+ return tileViewer.createTileImageWithBeachBorderAndItems(tile);
+ }
+
+ public BufferedImage createTileImage(Tile tile) {
+ return tileViewer.createTileImage(tile);
+ }
+
+ public BufferedImage createColonyTileImage(Tile tile, Colony colony) {
+ return tileViewer.createColonyTileImage(tile, colony);
+ }
+
+ public void displayColonyTiles(Graphics2D g, Tile[][] tiles, Colony colony) {
+ tileViewer.displayColonyTiles(g, tiles, colony);
+ }
+
}
diff --git a/src/net/sf/freecol/client/gui/TerrainCursor.java b/src/net/sf/freecol/client/gui/TerrainCursor.java
index c5ffce07f..9feece474 100644
--- a/src/net/sf/freecol/client/gui/TerrainCursor.java
+++ b/src/net/sf/freecol/client/gui/TerrainCursor.java
@@ -34,12 +34,10 @@ public class TerrainCursor implements ActionListener {
public static final int OFF = 0;
public static final int ON = 1;
- private int canvasX;
- private int canvasY;
private final Timer blinkTimer;
private boolean active;
private final EventListenerList listenerList;
-
+
/**
* Creates a new TerrainCursor
instance.
@@ -53,7 +51,7 @@ public class TerrainCursor implements ActionListener {
listenerList = new EventListenerList();
}
-
+
/**
* Returns whether this TerrainCursor is active.
*
@@ -62,7 +60,7 @@ public class TerrainCursor implements ActionListener {
public boolean isActive() {
return active;
}
-
+
/**
* Sets the active state of the TerrainCursor.
*
@@ -71,43 +69,30 @@ public class TerrainCursor implements ActionListener {
public void setActive(boolean newState) {
active = newState;
}
-
+
public void startBlinking() {
if (!blinkTimer.isRunning()) blinkTimer.start();
}
-
+
public void stopBlinking() {
if (blinkTimer.isRunning()) blinkTimer.stop();
}
- public void setCanvasPos(int x,int y) {
- canvasX = x;
- canvasY = y;
- }
-
- public int getCanvasX() {
- return canvasX;
- }
-
- public int getCanvasY() {
- return canvasY;
- }
-
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
-
+
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
-
- public void fireActionEvent(ActionEvent event) {
+
+ public void fireActionEvent(ActionEvent ae) {
for (ActionListener al
: listenerList.getListeners(ActionListener.class)) {
- al.actionPerformed(event);
+ al.actionPerformed(ae);
}
}
-
+
// Interface ActionListener
@@ -115,7 +100,7 @@ public class TerrainCursor implements ActionListener {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
active = !active;
int eventId = active? ON : OFF;
ActionEvent blinkEvent = new ActionEvent(this,eventId,"blink");
diff --git a/src/net/sf/freecol/client/gui/TilePopup.java b/src/net/sf/freecol/client/gui/TilePopup.java
index 6d1cf3f17..26ad0da06 100644
--- a/src/net/sf/freecol/client/gui/TilePopup.java
+++ b/src/net/sf/freecol/client/gui/TilePopup.java
@@ -23,10 +23,10 @@ import java.awt.Component;
import java.awt.Container;
import java.awt.Font;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
@@ -69,8 +69,8 @@ public final class TilePopup extends JPopupMenu {
public static final int UNIT_LINES_IN_OTHER_MENUS = 19;
private final FreeColClient freeColClient;
- private final GUI gui;
- private final MapViewer mapViewer;
+ private final SwingGUI gui;
+ private final Canvas canvas;
private boolean hasAnItem = false;
@@ -78,15 +78,17 @@ public final class TilePopup extends JPopupMenu {
* The constructor that will insert the MenuItems.
*
* @param freeColClient The FreeColClient
for the game.
+ * @param canvas The Canvas.
* @param tile The Tile
to create a popup for.
* The popup menu also appears near this Tile
.
*/
- public TilePopup(final FreeColClient freeColClient, final MapViewer mapViewer, final Tile tile) {
+ public TilePopup(final FreeColClient freeColClient, final Canvas canvas,
+ final Tile tile) {
super(Messages.message(tile.getSimpleLabel()));
this.freeColClient = freeColClient;
- this.gui = freeColClient.getGUI();
- this.mapViewer = mapViewer;
+ this.gui = (SwingGUI)freeColClient.getGUI();
+ this.canvas = canvas;
final Player player = freeColClient.getMyPlayer();
final Unit activeUnit = gui.getActiveUnit();
@@ -105,22 +107,15 @@ public final class TilePopup extends JPopupMenu {
gotoMenuItem = Utility.localizedMenuItem("goToThisTile");
}
if (gotoMenuItem != null) {
- gotoMenuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (!freeColClient.currentPlayerIsMyPlayer()) {
- return;
- }
- Tile currTile = activeUnit.getTile();
- // already at the destination?
- if (currTile == tile) return;
- freeColClient.getInGameController()
- .goToTile(activeUnit, tile);
- // if unit did not move, we should show
- // the goto path
- if (activeUnit.getTile() == currTile) {
- mapViewer.updateCurrentPathForActiveUnit();
- }
+ gotoMenuItem.addActionListener((ActionEvent ae) -> {
+ if (!freeColClient.currentPlayerIsMyPlayer()) return;
+ Tile currTile = activeUnit.getTile();
+ if (currTile == tile) return; // already at destination
+ freeColClient.getInGameController()
+ .goToTile(activeUnit, tile);
+ // if unit did not move, we should show the goto path
+ if (activeUnit.getTile() == currTile) {
+ canvas.updateCurrentPathForActiveUnit();
}
});
add(gotoMenuItem);
@@ -131,14 +126,9 @@ public final class TilePopup extends JPopupMenu {
if (unitTile == tile && activeUnit.hasHighSeasMove()) {
JMenuItem europeMenuItem = Utility.localizedMenuItem(StringTemplate
.template("goToEurope"));
- europeMenuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (!freeColClient.currentPlayerIsMyPlayer()) {
- return;
- }
- igc.moveTo(activeUnit, player.getEurope());
- }
+ europeMenuItem.addActionListener((ActionEvent ae) -> {
+ if (!freeColClient.currentPlayerIsMyPlayer()) return;
+ igc.moveTo(activeUnit, player.getEurope());
});
add(europeMenuItem);
hasAnItem = true;
@@ -149,39 +139,24 @@ public final class TilePopup extends JPopupMenu {
JMenuItem ji = null;
if (activeUnit.checkSetState(UnitState.ACTIVE)) {
ji = Utility.localizedMenuItem("activateUnit");
- ji.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (activeUnit.checkSetState(UnitState.ACTIVE)) {
- igc.changeState(activeUnit, Unit.UnitState.ACTIVE);
- }
- }
+ ji.addActionListener((ActionEvent ae) -> {
+ igc.changeState(activeUnit, Unit.UnitState.ACTIVE);
});
add(ji);
hasAnItem = true;
}
if (activeUnit.checkSetState(UnitState.FORTIFYING)) {
ji = Utility.localizedMenuItem("fortify");
- ji.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (activeUnit.checkSetState(UnitState.FORTIFYING)) {
- igc.changeState(activeUnit, Unit.UnitState.FORTIFYING);
- }
- }
+ ji.addActionListener((ActionEvent ae) -> {
+ igc.changeState(activeUnit, Unit.UnitState.FORTIFYING);
});
add(ji);
hasAnItem = true;
}
if (activeUnit.checkSetState(UnitState.SKIPPED)) {
ji = Utility.localizedMenuItem("skip");
- ji.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (activeUnit.checkSetState(UnitState.SKIPPED)) {
- igc.changeState(activeUnit, Unit.UnitState.SKIPPED);
- }
- }
+ ji.addActionListener((ActionEvent ae) -> {
+ igc.changeState(activeUnit, Unit.UnitState.SKIPPED);
});
add(ji);
hasAnItem = true;
@@ -189,11 +164,8 @@ public final class TilePopup extends JPopupMenu {
if (activeUnit.canCarryTreasure()
&& activeUnit.canCashInTreasureTrain()) {
ji = Utility.localizedMenuItem("cashInTreasureTrain");
- ji.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- igc.checkCashInTreasureTrain(activeUnit);
- }
+ ji.addActionListener((ActionEvent ae) -> {
+ igc.checkCashInTreasureTrain(activeUnit);
});
ji.setEnabled(true);
add(ji);
@@ -202,11 +174,8 @@ public final class TilePopup extends JPopupMenu {
if (activeUnit.getDestination() != null) {
ji = Utility.localizedMenuItem("clearOrders");
- ji.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- igc.clearOrders(activeUnit);
- }
+ ji.addActionListener((ActionEvent ae) -> {
+ igc.clearOrders(activeUnit);
});
add(ji);
hasAnItem = true;
@@ -232,11 +201,10 @@ public final class TilePopup extends JPopupMenu {
int maxUnits = UNIT_LINES_IN_FIRST_MENU;
Container currentMenu = this;
boolean moreUnits = false;
- List units = tile.getUnitList();
Unit firstUnit = tile.getFirstUnit();
- Collections.sort(units, ReportPanel.getUnitTypeComparator());
- for (final Unit currentUnit : units) {
-
+ for (Unit u : tile.getUnitList().stream()
+ .sorted(Unit.typeRoleComparator)
+ .collect(Collectors.toList())) {
if (lineCount > maxUnits) {
JMenu more = Utility.localizedMenu("more");
more.setFont(more.getFont().deriveFont(Font.ITALIC));
@@ -247,26 +215,20 @@ public final class TilePopup extends JPopupMenu {
lineCount = 0;
maxUnits = UNIT_LINES_IN_OTHER_MENUS;
}
-
- lineCount += addUnit(currentMenu, currentUnit,
- !currentUnit.isDamaged(), false);
+ lineCount += addUnit(currentMenu, u, !u.isDamaged(), false);
}
if (tile.getUnitCount() > 1 && player.owns(firstUnit)) {
if (moreUnits) addSeparator();
JMenuItem activateAllItem = Utility.localizedMenuItem(StringTemplate
.template("activateAllUnits"));
- activateAllItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- Unit lastUnit = null;
- for (Unit unit : tile.getUnitList()) {
- freeColClient.getInGameController()
- .clearOrders(unit);
- lastUnit = unit;
- }
- gui.setActiveUnit(lastUnit);
+ activateAllItem.addActionListener((ActionEvent ae) -> {
+ Unit lastUnit = null;
+ for (Unit unit : tile.getUnitList()) {
+ freeColClient.getInGameController().clearOrders(unit);
+ lastUnit = unit;
}
+ gui.setActiveUnit(lastUnit);
});
add(activateAllItem);
}
@@ -301,32 +263,23 @@ public final class TilePopup extends JPopupMenu {
for (final Unit unit : tile.getUnitList()) {
JMenuItem toMenuItem = new JMenuItem(unit.toString());
- toMenuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.changeOwnership(freeColClient, unit);
- }
+ toMenuItem.addActionListener((ActionEvent ae) -> {
+ DebugUtils.changeOwnership(freeColClient, unit);
});
changeOwnership.add(toMenuItem);
if (unit.isCarrier()) {
JMenuItem menuItem = new JMenuItem(unit.toString());
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.displayMission(freeColClient, unit);
- }
+ menuItem.addActionListener((ActionEvent ae) -> {
+ DebugUtils.displayMission(freeColClient, unit);
});
transportLists.add(menuItem);
}
if (unit.isPerson()) {
JMenuItem roleMenuItem = new JMenuItem(unit.toString());
- roleMenuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.changeRole(freeColClient, unit);
- }
+ roleMenuItem.addActionListener((ActionEvent ae) -> {
+ DebugUtils.changeRole(freeColClient, unit);
});
changeRole.add(roleMenuItem);
}
@@ -339,40 +292,28 @@ public final class TilePopup extends JPopupMenu {
}
JMenuItem toMenuItem = new JMenuItem(tile.getColony().toString());
final Colony colony = tile.getColony();
- toMenuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.changeOwnership(freeColClient, colony);
- }
+ toMenuItem.addActionListener((ActionEvent ae) -> {
+ DebugUtils.changeOwnership(freeColClient, colony);
});
changeOwnership.add(toMenuItem);
JMenuItem displayColonyPlan = new JMenuItem("Display Colony Plan");
- displayColonyPlan.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.displayColonyPlan(freeColClient, colony);
- }
+ displayColonyPlan.addActionListener((ActionEvent ae) -> {
+ DebugUtils.displayColonyPlan(freeColClient, colony);
});
add(displayColonyPlan);
JMenuItem applyDisaster = new JMenuItem("Apply Disaster");
- applyDisaster.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.applyDisaster(freeColClient, colony);
- }
+ applyDisaster.addActionListener((ActionEvent ae) -> {
+ DebugUtils.applyDisaster(freeColClient, colony);
});
add(applyDisaster);
}
if (tile.getIndianSettlement() != null) {
JMenuItem displayGoods = new JMenuItem("Examine Settlement");
final IndianSettlement is = tile.getIndianSettlement();
- displayGoods.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.summarizeSettlement(freeColClient, is);
- }
+ displayGoods.addActionListener((ActionEvent ae) -> {
+ DebugUtils.summarizeSettlement(freeColClient, is);
});
add(displayGoods);
}
@@ -382,22 +323,16 @@ public final class TilePopup extends JPopupMenu {
if (tile.hasLostCityRumour()) {
JMenuItem rumourItem = new JMenuItem("Set Lost City Rumour type");
rumourItem.setOpaque(false);
- rumourItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.setRumourType(freeColClient, tile);
- }
+ rumourItem.addActionListener((ActionEvent ae) -> {
+ DebugUtils.setRumourType(freeColClient, tile);
});
add(rumourItem);
}
JMenuItem addu = new JMenuItem("Add unit");
addu.setOpaque(false);
- addu.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.addNewUnitToTile(freeColClient, tile);
- }
+ addu.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addNewUnitToTile(freeColClient, tile);
});
add(addu);
@@ -405,11 +340,8 @@ public final class TilePopup extends JPopupMenu {
JMenuItem adda = new JMenuItem("Reset moves");
adda.setOpaque(false);
final List tileUnits = tile.getUnitList();
- adda.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.resetMoves(freeColClient, tileUnits);
- }
+ adda.addActionListener((ActionEvent ae) -> {
+ DebugUtils.resetMoves(freeColClient, tileUnits);
});
add(adda);
}
@@ -417,21 +349,18 @@ public final class TilePopup extends JPopupMenu {
final Unit activeUnit = gui.getActiveUnit();
if (activeUnit != null && activeUnit.getTile() != null) {
JMenuItem menuItem = new JMenuItem("Show search");
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- if (!freeColClient.currentPlayerIsMyPlayer()) return;
- Tile currTile = activeUnit.getTile();
- if (currTile == tile) return;
- final Map map = activeUnit.getGame().getMap();
- LogBuilder lb = new LogBuilder(512);
- PathNode path = map.findPath(activeUnit,
- activeUnit.getTile(), tile, activeUnit.getCarrier(),
- null, lb);
- gui.showInformationMessage(lb.toString());
- mapViewer.setCurrentPath(path);
- gui.refresh();
- }
+ menuItem.addActionListener((ActionEvent ae) -> {
+ if (!freeColClient.currentPlayerIsMyPlayer()) return;
+ Tile currTile = activeUnit.getTile();
+ if (currTile == tile) return;
+ final Map map = activeUnit.getGame().getMap();
+ LogBuilder lb = new LogBuilder(512);
+ PathNode path = map.findPath(activeUnit,
+ activeUnit.getTile(), tile, activeUnit.getCarrier(),
+ null, lb);
+ gui.showInformationMessage(lb.toString());
+ canvas.setCurrentPath(path);
+ gui.refresh();
});
add(menuItem);
}
@@ -441,11 +370,8 @@ public final class TilePopup extends JPopupMenu {
JMenuItem addg = new JMenuItem("Add goods");
addg.setOpaque(false);
final Unit unit = u;
- addg.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.addUnitGoods(freeColClient, unit);
- }
+ addg.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addUnitGoods(freeColClient, unit);
});
add(addg);
break;
@@ -454,11 +380,8 @@ public final class TilePopup extends JPopupMenu {
JMenuItem dumpItem = new JMenuItem("Dump tile");
dumpItem.setOpaque(false);
- dumpItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- DebugUtils.dumpTile(freeColClient, tile);
- }
+ dumpItem.addActionListener((ActionEvent ae) -> {
+ DebugUtils.dumpTile(freeColClient, tile);
});
add(dumpItem);
}
@@ -482,24 +405,18 @@ public final class TilePopup extends JPopupMenu {
JMenuItem menuItem = new JMenuItem(text);
menuItem.setFont(FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.TINY, Font.BOLD,
- gui.getImageLibrary().getScalingFactor()));
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.setActiveUnit(unit);
- }
+ gui.getImageLibrary().getScaleFactor()));
+ menuItem.addActionListener((ActionEvent ae) -> {
+ gui.setActiveUnit(unit);
});
- int lineCount = 1;
if (indent) {
menuItem.setFont(menuItem.getFont().deriveFont(Font.ITALIC));
}
menuItem.setEnabled(enabled);
menu.add(menuItem);
- for (Unit passenger : unit.getUnitList()) {
- lineCount += addUnit(menu, passenger, true, true);
- }
-
+ int lineCount = 1 + unit.getUnitList().stream()
+ .mapToInt(u -> addUnit(menu, u, true, true)).sum();
boolean hasGoods = false;
for (Goods goods: unit.getGoodsList()) {
text = (indent ? " " : " ")
@@ -533,22 +450,16 @@ public final class TilePopup extends JPopupMenu {
JMenuItem menuItem = Utility.localizedMenuItem(name);
menuItem.setFont(FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.TINY, Font.BOLD,
- gui.getImageLibrary().getScalingFactor()));
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.showColonyPanel(colony, null);
- }
+ gui.getImageLibrary().getScaleFactor()));
+ menuItem.addActionListener((ActionEvent ae) -> {
+ gui.showColonyPanel(colony, null);
});
add(menuItem);
menuItem = Utility.localizedMenuItem("rename");
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- freeColClient.getInGameController().rename(colony);
- }
+ menuItem.addActionListener((ActionEvent ae) -> {
+ freeColClient.getInGameController().rename(colony);
});
add(menuItem);
@@ -568,12 +479,9 @@ public final class TilePopup extends JPopupMenu {
JMenuItem menuItem = Utility.localizedMenuItem(name);
menuItem.setFont(FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.TINY, Font.BOLD,
- gui.getImageLibrary().getScalingFactor()));
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.showIndianSettlementPanel(settlement);
- }
+ gui.getImageLibrary().getScaleFactor()));
+ menuItem.addActionListener((ActionEvent ae) -> {
+ gui.showIndianSettlementPanel(settlement);
});
add(menuItem);
hasAnItem = true;
@@ -586,11 +494,8 @@ public final class TilePopup extends JPopupMenu {
*/
private void addTile(final Tile tile) {
JMenuItem menuItem = new JMenuItem(Messages.getName(tile));
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.showTilePanel(tile);
- }
+ menuItem.addActionListener((ActionEvent ae) -> {
+ gui.showTilePanel(tile);
});
add(menuItem);
diff --git a/src/net/sf/freecol/client/gui/TileViewer.java b/src/net/sf/freecol/client/gui/TileViewer.java
new file mode 100644
index 000000000..63f8278b1
--- /dev/null
+++ b/src/net/sf/freecol/client/gui/TileViewer.java
@@ -0,0 +1,789 @@
+/**
+ * Copyright (C) 2002-2015 The FreeCol Team
+ *
+ * This file is part of FreeCol.
+ *
+ * FreeCol is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * FreeCol is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with FreeCol. If not, see .
+ */
+
+package net.sf.freecol.client.gui;
+
+import java.awt.AlphaComposite;
+import java.awt.Color;
+import java.awt.Composite;
+import java.awt.Dimension;
+import java.awt.Font;
+import java.awt.Graphics2D;
+import java.awt.geom.GeneralPath;
+import java.awt.image.BufferedImage;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import net.sf.freecol.client.ClientOptions;
+import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.common.debug.DebugUtils;
+import net.sf.freecol.common.debug.FreeColDebugger;
+import net.sf.freecol.common.i18n.Messages;
+import net.sf.freecol.common.model.Ability;
+import net.sf.freecol.common.model.Colony;
+import net.sf.freecol.common.model.ColonyTile;
+import net.sf.freecol.common.model.Direction;
+import net.sf.freecol.common.model.GameOptions;
+import net.sf.freecol.common.model.IndianSettlement;
+import net.sf.freecol.common.model.LostCityRumour;
+import net.sf.freecol.common.model.Player;
+import net.sf.freecol.common.model.Resource;
+import net.sf.freecol.common.model.Settlement;
+import net.sf.freecol.common.model.Tile;
+import net.sf.freecol.common.model.TileImprovement;
+import net.sf.freecol.common.model.TileItem;
+import net.sf.freecol.common.model.TileType;
+import net.sf.freecol.common.model.Unit;
+import net.sf.freecol.common.resources.ResourceManager;
+import net.sf.freecol.common.util.Utils;
+
+import static net.sf.freecol.common.util.StringUtils.*;
+
+
+/**
+ * TileViewer is a private helper class of MapViewer and SwingGUI.
+ *
+ * This class is responsible for drawing map tiles
+ * for MapViewer and some GUI-panels.
+ */
+public final class TileViewer {
+
+ private static final Logger logger = Logger.getLogger(TileViewer.class.getName());
+
+
+ private static class SortableImage implements Comparable {
+
+ public final BufferedImage image;
+ public final int index;
+
+ public SortableImage(BufferedImage image, int index) {
+ this.image = image;
+ this.index = index;
+ }
+
+ // Implement Comparable
+
+ @Override
+ public int compareTo(SortableImage other) {
+ return other.index - this.index;
+ }
+
+ // Override Object
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean equals(Object other) {
+ if (other instanceof SortableImage) {
+ return this.compareTo((SortableImage)other) == 0;
+ }
+ return super.equals(other);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int hashCode() {
+ int hash = super.hashCode();
+ hash = 37 * hash + Utils.hashCode(image);
+ return 37 * hash + index;
+ }
+ }
+
+ private final FreeColClient freeColClient;
+
+ private ImageLibrary lib;
+
+ private RoadPainter rp;
+
+ // Helper variables for displaying.
+ private int tileHeight, tileWidth, halfHeight, halfWidth;
+
+ // The height offset to paint at (in pixels).
+ static final int STATE_OFFSET_X = 25,
+ STATE_OFFSET_Y = 10;
+
+ private final GeneralPath fog = new GeneralPath();
+
+
+ /**
+ * The constructor to use.
+ *
+ * @param freeColClient The FreeColClient
for the game.
+ */
+ TileViewer(FreeColClient freeColClient) {
+ this.freeColClient = freeColClient;
+
+ setImageLibraryAndUpdateData(new ImageLibrary());
+ }
+
+
+ /**
+ * Gets the contained ImageLibrary
.
+ *
+ * @return The image library;
+ */
+ ImageLibrary getImageLibrary() {
+ return lib;
+ }
+
+ /**
+ * Returns the scaled terrain-image for a terrain type (and position 0, 0).
+ *
+ * @param type The type of the terrain-image to return.
+ * @param size The maximum size of the terrain image to return.
+ * @return The terrain-image
+ */
+ static BufferedImage createTileImageWithOverlayAndForest(
+ TileType type, Dimension size) {
+ Dimension size2 = new Dimension(
+ (size.width > 0) ? size.width
+ : (2*ImageLibrary.TILE_SIZE.width*size.height +
+ (ImageLibrary.TILE_OVERLAY_SIZE.height+1)) /
+ (2*ImageLibrary.TILE_OVERLAY_SIZE.height),
+ -1);
+ BufferedImage terrainImage = ImageLibrary.getTerrainImage(
+ type, 0, 0, size2);
+ BufferedImage overlayImage = ImageLibrary.getOverlayImage(
+ type, type.getId(), size2);
+ BufferedImage forestImage = type.isForested()
+ ? ImageLibrary.getForestImage(type, size2)
+ : null;
+ if (overlayImage == null && forestImage == null) {
+ return terrainImage;
+ } else {
+ int width = terrainImage.getWidth();
+ int height = terrainImage.getHeight();
+ if (overlayImage != null) {
+ height = Math.max(height, overlayImage.getHeight());
+ }
+ if (forestImage != null) {
+ height = Math.max(height, forestImage.getHeight());
+ }
+ BufferedImage compositeImage = new BufferedImage(width, height,
+ BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = compositeImage.createGraphics();
+ g.drawImage(terrainImage, 0, height - terrainImage.getHeight(), null);
+ if (overlayImage != null) {
+ g.drawImage(overlayImage, 0, height - overlayImage.getHeight(), null);
+ }
+ if (forestImage != null) {
+ g.drawImage(forestImage, 0, height - forestImage.getHeight(), null);
+ }
+ g.dispose();
+ return compositeImage;
+ }
+ }
+
+ /**
+ * Create a BufferedImage
and draw a Tile
on it.
+ * Draws the terrain and improvements.
+ *
+ * @param tile The Tile to draw.
+ * @return The image.
+ */
+ BufferedImage createTileImageWithBeachBorderAndItems(Tile tile) {
+ if (!tile.isExplored())
+ return lib.getTerrainImage(null, tile.getX(), tile.getY());
+ final TileType tileType = tile.getType();
+ Dimension terrainTileSize = lib.tileSize;
+ BufferedImage overlayImage = lib.getOverlayImage(tile);
+ final int compoundHeight = (overlayImage != null)
+ ? overlayImage.getHeight()
+ : tileType.isForested()
+ ? lib.tileForestSize.height
+ : terrainTileSize.height;
+ BufferedImage image = new BufferedImage(
+ terrainTileSize.width, compoundHeight, BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = image.createGraphics();
+ g.translate(0, compoundHeight - terrainTileSize.height);
+ displayTileWithBeachAndBorder(g, tile);
+ displayTileItems(g, tile, overlayImage);
+ g.dispose();
+ return image;
+ }
+
+ /**
+ * Create a BufferedImage
and draw a Tile
on it.
+ *
+ * @param tile The Tile
to draw.
+ * @return The image.
+ */
+ BufferedImage createTileImage(Tile tile) {
+ final TileType tileType = tile.getType();
+ Dimension terrainTileSize = lib.tileSize;
+ BufferedImage overlayImage = lib.getOverlayImage(tile);
+ final int compoundHeight = (overlayImage != null)
+ ? overlayImage.getHeight()
+ : tileType.isForested()
+ ? lib.tileForestSize.height
+ : terrainTileSize.height;
+ BufferedImage image = new BufferedImage(
+ terrainTileSize.width, compoundHeight, BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = image.createGraphics();
+ g.translate(0, compoundHeight - terrainTileSize.height);
+ displayTile(g, tile, overlayImage);
+ g.dispose();
+ return image;
+ }
+
+ /**
+ * Create a BufferedImage
and draw a Tile
on it.
+ * The visualization of the Tile
also includes information
+ * from the corresponding ColonyTile
of the given
+ * Colony
.
+ *
+ * @param tile The Tile
to draw.
+ * @param colony The Colony
to create the visualization
+ * of the Tile
for. This object is also used to
+ * get the ColonyTile
for the given Tile
.
+ * @return The image.
+ */
+ BufferedImage createColonyTileImage(Tile tile, Colony colony) {
+ final TileType tileType = tile.getType();
+ Dimension terrainTileSize = lib.tileSize;
+ BufferedImage overlayImage = lib.getOverlayImage(tile);
+ final int compoundHeight = (overlayImage != null)
+ ? overlayImage.getHeight()
+ : tileType.isForested()
+ ? lib.tileForestSize.height
+ : terrainTileSize.height;
+ BufferedImage image = new BufferedImage(
+ terrainTileSize.width, compoundHeight, BufferedImage.TYPE_INT_ARGB);
+ Graphics2D g = image.createGraphics();
+ g.translate(0, compoundHeight - terrainTileSize.height);
+ displayColonyTile(g, tile, colony, overlayImage);
+ g.dispose();
+ return image;
+ }
+
+ /**
+ * Displays the 3x3 tiles for the TilesPanel in ColonyPanel.
+ *
+ * @param g The Graphics2D
object on which to draw
+ * the Tile
.
+ * @param tiles The array containing the Tile
objects to draw.
+ * @param colony The Colony
to create the visualization
+ * of the Tile
objects for.
+ */
+ void displayColonyTiles(Graphics2D g, Tile[][] tiles, Colony colony) {
+ Set overlayCache = ImageLibrary.createOverlayCache();
+ Dimension tileSize = lib.tileSize;
+ for (int x = 0; x < 3; x++) {
+ for (int y = 0; y < 3; y++) {
+ if (tiles[x][y] != null) {
+ int xx = (((2 - x) + y) * tileSize.width) / 2;
+ int yy = ((x + y) * tileSize.height) / 2;
+ g.translate(xx, yy);
+ BufferedImage overlayImage = lib.getOverlayImage(
+ tiles[x][y], overlayCache);
+ displayColonyTile(g, tiles[x][y], colony, overlayImage);
+ g.translate(-xx, -yy);
+ }
+ }
+ }
+ }
+
+ /**
+ * Displays the given colony tile.
+ * The visualization of the Tile
also includes information
+ * from the corresponding ColonyTile
from the given
+ * Colony
.
+ *
+ * @param g The Graphics2D
on which to draw.
+ * @param tile The Tile
to draw.
+ * @param colony The Colony
to create the visualization
+ * of the Tile
for. This object is also used to
+ * get the ColonyTile
for the given Tile
.
+ * @param overlayImage The BufferedImage of the tile overlay.
+ */
+ private void displayColonyTile(Graphics2D g, Tile tile, Colony colony,
+ BufferedImage overlayImage) {
+ displayTile(g, tile, overlayImage);
+
+ ColonyTile colonyTile = colony.getColonyTile(tile);
+ switch (colonyTile.getNoWorkReason()) {
+ case NONE: case COLONY_CENTER: case CLAIM_REQUIRED:
+ break;
+ default:
+ g.drawImage(lib.getMiscImage(ImageLibrary.TILE_TAKEN),
+ 0, 0, null);
+ }
+ int price = colony.getOwner().getLandPrice(tile);
+ if (price > 0 && !tile.hasSettlement()) {
+ BufferedImage image = lib.getMiscImage(
+ ImageLibrary.TILE_OWNED_BY_INDIANS);
+ displayCenteredImage(g, image);
+ }
+
+ Unit unit = colonyTile.getOccupyingUnit();
+ if (unit != null) {
+ BufferedImage image = lib.getSmallerUnitImage(unit);
+ g.drawImage(image,
+ tileWidth/4 - image.getWidth() / 2,
+ halfHeight - image.getHeight() / 2, null);
+ // Draw an occupation and nation indicator.
+ Player owner = freeColClient.getMyPlayer();
+ String text = Messages.message(unit.getOccupationLabel(owner, false));
+ g.drawImage(lib.getOccupationIndicatorChip(g, unit, text),
+ (int)(STATE_OFFSET_X * lib.getScaleFactor()),
+ 0, null);
+ }
+ }
+
+ /**
+ * Displays the given Tile
.
+ *
+ * @param g The Graphics2D on which to draw the Tile
.
+ * @param tile The Tile
to draw.
+ * @param overlayImage The BufferedImage for the tile overlay.
+ */
+ private void displayTile(Graphics2D g, Tile tile, BufferedImage overlayImage) {
+ displayTileWithBeachAndBorder(g, tile);
+ if (tile.isExplored()) {
+ displayTileItems(g, tile, overlayImage);
+ displaySettlementWithChipsOrPopulationNumber(g, tile, false);
+ displayFogOfWar(g, tile);
+ displayOptionalTileText(g, tile);
+ }
+ }
+
+ /**
+ * Sets the ImageLibrary and calculates various items that depend
+ * on tile size.
+ *
+ * @param lib an ImageLibrary
value
+ */
+ void setImageLibraryAndUpdateData(ImageLibrary lib) {
+ this.lib = lib;
+ // ATTENTION: we assume that all base tiles have the same size
+ Dimension tileSize = lib.tileSize;
+ rp = new RoadPainter(tileSize);
+ tileHeight = tileSize.height;
+ tileWidth = tileSize.width;
+ halfHeight = tileHeight/2;
+ halfWidth = tileWidth/2;
+
+ fog.reset();
+ fog.moveTo(halfWidth, 0);
+ fog.lineTo(tileWidth, halfHeight);
+ fog.lineTo(halfWidth, tileHeight);
+ fog.lineTo(0, halfHeight);
+ fog.closePath();
+ }
+
+ /**
+ * Centers the given Image on the tile.
+ *
+ * @param g a Graphics2D
+ * @param image the BufferedImage
+ */
+ void displayCenteredImage(Graphics2D g, BufferedImage image) {
+ g.drawImage(image,
+ (tileWidth - image.getWidth())/2,
+ (tileHeight - image.getHeight())/2,
+ null);
+ }
+
+ /**
+ * Centers the given Image on the tile, ensuring it is not drawing
+ * over tiles south of it.
+ *
+ * @param g a Graphics2D
+ * @param image the BufferedImage
+ */
+ void displayLargeCenteredImage(Graphics2D g, BufferedImage image) {
+ int y = tileHeight - image.getHeight();
+ if(y > 0)
+ y /= 2;
+ g.drawImage(image, (tileWidth - image.getWidth())/2, y, null);
+ }
+
+ /**
+ * Displays the given Tile onto the given Graphics2D object at the
+ * location specified by the coordinates. Only base terrain will be drawn.
+ *
+ * @param g The Graphics2D object on which to draw the Tile.
+ * @param tile The Tile to draw.
+ */
+ void displayTileWithBeachAndBorder(Graphics2D g, Tile tile) {
+ if (tile != null) {
+ TileType tileType = tile.getType();
+ int x = tile.getX();
+ int y = tile.getY();
+ // ATTENTION: we assume that all base tiles have the same size
+ g.drawImage(lib.getTerrainImage(tileType, x, y),
+ 0, 0, null);
+ if (tile.isExplored()) {
+ if (!tile.isLand() && tile.getStyle() > 0) {
+ int edgeStyle = tile.getStyle() >> 4;
+ if (edgeStyle > 0) {
+ g.drawImage(lib.getBeachEdgeImage(edgeStyle, x, y),
+ 0, 0, null);
+ }
+ int cornerStyle = tile.getStyle() & 15;
+ if (cornerStyle > 0) {
+ g.drawImage(lib.getBeachCornerImage(cornerStyle, x, y),
+ 0, 0, null);
+ }
+ }
+
+ List imageBorders = new ArrayList<>(8);
+ SortableImage si;
+ for (Direction direction : Direction.values()) {
+ Tile borderingTile = tile.getNeighbourOrNull(direction);
+ if (borderingTile != null && borderingTile.isExplored()) {
+ TileType borderingTileType = borderingTile.getType();
+ if (borderingTileType != tileType) {
+ if (!tile.isLand() && borderingTile.isLand()) {
+ // If there is a Coast image (eg. beach) defined, use it, otherwise skip
+ // Draw the grass from the neighboring tile, spilling over on the side of this tile
+ si = new SortableImage(
+ lib.getBorderImage(borderingTileType, direction, x, y),
+ borderingTileType.getIndex());
+ imageBorders.add(si);
+ TileImprovement river = borderingTile.getRiver();
+ if (river != null && river.isConnectedTo(direction.getReverseDirection())) {
+ si = new SortableImage(
+ lib.getRiverMouthImage(direction,
+ borderingTile.getRiver().getMagnitude(), x, y),
+ -1);
+ imageBorders.add(si);
+ }
+ } else if (!tile.isLand() || borderingTile.isLand()) {
+ if (borderingTileType.getIndex() < tileType.getIndex() &&
+ !lib.getTerrainImage(tileType, 0, 0).equals(lib.getTerrainImage(borderingTileType, 0, 0))) {
+ // Draw land terrain with bordering land type, or ocean/high seas limit,
+ // if the tiles do not share same graphics (ocean & great river)
+ si = new SortableImage(
+ lib.getBorderImage(borderingTileType, direction, x, y),
+ borderingTileType.getIndex());
+ imageBorders.add(si);
+ }
+ }
+ }
+ }
+ }
+ Collections.sort(imageBorders);
+ for (SortableImage sorted : imageBorders) {
+ g.drawImage(sorted.image, 0, 0, null);
+ }
+ }
+ }
+ }
+
+ void displayUnknownTileBorder(Graphics2D g, Tile tile) {
+ for (Direction direction : Direction.values()) {
+ Tile borderingTile = tile.getNeighbourOrNull(direction);
+ if (borderingTile != null && !borderingTile.isExplored()) {
+ g.drawImage(lib.getBorderImage(
+ null, direction, tile.getX(), tile.getY()),
+ 0, 0, null);
+ }
+ }
+ }
+
+ /**
+ * Displays the given Tile onto the given Graphics2D object at the
+ * location specified by the coordinates. Fog of war will be
+ * drawn.
+ *
+ * @param g The Graphics2D
object on which to draw
+ * the Tile
.
+ * @param tile The Tile
to draw.
+ */
+ void displayFogOfWar(Graphics2D g, Tile tile) {
+ if (freeColClient.getGame() != null
+ && freeColClient.getGame().getSpecification()
+ .getBoolean(GameOptions.FOG_OF_WAR)
+ && freeColClient.getMyPlayer() != null
+ && !freeColClient.getMyPlayer().canSee(tile)) {
+ g.setColor(Color.BLACK);
+ Composite oldComposite = g.getComposite();
+ g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
+ 0.2f));
+ g.fill(fog);
+ g.setComposite(oldComposite);
+ }
+ }
+
+ /**
+ * Displays the Tile text for a Tile.
+ * Shows tile names, coordinates and colony values.
+ *
+ * @param g The Graphics2D object on which the text gets drawn.
+ * @param tile The Tile to draw the text on.
+ */
+ void displayOptionalTileText(Graphics2D g, Tile tile) {
+ String text = null;
+ int op = freeColClient.getClientOptions()
+ .getInteger(ClientOptions.DISPLAY_TILE_TEXT);
+ switch (op) {
+ case ClientOptions.DISPLAY_TILE_TEXT_NAMES:
+ text = Messages.getName(tile);
+ break;
+ case ClientOptions.DISPLAY_TILE_TEXT_OWNERS:
+ if (tile.getOwner() != null) {
+ text = Messages.message(tile.getOwner().getNationLabel());
+ }
+ break;
+ case ClientOptions.DISPLAY_TILE_TEXT_REGIONS:
+ if (tile.getRegion() != null) {
+ if (FreeColDebugger.isInDebugMode(FreeColDebugger.DebugMode.MENUS)
+ && tile.getRegion().getName() == null) {
+ text = tile.getRegion().getSuffix();
+ } else {
+ text = Messages.message(tile.getRegion().getLabel());
+ }
+ }
+ break;
+ case ClientOptions.DISPLAY_TILE_TEXT_EMPTY:
+ break;
+ default:
+ logger.warning("displayTileText option " + op + " out of range");
+ break;
+ }
+
+ g.setColor(Color.BLACK);
+ g.setFont(FontLibrary.createFont(FontLibrary.FontType.NORMAL,
+ FontLibrary.FontSize.TINY, lib.getScaleFactor()));
+ if (text != null) {
+ int b = getBreakingPoint(text);
+ if (b == -1) {
+ g.drawString(text,
+ (tileWidth - g.getFontMetrics().stringWidth(text)) / 2,
+ (tileHeight - g.getFontMetrics().getAscent()) / 2);
+ } else {
+ g.drawString(text.substring(0, b),
+ (tileWidth - g.getFontMetrics().stringWidth(text.substring(0, b)))/2,
+ halfHeight - (g.getFontMetrics().getAscent()*2)/3);
+ g.drawString(text.substring(b+1),
+ (tileWidth - g.getFontMetrics().stringWidth(text.substring(b+1)))/2,
+ halfHeight + (g.getFontMetrics().getAscent()*2)/3);
+ }
+ }
+
+ if (FreeColDebugger.debugDisplayCoordinates()) {
+ String posString = tile.getX() + ", " + tile.getY();
+ if (tile.getHighSeasCount() >= 0) {
+ posString += "/" + Integer.toString(tile.getHighSeasCount());
+ }
+ g.drawString(posString,
+ (tileWidth - g.getFontMetrics().stringWidth(posString)) / 2,
+ (tileHeight - g.getFontMetrics().getAscent()) / 2);
+ }
+ String value = DebugUtils.getColonyValue(tile);
+ if (value != null) {
+ g.drawString(value,
+ (tileWidth - g.getFontMetrics().stringWidth(value)) / 2,
+ (tileHeight - g.getFontMetrics().getAscent()) / 2);
+ }
+ }
+
+ /**
+ * Displays the given Tile onto the given Graphics2D object at the
+ * location specified by the coordinates. Settlements and Lost
+ * City Rumours will be shown.
+ *
+ * @param g The Graphics2D object on which to draw the Tile.
+ * @param tile The Tile to draw.
+ * @param withNumber Whether to display the number of units present.
+ */
+ void displaySettlementWithChipsOrPopulationNumber(
+ Graphics2D g, Tile tile, boolean withNumber) {
+ final Player player = freeColClient.getMyPlayer();
+ final Settlement settlement = tile.getSettlement();
+
+ if (settlement != null) {
+ if (settlement instanceof Colony) {
+ Colony colony = (Colony)settlement;
+
+ // Draw image of colony in center of the tile.
+ BufferedImage colonyImage = lib.getSettlementImage(settlement);
+ displayLargeCenteredImage(g, colonyImage);
+
+ if (withNumber) {
+ String populationString = Integer.toString(
+ colony.getDisplayUnitCount());
+ int bonus = colony.getProductionBonus();
+ Color theColor = ResourceManager.getColor(
+ "color.map.productionBonus." + bonus);
+ // if government admits even more units, use
+ // italic and bigger number icon
+ Font font = (colony.getPreferredSizeChange() > 0)
+ ? FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
+ FontLibrary.FontSize.SMALLER, Font.BOLD | Font.ITALIC,
+ lib.getScaleFactor())
+ : FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
+ FontLibrary.FontSize.TINY, Font.BOLD,
+ lib.getScaleFactor());
+ BufferedImage stringImage = lib.getStringImage(g,
+ populationString, theColor, font);
+ displayCenteredImage(g, stringImage);
+ }
+
+ } else if (settlement instanceof IndianSettlement) {
+ IndianSettlement is = (IndianSettlement)settlement;
+ BufferedImage settlementImage = lib.getSettlementImage(settlement);
+
+ // Draw image of indian settlement in center of the tile.
+ displayCenteredImage(g, settlementImage);
+
+ BufferedImage chip;
+ float xOffset = STATE_OFFSET_X * lib.getScaleFactor();
+ float yOffset = STATE_OFFSET_Y * lib.getScaleFactor();
+ final int colonyLabels = freeColClient.getClientOptions()
+ .getInteger(ClientOptions.COLONY_LABELS);
+ if (colonyLabels != ClientOptions.COLONY_LABELS_MODERN) {
+ // Draw the settlement chip
+ chip = lib.getIndianSettlementChip(g, is);
+ g.drawImage(chip, (int)xOffset, (int)yOffset, null);
+ xOffset += chip.getWidth() + 2;
+
+ // Draw the mission chip if needed.
+ Unit missionary = is.getMissionary();
+ if (missionary != null) {
+ boolean expert
+ = missionary.hasAbility(Ability.EXPERT_MISSIONARY);
+ g.drawImage(lib.getMissionChip(g, missionary.getOwner(),
+ expert),
+ (int)xOffset, (int)yOffset, null);
+ xOffset += chip.getWidth() + 2;
+ }
+ }
+
+ // Draw the alarm chip if needed.
+ if ((chip = lib.getAlarmChip(g, is, player)) != null) {
+ g.drawImage(chip, (int)xOffset, (int)yOffset, null);
+ }
+ } else {
+ logger.warning("Bogus settlement: " + settlement);
+ }
+ }
+ }
+
+ /**
+ * Displays the given tile's items onto the given Graphics2D object.
+ * Additions and improvements to Tile will be drawn.
+ * Only works for explored tiles.
+ *
+ * @param g The Graphics2D object on which to draw the Tile.
+ * @param tile The Tile to draw.
+ * @param overlayImage The BufferedImage for the tile overlay.
+ */
+ void displayTileItems(Graphics2D g, Tile tile, BufferedImage overlayImage) {
+ // ATTENTION: we assume that only overlays and forests
+ // might be taller than a tile.
+
+ // layer additions and improvements according to zIndex
+ List tileItems = (tile.getTileItemContainer() != null)
+ ? tile.getTileItemContainer().getTileItems()
+ : new ArrayList();
+ int startIndex = 0;
+ for (int index = startIndex; index < tileItems.size(); index++) {
+ if (tileItems.get(index).getZIndex() < Tile.OVERLAY_ZINDEX) {
+ displayTileItem(g, tile, tileItems.get(index));
+ startIndex = index + 1;
+ } else {
+ startIndex = index;
+ break;
+ }
+ }
+ // Tile Overlays (eg. hills and mountains)
+ if (overlayImage != null) {
+ g.drawImage(overlayImage,
+ 0, (tileHeight - overlayImage.getHeight()), null);
+ }
+ for (int index = startIndex; index < tileItems.size(); index++) {
+ if (tileItems.get(index).getZIndex() < Tile.FOREST_ZINDEX) {
+ displayTileItem(g, tile, tileItems.get(index));
+ startIndex = index + 1;
+ } else {
+ startIndex = index;
+ break;
+ }
+ }
+ // Forest
+ if (tile.isForested()) {
+ BufferedImage forestImage = lib.getForestImage(
+ tile.getType(), tile.getRiverStyle());
+ g.drawImage(forestImage,
+ 0, (tileHeight - forestImage.getHeight()), null);
+ }
+
+ // draw all remaining items
+ for (TileItem ti : tileItems.subList(startIndex, tileItems.size())) {
+ displayTileItem(g, tile, ti);
+ }
+ }
+
+ /**
+ * Draws the given TileItem on the given Tile.
+ */
+ private void displayTileItem(Graphics2D g, Tile tile, TileItem item) {
+ if (item instanceof TileImprovement) {
+ displayTileImprovement(g, tile, (TileImprovement)item);
+ } else if (item instanceof LostCityRumour) {
+ displayLostCityRumour(g);
+ } else {
+ displayResourceTileItem(g, (Resource) item);
+ }
+ }
+
+ private void displayResourceTileItem(Graphics2D g, Resource item) {
+ BufferedImage bonusImage = lib.getMiscImage(
+ "image.tileitem." + item.getType().getId());
+ displayCenteredImage(g, bonusImage);
+ }
+
+ private void displayLostCityRumour(Graphics2D g) {
+ displayCenteredImage(g,
+ lib.getMiscImage(ImageLibrary.LOST_CITY_RUMOUR));
+ }
+
+ private void displayTileImprovement(Graphics2D g,
+ Tile tile, TileImprovement ti) {
+ if (ti.isComplete()) {
+ if (ti.isRoad()) {
+ rp.displayRoad(g, tile);
+ } else if (ti.isRiver()
+ && ti.getMagnitude() < TileImprovement.FJORD_RIVER) {
+ // @compat 0.10.5
+ // America_large had some bogus rivers in 0.10.5
+ if (ti.getStyle() != null)
+ // end @compat 0.10.5
+ g.drawImage(lib.getRiverImage(ti.getStyle()), 0, 0, null);
+ } else {
+ String key = "image.tile." + ti.getType().getId();
+ if (ResourceManager.hasImageResource(key)) {
+ // Has its own Overlay Image in Misc, use it
+ BufferedImage overlay = ResourceManager.getImage(key,
+ lib.tileSize);
+ g.drawImage(overlay, 0, 0, null);
+ }
+ }
+ }
+ }
+
+}
diff --git a/src/net/sf/freecol/client/gui/action/AboutAction.java b/src/net/sf/freecol/client/gui/action/AboutAction.java
index 8c764eea8..339b60437 100644
--- a/src/net/sf/freecol/client/gui/action/AboutAction.java
+++ b/src/net/sf/freecol/client/gui/action/AboutAction.java
@@ -51,7 +51,7 @@ public class AboutAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showAboutPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ActionManager.java b/src/net/sf/freecol/client/gui/action/ActionManager.java
index 4c16ab10f..1eba723c9 100644
--- a/src/net/sf/freecol/client/gui/action/ActionManager.java
+++ b/src/net/sf/freecol/client/gui/action/ActionManager.java
@@ -19,7 +19,6 @@
package net.sf.freecol.client.gui.action;
-import java.util.Iterator;
import java.util.logging.Logger;
import net.sf.freecol.client.FreeColClient;
@@ -175,6 +174,7 @@ public class ActionManager extends OptionGroup {
add(new ImprovementAction(freeColClient, type));
}
}
+ update();
}
/**
diff --git a/src/net/sf/freecol/client/gui/action/AssignTradeRouteAction.java b/src/net/sf/freecol/client/gui/action/AssignTradeRouteAction.java
index 10e0e6fbf..a26106f5a 100644
--- a/src/net/sf/freecol/client/gui/action/AssignTradeRouteAction.java
+++ b/src/net/sf/freecol/client/gui/action/AssignTradeRouteAction.java
@@ -64,7 +64,7 @@ public class AssignTradeRouteAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
Unit unit = getGUI().getActiveUnit();
if (unit != null) getGUI().showTradeRoutePanel(unit);
}
diff --git a/src/net/sf/freecol/client/gui/action/BuildColonyAction.java b/src/net/sf/freecol/client/gui/action/BuildColonyAction.java
index 328b9c76f..20c7e08de 100644
--- a/src/net/sf/freecol/client/gui/action/BuildColonyAction.java
+++ b/src/net/sf/freecol/client/gui/action/BuildColonyAction.java
@@ -68,7 +68,7 @@ public class BuildColonyAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().buildColony(getGUI().getActiveUnit());
}
}
diff --git a/src/net/sf/freecol/client/gui/action/CenterAction.java b/src/net/sf/freecol/client/gui/action/CenterAction.java
index f3c1346ae..751133396 100644
--- a/src/net/sf/freecol/client/gui/action/CenterAction.java
+++ b/src/net/sf/freecol/client/gui/action/CenterAction.java
@@ -48,7 +48,7 @@ public class CenterAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().centerActiveUnit();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ChangeAction.java b/src/net/sf/freecol/client/gui/action/ChangeAction.java
index a6815bbc9..8c51a250e 100644
--- a/src/net/sf/freecol/client/gui/action/ChangeAction.java
+++ b/src/net/sf/freecol/client/gui/action/ChangeAction.java
@@ -70,14 +70,14 @@ public class ChangeAction extends UnitAction {
public final void update() {
super.update();
- Unit unit = getGUI().getActiveUnit();
+ final Unit unit = getGUI().getActiveUnit();
if (unit != null && unit.hasTile()) {
if (unit.getColony() != null) {
- putValue(NAME, Messages.message("changeAction.enterColony.name"));
+ putValue(NAME, Messages.getName("changeAction.enterColony"));
} else if (unit.isOnCarrier()) {
- putValue(NAME, Messages.message("changeAction.selectCarrier.name"));
+ putValue(NAME, Messages.getName("changeAction.selectCarrier"));
} else {
- putValue(NAME, Messages.message("changeAction.nextUnitOnTile.name"));
+ putValue(NAME, Messages.getName("changeAction.nextUnitOnTile"));
}
}
}
@@ -89,9 +89,9 @@ public class ChangeAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- Unit unit = getGUI().getActiveUnit();
- Tile tile = unit.getTile();
+ public void actionPerformed(ActionEvent ae) {
+ final Unit unit = getGUI().getActiveUnit();
+ final Tile tile = unit.getTile();
if (tile.getColony() != null) {
getGUI().showColonyPanel(tile.getColony(), unit);
diff --git a/src/net/sf/freecol/client/gui/action/ChangeWindowedModeAction.java b/src/net/sf/freecol/client/gui/action/ChangeWindowedModeAction.java
index 84d5b7d8a..8a4bd7cc4 100644
--- a/src/net/sf/freecol/client/gui/action/ChangeWindowedModeAction.java
+++ b/src/net/sf/freecol/client/gui/action/ChangeWindowedModeAction.java
@@ -75,9 +75,9 @@ public class ChangeWindowedModeAction extends SelectableAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
GUI gui = getGUI();
if (gui == null) return;
- gui.changeWindowedMode(!gui.isWindowed());
+ gui.changeWindowedMode();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ChatAction.java b/src/net/sf/freecol/client/gui/action/ChatAction.java
index 9dafbf861..186353faf 100644
--- a/src/net/sf/freecol/client/gui/action/ChatAction.java
+++ b/src/net/sf/freecol/client/gui/action/ChatAction.java
@@ -64,7 +64,7 @@ public class ChatAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showChatPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ClearOrdersAction.java b/src/net/sf/freecol/client/gui/action/ClearOrdersAction.java
index c21bbd85a..798461124 100644
--- a/src/net/sf/freecol/client/gui/action/ClearOrdersAction.java
+++ b/src/net/sf/freecol/client/gui/action/ClearOrdersAction.java
@@ -48,7 +48,7 @@ public class ClearOrdersAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().clearOrders(getGUI().getActiveUnit());
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ColopediaAction.java b/src/net/sf/freecol/client/gui/action/ColopediaAction.java
index a0a23b734..fb65cb146 100644
--- a/src/net/sf/freecol/client/gui/action/ColopediaAction.java
+++ b/src/net/sf/freecol/client/gui/action/ColopediaAction.java
@@ -33,9 +33,10 @@ public class ColopediaAction extends FreeColAction {
public static final String id = "colopediaAction.";
+ // Order of elements will influence ingame order of menu items.
public static enum PanelType {
- TERRAIN, RESOURCES, UNITS, GOODS,
- SKILLS, BUILDINGS, FATHERS, NATIONS,
+ TERRAIN, RESOURCES, GOODS, UNITS,
+ BUILDINGS, FATHERS, NATIONS,
NATION_TYPES, CONCEPTS;
public String getKey() {
@@ -46,9 +47,8 @@ public class ColopediaAction extends FreeColAction {
private static final int[] mnemonics = {
KeyEvent.VK_T,
KeyEvent.VK_R,
- KeyEvent.VK_U,
KeyEvent.VK_G,
- KeyEvent.VK_S,
+ KeyEvent.VK_U,
KeyEvent.VK_B,
KeyEvent.VK_F,
KeyEvent.VK_N,
@@ -76,7 +76,7 @@ public class ColopediaAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showColopediaPanel(getId());
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ContinueAction.java b/src/net/sf/freecol/client/gui/action/ContinueAction.java
index a6c14ee36..276d51a95 100644
--- a/src/net/sf/freecol/client/gui/action/ContinueAction.java
+++ b/src/net/sf/freecol/client/gui/action/ContinueAction.java
@@ -55,7 +55,7 @@ public class ContinueAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
File lastSave = FreeColDirectories.getLastSaveGameFile();
if (lastSave != null) {
getGUI().removeInGameComponents();
diff --git a/src/net/sf/freecol/client/gui/action/DebugAction.java b/src/net/sf/freecol/client/gui/action/DebugAction.java
index 2cf350bef..d8f503691 100644
--- a/src/net/sf/freecol/client/gui/action/DebugAction.java
+++ b/src/net/sf/freecol/client/gui/action/DebugAction.java
@@ -66,7 +66,7 @@ public class DebugAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (shouldBeEnabled()) {
igc().setInDebugMode();
getConnectController().reconnect();
diff --git a/src/net/sf/freecol/client/gui/action/DeclareIndependenceAction.java b/src/net/sf/freecol/client/gui/action/DeclareIndependenceAction.java
index cd6a5c4e0..98eb373ec 100644
--- a/src/net/sf/freecol/client/gui/action/DeclareIndependenceAction.java
+++ b/src/net/sf/freecol/client/gui/action/DeclareIndependenceAction.java
@@ -63,8 +63,7 @@ public class DeclareIndependenceAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().declareIndependence();
- update();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/DetermineHighSeasAction.java b/src/net/sf/freecol/client/gui/action/DetermineHighSeasAction.java
index a8732600f..8d46720fd 100644
--- a/src/net/sf/freecol/client/gui/action/DetermineHighSeasAction.java
+++ b/src/net/sf/freecol/client/gui/action/DetermineHighSeasAction.java
@@ -64,7 +64,7 @@ public class DetermineHighSeasAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
final Map map = getGame().getMap();
Parameters p = getGUI().showParametersDialog();
diff --git a/src/net/sf/freecol/client/gui/action/DisbandUnitAction.java b/src/net/sf/freecol/client/gui/action/DisbandUnitAction.java
index 936469bbb..56539711b 100644
--- a/src/net/sf/freecol/client/gui/action/DisbandUnitAction.java
+++ b/src/net/sf/freecol/client/gui/action/DisbandUnitAction.java
@@ -50,7 +50,7 @@ public class DisbandUnitAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().disbandUnit(getGUI().getActiveUnit());
}
}
diff --git a/src/net/sf/freecol/client/gui/action/DisplayBordersAction.java b/src/net/sf/freecol/client/gui/action/DisplayBordersAction.java
index 520814ad0..eeda94b0f 100644
--- a/src/net/sf/freecol/client/gui/action/DisplayBordersAction.java
+++ b/src/net/sf/freecol/client/gui/action/DisplayBordersAction.java
@@ -51,8 +51,8 @@ public class DisplayBordersAction extends SelectableAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- setSelected(((JCheckBoxMenuItem) e.getSource()).isSelected());
+ public void actionPerformed(ActionEvent ae) {
+ setSelected(((JCheckBoxMenuItem)ae.getSource()).isSelected());
setOption(isSelected());
getGUI().refresh();
}
diff --git a/src/net/sf/freecol/client/gui/action/DisplayGridAction.java b/src/net/sf/freecol/client/gui/action/DisplayGridAction.java
index a7ecd0625..95dec50da 100644
--- a/src/net/sf/freecol/client/gui/action/DisplayGridAction.java
+++ b/src/net/sf/freecol/client/gui/action/DisplayGridAction.java
@@ -51,8 +51,8 @@ public class DisplayGridAction extends SelectableAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- setSelected(((JCheckBoxMenuItem)e.getSource()).isSelected());
+ public void actionPerformed(ActionEvent ae) {
+ setSelected(((JCheckBoxMenuItem)ae.getSource()).isSelected());
setOption(isSelected());
getGUI().refresh();
}
diff --git a/src/net/sf/freecol/client/gui/action/DisplayTileTextAction.java b/src/net/sf/freecol/client/gui/action/DisplayTileTextAction.java
index 81c65f130..93d71f140 100644
--- a/src/net/sf/freecol/client/gui/action/DisplayTileTextAction.java
+++ b/src/net/sf/freecol/client/gui/action/DisplayTileTextAction.java
@@ -94,8 +94,8 @@ public class DisplayTileTextAction extends SelectableAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- if (((JRadioButtonMenuItem) e.getSource()).isSelected()) {
+ public void actionPerformed(ActionEvent ae) {
+ if (((JRadioButtonMenuItem)ae.getSource()).isSelected()) {
freeColClient.getClientOptions()
.setInteger(ClientOptions.DISPLAY_TILE_TEXT, display.ordinal());
getGUI().refresh();
diff --git a/src/net/sf/freecol/client/gui/action/EndTurnAction.java b/src/net/sf/freecol/client/gui/action/EndTurnAction.java
index 828ddf738..9d0a6db50 100644
--- a/src/net/sf/freecol/client/gui/action/EndTurnAction.java
+++ b/src/net/sf/freecol/client/gui/action/EndTurnAction.java
@@ -50,7 +50,7 @@ public class EndTurnAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().endTurn(true);
}
}
diff --git a/src/net/sf/freecol/client/gui/action/EuropeAction.java b/src/net/sf/freecol/client/gui/action/EuropeAction.java
index 846a72acf..e125e69bf 100644
--- a/src/net/sf/freecol/client/gui/action/EuropeAction.java
+++ b/src/net/sf/freecol/client/gui/action/EuropeAction.java
@@ -62,7 +62,7 @@ public class EuropeAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showEuropePanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ExecuteGotoOrdersAction.java b/src/net/sf/freecol/client/gui/action/ExecuteGotoOrdersAction.java
index 9728d305a..62c375f1c 100644
--- a/src/net/sf/freecol/client/gui/action/ExecuteGotoOrdersAction.java
+++ b/src/net/sf/freecol/client/gui/action/ExecuteGotoOrdersAction.java
@@ -48,7 +48,7 @@ public class ExecuteGotoOrdersAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().executeGotoOrders();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/FindSettlementAction.java b/src/net/sf/freecol/client/gui/action/FindSettlementAction.java
index b96b1ef18..2fffdf4a8 100644
--- a/src/net/sf/freecol/client/gui/action/FindSettlementAction.java
+++ b/src/net/sf/freecol/client/gui/action/FindSettlementAction.java
@@ -48,7 +48,7 @@ public class FindSettlementAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showFindSettlementPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/FortifyAction.java b/src/net/sf/freecol/client/gui/action/FortifyAction.java
index f0253520b..a7dc00cce 100644
--- a/src/net/sf/freecol/client/gui/action/FortifyAction.java
+++ b/src/net/sf/freecol/client/gui/action/FortifyAction.java
@@ -63,7 +63,7 @@ public class FortifyAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().changeState(getGUI().getActiveUnit(),
Unit.UnitState.FORTIFYING);
}
diff --git a/src/net/sf/freecol/client/gui/action/FreeColAction.java b/src/net/sf/freecol/client/gui/action/FreeColAction.java
index 593088884..721d1b3e3 100644
--- a/src/net/sf/freecol/client/gui/action/FreeColAction.java
+++ b/src/net/sf/freecol/client/gui/action/FreeColAction.java
@@ -19,13 +19,11 @@
package net.sf.freecol.client.gui.action;
-import java.awt.Image;
import java.awt.event.ActionEvent;
import java.util.logging.Logger;
import javax.swing.AbstractAction;
import javax.swing.Action;
-import javax.swing.ImageIcon;
import javax.swing.KeyStroke;
import javax.swing.event.MenuKeyEvent;
import javax.swing.event.MenuKeyListener;
@@ -241,14 +239,10 @@ public abstract class FreeColAction extends AbstractAction
+ (ResourceManager.hasImageResource(pressedKey) ? 1 : 0)
+ (ResourceManager.hasImageResource(disabledKey) ? 1 : 0);
if (hasOrderButtons()) {
- Image normal = ResourceManager.getImage(normalKey);
- Image highlighted = ResourceManager.getImage(highlightedKey);
- Image pressed = ResourceManager.getImage(pressedKey);
- Image disabled = ResourceManager.getImage(disabledKey);
- putValue(BUTTON_IMAGE, new ImageIcon(normal));
- putValue(BUTTON_ROLLOVER_IMAGE, new ImageIcon(highlighted));
- putValue(BUTTON_PRESSED_IMAGE, new ImageIcon(pressed));
- putValue(BUTTON_DISABLED_IMAGE, new ImageIcon(disabled));
+ putValue(BUTTON_IMAGE, normalKey);
+ putValue(BUTTON_ROLLOVER_IMAGE, highlightedKey);
+ putValue(BUTTON_PRESSED_IMAGE, pressedKey);
+ putValue(BUTTON_DISABLED_IMAGE, disabledKey);
} else {
logger.warning("Missing " + (4-orderButtonImageCount)
+ " order button images for " + getId());
@@ -364,9 +358,7 @@ public abstract class FreeColAction extends AbstractAction
*/
public void update() {
boolean b = shouldBeEnabled();
- if (isEnabled() != b) {
- setEnabled(b);
- }
+ if (isEnabled() != b) setEnabled(b);
}
diff --git a/src/net/sf/freecol/client/gui/action/GotoAction.java b/src/net/sf/freecol/client/gui/action/GotoAction.java
index fb76091a9..99040e589 100644
--- a/src/net/sf/freecol/client/gui/action/GotoAction.java
+++ b/src/net/sf/freecol/client/gui/action/GotoAction.java
@@ -62,7 +62,7 @@ public class GotoAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
Unit unit = getGUI().getActiveUnit();
if (unit != null) {
igc().selectDestination(unit);
diff --git a/src/net/sf/freecol/client/gui/action/GotoTileAction.java b/src/net/sf/freecol/client/gui/action/GotoTileAction.java
index 9c7f21850..02fe05c17 100644
--- a/src/net/sf/freecol/client/gui/action/GotoTileAction.java
+++ b/src/net/sf/freecol/client/gui/action/GotoTileAction.java
@@ -60,7 +60,7 @@ public class GotoTileAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().activateGotoPath();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ImprovementAction.java b/src/net/sf/freecol/client/gui/action/ImprovementAction.java
index 2a86d03fb..381d5d4d6 100644
--- a/src/net/sf/freecol/client/gui/action/ImprovementAction.java
+++ b/src/net/sf/freecol/client/gui/action/ImprovementAction.java
@@ -78,7 +78,7 @@ public class ImprovementAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
Unit unit = getGUI().getActiveUnit();
if (unit == null) return;
diff --git a/src/net/sf/freecol/client/gui/action/LoadAction.java b/src/net/sf/freecol/client/gui/action/LoadAction.java
index a9a4e305d..c3e5a5e53 100644
--- a/src/net/sf/freecol/client/gui/action/LoadAction.java
+++ b/src/net/sf/freecol/client/gui/action/LoadAction.java
@@ -68,7 +68,7 @@ public class LoadAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
final Unit unit = getGUI().getActiveUnit();
if (unit == null) return;
diff --git a/src/net/sf/freecol/client/gui/action/MapControlsAction.java b/src/net/sf/freecol/client/gui/action/MapControlsAction.java
index 1d75f27bf..22d1d0b47 100644
--- a/src/net/sf/freecol/client/gui/action/MapControlsAction.java
+++ b/src/net/sf/freecol/client/gui/action/MapControlsAction.java
@@ -64,8 +64,8 @@ public class MapControlsAction extends SelectableAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- setSelected(((AbstractButton)e.getSource()).isSelected());
+ public void actionPerformed(ActionEvent ae) {
+ setSelected(((AbstractButton)ae.getSource()).isSelected());
setOption(isSelected());
update();
}
diff --git a/src/net/sf/freecol/client/gui/action/MapEditorAction.java b/src/net/sf/freecol/client/gui/action/MapEditorAction.java
index 8140e9d2a..79362ad64 100644
--- a/src/net/sf/freecol/client/gui/action/MapEditorAction.java
+++ b/src/net/sf/freecol/client/gui/action/MapEditorAction.java
@@ -48,7 +48,7 @@ public class MapEditorAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
freeColClient.getMapEditorController().startMapEditor();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/MiniMapToggleFogOfWarAction.java b/src/net/sf/freecol/client/gui/action/MiniMapToggleFogOfWarAction.java
index 1b442c228..3afbf8498 100644
--- a/src/net/sf/freecol/client/gui/action/MiniMapToggleFogOfWarAction.java
+++ b/src/net/sf/freecol/client/gui/action/MiniMapToggleFogOfWarAction.java
@@ -62,7 +62,7 @@ public class MiniMapToggleFogOfWarAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().miniMapToggleFogOfWarControls();
if (freeColClient.getClientOptions().getBoolean(ClientOptions.MINIMAP_TOGGLE_FOG_OF_WAR)) {
diff --git a/src/net/sf/freecol/client/gui/action/MiniMapToggleViewAction.java b/src/net/sf/freecol/client/gui/action/MiniMapToggleViewAction.java
index b437d318f..35202ebc1 100644
--- a/src/net/sf/freecol/client/gui/action/MiniMapToggleViewAction.java
+++ b/src/net/sf/freecol/client/gui/action/MiniMapToggleViewAction.java
@@ -62,7 +62,7 @@ public class MiniMapToggleViewAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().miniMapToggleViewControls();
if (freeColClient.getClientOptions().getBoolean(ClientOptions.MINIMAP_TOGGLE_BORDERS)) {
diff --git a/src/net/sf/freecol/client/gui/action/MiniMapZoomInAction.java b/src/net/sf/freecol/client/gui/action/MiniMapZoomInAction.java
index b1d3f44b1..6fe89c3c7 100644
--- a/src/net/sf/freecol/client/gui/action/MiniMapZoomInAction.java
+++ b/src/net/sf/freecol/client/gui/action/MiniMapZoomInAction.java
@@ -73,7 +73,7 @@ public class MiniMapZoomInAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().zoomInMapControls();
update();
getActionManager().getFreeColAction(MiniMapZoomOutAction.id).update();
diff --git a/src/net/sf/freecol/client/gui/action/MiniMapZoomOutAction.java b/src/net/sf/freecol/client/gui/action/MiniMapZoomOutAction.java
index 9c7874a84..4ff530e21 100644
--- a/src/net/sf/freecol/client/gui/action/MiniMapZoomOutAction.java
+++ b/src/net/sf/freecol/client/gui/action/MiniMapZoomOutAction.java
@@ -73,7 +73,7 @@ public class MiniMapZoomOutAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().zoomOutMapControls();
update();
getActionManager().getFreeColAction(MiniMapZoomInAction.id).update();
diff --git a/src/net/sf/freecol/client/gui/action/MoveAction.java b/src/net/sf/freecol/client/gui/action/MoveAction.java
index 26987bf47..5b1ac0fe9 100644
--- a/src/net/sf/freecol/client/gui/action/MoveAction.java
+++ b/src/net/sf/freecol/client/gui/action/MoveAction.java
@@ -69,7 +69,7 @@ public class MoveAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
switch (getGUI().getViewMode()) {
case GUI.MOVE_UNITS_MODE:
igc().moveUnit(getGUI().getActiveUnit(), direction);
diff --git a/src/net/sf/freecol/client/gui/action/NewAction.java b/src/net/sf/freecol/client/gui/action/NewAction.java
index baa8fdccb..50cfc5196 100644
--- a/src/net/sf/freecol/client/gui/action/NewAction.java
+++ b/src/net/sf/freecol/client/gui/action/NewAction.java
@@ -48,11 +48,11 @@ public class NewAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (freeColClient.isMapEditor()) {
freeColClient.getMapEditorController().newMap();
} else {
- freeColClient.newGame();
+ freeColClient.newGame(true);
}
}
}
diff --git a/src/net/sf/freecol/client/gui/action/NewEmptyMapAction.java b/src/net/sf/freecol/client/gui/action/NewEmptyMapAction.java
index bae197888..b7063678e 100644
--- a/src/net/sf/freecol/client/gui/action/NewEmptyMapAction.java
+++ b/src/net/sf/freecol/client/gui/action/NewEmptyMapAction.java
@@ -63,7 +63,7 @@ public class NewEmptyMapAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
Dimension size = getGUI().showMapSizeDialog();
if (size == null) return;
final Game game = getGame();
@@ -72,7 +72,7 @@ public class NewEmptyMapAction extends MapboardAction {
game.setMap(map);
Tile tile = map.getTile(size.width/2, size.height/2);
getGUI().setFocus(tile);
- getFreeColClient().updateActions();
+ getGUI().updateMenuBar();
getGUI().refresh();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/OpenAction.java b/src/net/sf/freecol/client/gui/action/OpenAction.java
index a13b7d36d..be539d1b9 100644
--- a/src/net/sf/freecol/client/gui/action/OpenAction.java
+++ b/src/net/sf/freecol/client/gui/action/OpenAction.java
@@ -48,7 +48,7 @@ public class OpenAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (!freeColClient.isMapEditor()) {
igc().loadGame();
} else {
diff --git a/src/net/sf/freecol/client/gui/action/PreferencesAction.java b/src/net/sf/freecol/client/gui/action/PreferencesAction.java
index 2d705d7e2..eae03a6c7 100644
--- a/src/net/sf/freecol/client/gui/action/PreferencesAction.java
+++ b/src/net/sf/freecol/client/gui/action/PreferencesAction.java
@@ -48,7 +48,7 @@ public class PreferencesAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showClientOptionsDialog();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/QuitAction.java b/src/net/sf/freecol/client/gui/action/QuitAction.java
index 79c2ada4a..e442036c0 100644
--- a/src/net/sf/freecol/client/gui/action/QuitAction.java
+++ b/src/net/sf/freecol/client/gui/action/QuitAction.java
@@ -48,7 +48,7 @@ public class QuitAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
freeColClient.askToQuit();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReconnectAction.java b/src/net/sf/freecol/client/gui/action/ReconnectAction.java
index 9be9c4d8b..d04b7f3d8 100644
--- a/src/net/sf/freecol/client/gui/action/ReconnectAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReconnectAction.java
@@ -48,7 +48,7 @@ public class ReconnectAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().reconnect();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/RenameAction.java b/src/net/sf/freecol/client/gui/action/RenameAction.java
index dae097387..3a89d4f30 100644
--- a/src/net/sf/freecol/client/gui/action/RenameAction.java
+++ b/src/net/sf/freecol/client/gui/action/RenameAction.java
@@ -48,7 +48,7 @@ public class RenameAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().rename(getGUI().getActiveUnit());
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportCargoAction.java b/src/net/sf/freecol/client/gui/action/ReportCargoAction.java
index 86168b066..3cc788092 100644
--- a/src/net/sf/freecol/client/gui/action/ReportCargoAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportCargoAction.java
@@ -48,7 +48,7 @@ public class ReportCargoAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportCargoPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportColonyAction.java b/src/net/sf/freecol/client/gui/action/ReportColonyAction.java
index 69eb3499d..ebb26a448 100644
--- a/src/net/sf/freecol/client/gui/action/ReportColonyAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportColonyAction.java
@@ -48,7 +48,7 @@ public class ReportColonyAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportColonyPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportContinentalCongressAction.java b/src/net/sf/freecol/client/gui/action/ReportContinentalCongressAction.java
index 8c4683cf2..387de28de 100644
--- a/src/net/sf/freecol/client/gui/action/ReportContinentalCongressAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportContinentalCongressAction.java
@@ -48,7 +48,7 @@ public class ReportContinentalCongressAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportContinentalCongressPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportEducationAction.java b/src/net/sf/freecol/client/gui/action/ReportEducationAction.java
index c50184e9b..250d5bd09 100644
--- a/src/net/sf/freecol/client/gui/action/ReportEducationAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportEducationAction.java
@@ -48,7 +48,7 @@ public class ReportEducationAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportEducationPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportExplorationAction.java b/src/net/sf/freecol/client/gui/action/ReportExplorationAction.java
index 83f4324a7..ea32e4b93 100644
--- a/src/net/sf/freecol/client/gui/action/ReportExplorationAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportExplorationAction.java
@@ -48,7 +48,7 @@ public class ReportExplorationAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
freeColClient.getGUI().showReportExplorationPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportForeignAction.java b/src/net/sf/freecol/client/gui/action/ReportForeignAction.java
index da9a4927e..74f8fc39f 100644
--- a/src/net/sf/freecol/client/gui/action/ReportForeignAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportForeignAction.java
@@ -48,7 +48,7 @@ public class ReportForeignAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportForeignAffairPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportHighScoresAction.java b/src/net/sf/freecol/client/gui/action/ReportHighScoresAction.java
index 685bab740..810a562d8 100644
--- a/src/net/sf/freecol/client/gui/action/ReportHighScoresAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportHighScoresAction.java
@@ -48,7 +48,7 @@ public class ReportHighScoresAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().displayHighScores(null);
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportHistoryAction.java b/src/net/sf/freecol/client/gui/action/ReportHistoryAction.java
index e6214dd85..ff2816d69 100644
--- a/src/net/sf/freecol/client/gui/action/ReportHistoryAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportHistoryAction.java
@@ -48,7 +48,7 @@ public class ReportHistoryAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportHistoryPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportIndianAction.java b/src/net/sf/freecol/client/gui/action/ReportIndianAction.java
index abca471fd..ce5d98089 100644
--- a/src/net/sf/freecol/client/gui/action/ReportIndianAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportIndianAction.java
@@ -48,7 +48,7 @@ public class ReportIndianAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportIndianPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportLabourAction.java b/src/net/sf/freecol/client/gui/action/ReportLabourAction.java
index c4b568a5b..879568ce9 100644
--- a/src/net/sf/freecol/client/gui/action/ReportLabourAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportLabourAction.java
@@ -49,7 +49,7 @@ public class ReportLabourAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (getClientOptions().getInteger(ClientOptions.LABOUR_REPORT)
== ClientOptions.LABOUR_REPORT_CLASSIC) {
getGUI().showReportLabourPanel();
diff --git a/src/net/sf/freecol/client/gui/action/ReportMilitaryAction.java b/src/net/sf/freecol/client/gui/action/ReportMilitaryAction.java
index 1f021f73a..af40e6dab 100644
--- a/src/net/sf/freecol/client/gui/action/ReportMilitaryAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportMilitaryAction.java
@@ -48,7 +48,7 @@ public class ReportMilitaryAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportMilitaryPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportNavalAction.java b/src/net/sf/freecol/client/gui/action/ReportNavalAction.java
index 1d53fc23e..0d8dbafad 100644
--- a/src/net/sf/freecol/client/gui/action/ReportNavalAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportNavalAction.java
@@ -48,7 +48,7 @@ public class ReportNavalAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportNavalPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportProductionAction.java b/src/net/sf/freecol/client/gui/action/ReportProductionAction.java
index f3be6756a..a946d17ef 100644
--- a/src/net/sf/freecol/client/gui/action/ReportProductionAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportProductionAction.java
@@ -48,7 +48,7 @@ public class ReportProductionAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportProductionPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportReligionAction.java b/src/net/sf/freecol/client/gui/action/ReportReligionAction.java
index bf10a473b..dc5eebddc 100644
--- a/src/net/sf/freecol/client/gui/action/ReportReligionAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportReligionAction.java
@@ -48,7 +48,7 @@ public class ReportReligionAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportReligiousPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportRequirementsAction.java b/src/net/sf/freecol/client/gui/action/ReportRequirementsAction.java
index 4e14b9f38..8901e8ea0 100644
--- a/src/net/sf/freecol/client/gui/action/ReportRequirementsAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportRequirementsAction.java
@@ -48,7 +48,7 @@ public class ReportRequirementsAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportRequirementsPanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportTradeAction.java b/src/net/sf/freecol/client/gui/action/ReportTradeAction.java
index d0d88188d..766b770c0 100644
--- a/src/net/sf/freecol/client/gui/action/ReportTradeAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportTradeAction.java
@@ -48,7 +48,7 @@ public class ReportTradeAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showReportTradePanel();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ReportTurnAction.java b/src/net/sf/freecol/client/gui/action/ReportTurnAction.java
index 8acb1d972..b4208145c 100644
--- a/src/net/sf/freecol/client/gui/action/ReportTurnAction.java
+++ b/src/net/sf/freecol/client/gui/action/ReportTurnAction.java
@@ -48,7 +48,7 @@ public class ReportTurnAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().displayTurnReportMessages();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/RetireAction.java b/src/net/sf/freecol/client/gui/action/RetireAction.java
index c1431e03d..dedb8330b 100644
--- a/src/net/sf/freecol/client/gui/action/RetireAction.java
+++ b/src/net/sf/freecol/client/gui/action/RetireAction.java
@@ -63,7 +63,7 @@ public class RetireAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
freeColClient.retire();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/SaveAction.java b/src/net/sf/freecol/client/gui/action/SaveAction.java
index c2817fd00..f24d7f480 100644
--- a/src/net/sf/freecol/client/gui/action/SaveAction.java
+++ b/src/net/sf/freecol/client/gui/action/SaveAction.java
@@ -63,7 +63,7 @@ public class SaveAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (!freeColClient.isMapEditor()) {
igc().saveGame();
} else {
diff --git a/src/net/sf/freecol/client/gui/action/SaveAndQuitAction.java b/src/net/sf/freecol/client/gui/action/SaveAndQuitAction.java
index 31ce57c24..71678a2f3 100644
--- a/src/net/sf/freecol/client/gui/action/SaveAndQuitAction.java
+++ b/src/net/sf/freecol/client/gui/action/SaveAndQuitAction.java
@@ -48,7 +48,7 @@ public class SaveAndQuitAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (freeColClient.isMapEditor()) {
freeColClient.getMapEditorController().saveGame();
} else {
diff --git a/src/net/sf/freecol/client/gui/action/ScaleMapAction.java b/src/net/sf/freecol/client/gui/action/ScaleMapAction.java
index 326bf09f1..f5ec13a61 100644
--- a/src/net/sf/freecol/client/gui/action/ScaleMapAction.java
+++ b/src/net/sf/freecol/client/gui/action/ScaleMapAction.java
@@ -96,7 +96,7 @@ public class ScaleMapAction extends FreeColAction {
t.getTileItemContainer().updateRiver();
}*/
- getGUI().setSelectedTile(map.getTile(0, 0), false);
+ getGUI().setSelectedTile(map.getTile(0, 0));
getGUI().refresh();
}
@@ -121,7 +121,7 @@ public class ScaleMapAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
Dimension ms = getGUI().showScaleMapSizeDialog();
if (ms != null) {
scaleMapTo(ms.width, ms.height);
diff --git a/src/net/sf/freecol/client/gui/action/ShowDifficultyAction.java b/src/net/sf/freecol/client/gui/action/ShowDifficultyAction.java
index 234690194..535322c04 100644
--- a/src/net/sf/freecol/client/gui/action/ShowDifficultyAction.java
+++ b/src/net/sf/freecol/client/gui/action/ShowDifficultyAction.java
@@ -48,7 +48,7 @@ public class ShowDifficultyAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showDifficultyDialog();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ShowGameOptionsAction.java b/src/net/sf/freecol/client/gui/action/ShowGameOptionsAction.java
index 74af1918e..168c21d11 100644
--- a/src/net/sf/freecol/client/gui/action/ShowGameOptionsAction.java
+++ b/src/net/sf/freecol/client/gui/action/ShowGameOptionsAction.java
@@ -48,7 +48,7 @@ public class ShowGameOptionsAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showGameOptionsDialog(false, false);
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ShowMainAction.java b/src/net/sf/freecol/client/gui/action/ShowMainAction.java
index fb9105497..92ef5e8c1 100644
--- a/src/net/sf/freecol/client/gui/action/ShowMainAction.java
+++ b/src/net/sf/freecol/client/gui/action/ShowMainAction.java
@@ -51,7 +51,7 @@ public class ShowMainAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (!getGUI().confirmStopGame()) return;
getConnectController().quitGame(true);
getGUI().removeInGameComponents();
diff --git a/src/net/sf/freecol/client/gui/action/ShowMapGeneratorOptionsAction.java b/src/net/sf/freecol/client/gui/action/ShowMapGeneratorOptionsAction.java
index f88375a57..49995bcb7 100644
--- a/src/net/sf/freecol/client/gui/action/ShowMapGeneratorOptionsAction.java
+++ b/src/net/sf/freecol/client/gui/action/ShowMapGeneratorOptionsAction.java
@@ -48,7 +48,7 @@ public class ShowMapGeneratorOptionsAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showMapGeneratorOptionsDialog(false);
}
}
diff --git a/src/net/sf/freecol/client/gui/action/SkipUnitAction.java b/src/net/sf/freecol/client/gui/action/SkipUnitAction.java
index fea637956..8a85bbf76 100644
--- a/src/net/sf/freecol/client/gui/action/SkipUnitAction.java
+++ b/src/net/sf/freecol/client/gui/action/SkipUnitAction.java
@@ -22,6 +22,7 @@ package net.sf.freecol.client.gui.action;
import java.awt.event.ActionEvent;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.common.model.Unit;
/**
@@ -50,7 +51,7 @@ public class SkipUnitAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- igc().skipUnit(getGUI().getActiveUnit());
+ public void actionPerformed(ActionEvent ae) {
+ igc().changeState(getGUI().getActiveUnit(), Unit.UnitState.SKIPPED);
}
}
diff --git a/src/net/sf/freecol/client/gui/action/TilePopupAction.java b/src/net/sf/freecol/client/gui/action/TilePopupAction.java
index c32861155..3a28d9a08 100644
--- a/src/net/sf/freecol/client/gui/action/TilePopupAction.java
+++ b/src/net/sf/freecol/client/gui/action/TilePopupAction.java
@@ -48,7 +48,7 @@ public class TilePopupAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showTilePopUpAtSelectedTile();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ToggleViewModeAction.java b/src/net/sf/freecol/client/gui/action/ToggleViewModeAction.java
index 99483e412..57e0b206d 100644
--- a/src/net/sf/freecol/client/gui/action/ToggleViewModeAction.java
+++ b/src/net/sf/freecol/client/gui/action/ToggleViewModeAction.java
@@ -49,7 +49,7 @@ public class ToggleViewModeAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().toggleViewMode();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/TradeRouteAction.java b/src/net/sf/freecol/client/gui/action/TradeRouteAction.java
index d23436fe4..af186a351 100644
--- a/src/net/sf/freecol/client/gui/action/TradeRouteAction.java
+++ b/src/net/sf/freecol/client/gui/action/TradeRouteAction.java
@@ -48,7 +48,7 @@ public class TradeRouteAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().showTradeRoutePanel(null);
}
}
diff --git a/src/net/sf/freecol/client/gui/action/UnloadAction.java b/src/net/sf/freecol/client/gui/action/UnloadAction.java
index ec4f62e55..8bba506f1 100644
--- a/src/net/sf/freecol/client/gui/action/UnloadAction.java
+++ b/src/net/sf/freecol/client/gui/action/UnloadAction.java
@@ -89,7 +89,7 @@ public class UnloadAction extends MapboardAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
Unit carrier = getUnit();
if (carrier != null) igc().unload(carrier);
}
diff --git a/src/net/sf/freecol/client/gui/action/WaitAction.java b/src/net/sf/freecol/client/gui/action/WaitAction.java
index 8891c73ee..f1f5399e5 100644
--- a/src/net/sf/freecol/client/gui/action/WaitAction.java
+++ b/src/net/sf/freecol/client/gui/action/WaitAction.java
@@ -50,7 +50,7 @@ public class WaitAction extends UnitAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
igc().waitUnit();
}
}
diff --git a/src/net/sf/freecol/client/gui/action/ZoomInAction.java b/src/net/sf/freecol/client/gui/action/ZoomInAction.java
index c25c14723..01f333a0d 100644
--- a/src/net/sf/freecol/client/gui/action/ZoomInAction.java
+++ b/src/net/sf/freecol/client/gui/action/ZoomInAction.java
@@ -63,7 +63,7 @@ public class ZoomInAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().zoomInMap();
update();
getActionManager().getFreeColAction(ZoomOutAction.id).update();
diff --git a/src/net/sf/freecol/client/gui/action/ZoomOutAction.java b/src/net/sf/freecol/client/gui/action/ZoomOutAction.java
index 3b39da004..9fb43ffc7 100644
--- a/src/net/sf/freecol/client/gui/action/ZoomOutAction.java
+++ b/src/net/sf/freecol/client/gui/action/ZoomOutAction.java
@@ -63,7 +63,7 @@ public class ZoomOutAction extends FreeColAction {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().zoomOutMap();
update();
getActionManager().getFreeColAction(ZoomInAction.id).update();
diff --git a/src/net/sf/freecol/client/gui/animation/Animations.java b/src/net/sf/freecol/client/gui/animation/Animations.java
index 87ec64c55..a07680881 100644
--- a/src/net/sf/freecol/client/gui/animation/Animations.java
+++ b/src/net/sf/freecol/client/gui/animation/Animations.java
@@ -19,7 +19,7 @@
package net.sf.freecol.client.gui.animation;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
@@ -32,32 +32,32 @@ public class Animations {
/**
* Animates a unit move.
*
- * @param gui The GUI
to display on.
+ * @param freeColClient The enclosing FreeColClient
.
* @param unit The Unit
to be animated.
* @param source The source Tile
for the unit.
* @param destination The destination Tile
for the unit.
*/
- public static void unitMove(GUI gui, Unit unit,
+ public static void unitMove(FreeColClient freeColClient, Unit unit,
Tile source, Tile destination) {
- new UnitMoveAnimation(gui, unit, source, destination)
+ new UnitMoveAnimation(freeColClient, unit, source, destination)
.animate();
}
/**
* Animates a unit attack.
*
- * @param gui The GUI
to display on.
+ * @param freeColClient The enclosing FreeColClient
.
* @param attacker The Unit
that is attacking.
* @param defender The Unit
that is defending.
* @param attackerTile The Tile
the attack comes from.
* @param defenderTile The Tile
the attack goes to.
* @param success Did the attack succeed?
*/
- public static void unitAttack(GUI gui,
+ public static void unitAttack(FreeColClient freeColClient,
Unit attacker, Unit defender,
Tile attackerTile, Tile defenderTile,
boolean success) {
- new UnitAttackAnimation(gui, attacker, defender,
+ new UnitAttackAnimation(freeColClient, attacker, defender,
attackerTile, defenderTile, success)
.animate();
}
diff --git a/src/net/sf/freecol/client/gui/animation/UnitAttackAnimation.java b/src/net/sf/freecol/client/gui/animation/UnitAttackAnimation.java
index 198d755ce..63ae84504 100644
--- a/src/net/sf/freecol/client/gui/animation/UnitAttackAnimation.java
+++ b/src/net/sf/freecol/client/gui/animation/UnitAttackAnimation.java
@@ -19,7 +19,8 @@
package net.sf.freecol.client.gui.animation;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.io.sza.SimpleZippedAnimation;
import net.sf.freecol.common.model.Direction;
import net.sf.freecol.common.model.Tile;
@@ -32,7 +33,7 @@ import net.sf.freecol.common.resources.ResourceManager;
*/
final class UnitAttackAnimation {
- private final GUI gui;
+ private final FreeColClient freeColClient;
private final Unit attacker;
private final Unit defender;
private final Tile attackerTile;
@@ -43,17 +44,18 @@ final class UnitAttackAnimation {
/**
* Build a new attack animation.
*
- * @param gui The GUI
to display on.
+ * @param freeColClient The enclosing FreeColClient
.
* @param attacker The Unit
that is attacking.
* @param defender The Unit
that is defending.
* @param attackerTile The Tile
the attack comes from.
* @param defenderTile The Tile
the attack goes to.
* @param success Does the attack succeed?
*/
- public UnitAttackAnimation(GUI gui, Unit attacker, Unit defender,
+ public UnitAttackAnimation(FreeColClient freeColClient,
+ Unit attacker, Unit defender,
Tile attackerTile, Tile defenderTile,
boolean success) {
- this.gui = gui;
+ this.freeColClient = freeColClient;
this.attacker = attacker;
this.defender = defender;
this.attackerTile = attackerTile;
@@ -90,7 +92,7 @@ final class UnitAttackAnimation {
*/
private SimpleZippedAnimation getAnimation(Unit unit,
Direction direction) {
- float scale = gui.getMapScale();
+ float scale = ((SwingGUI)freeColClient.getGUI()).getMapScale();
String roleStr = (unit.hasDefaultRole()) ? ""
: "." + unit.getRoleSuffix();
String startStr = "animation.unit." + unit.getType().getId() + roleStr
@@ -129,10 +131,11 @@ final class UnitAttackAnimation {
* Do the animation.
*/
public void animate() {
+ final SwingGUI gui = (SwingGUI)freeColClient.getGUI();
Direction direction = attackerTile.getDirection(defenderTile);
SimpleZippedAnimation sza;
- if (gui.getAnimationSpeed(attacker) > 0) {
+ if (freeColClient.getAnimationSpeed(attacker.getOwner()) > 0) {
if ((sza = getAnimation(attacker, direction)) != null) {
new UnitImageAnimation(gui, attacker, attackerTile, sza, mirror)
.animate();
@@ -140,7 +143,7 @@ final class UnitAttackAnimation {
}
if (!success
- && gui.getAnimationSpeed(defender) > 0) {
+ && freeColClient.getAnimationSpeed(defender.getOwner()) > 0) {
direction = direction.getReverseDirection();
if ((sza = getAnimation(defender, direction)) != null) {
new UnitImageAnimation(gui, defender, defenderTile, sza, mirror)
diff --git a/src/net/sf/freecol/client/gui/animation/UnitImageAnimation.java b/src/net/sf/freecol/client/gui/animation/UnitImageAnimation.java
index 717e2922f..41e84c5c7 100644
--- a/src/net/sf/freecol/client/gui/animation/UnitImageAnimation.java
+++ b/src/net/sf/freecol/client/gui/animation/UnitImageAnimation.java
@@ -25,9 +25,8 @@ import java.awt.Rectangle;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
-import net.sf.freecol.client.gui.OutForAnimationCallback;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.io.sza.AnimationEvent;
import net.sf.freecol.common.io.sza.ImageAnimationEvent;
import net.sf.freecol.common.io.sza.SimpleZippedAnimation;
@@ -40,7 +39,7 @@ import net.sf.freecol.common.model.Unit;
*/
public final class UnitImageAnimation {
- private final GUI gui;
+ private final SwingGUI gui;
private final Unit unit;
private final Tile tile;
private final SimpleZippedAnimation animation;
@@ -49,11 +48,12 @@ public final class UnitImageAnimation {
/**
* Constructor
*
+ * @param gui The gui.
* @param unit The Unit
to be animated.
* @param tile The Tile
where the animation occurs.
* @param animation The animation to show.
*/
- public UnitImageAnimation(GUI gui, Unit unit, Tile tile,
+ public UnitImageAnimation(SwingGUI gui, Unit unit, Tile tile,
SimpleZippedAnimation animation, boolean mirror) {
this.gui = gui;
this.unit = unit;
@@ -70,9 +70,7 @@ public final class UnitImageAnimation {
// Painting the whole screen once to get rid of disposed dialog-boxes.
gui.paintImmediatelyCanvasInItsBounds();
- gui.executeWithUnitOutForAnimation(unit, tile, new OutForAnimationCallback() {
- @Override
- public void executeWithUnitOutForAnimation(final JLabel unitLabel) {
+ gui.executeWithUnitOutForAnimation(unit, tile, (JLabel unitLabel) -> {
for (AnimationEvent event : animation) {
long time = System.nanoTime();
if (event instanceof ImageAnimationEvent) {
@@ -85,7 +83,7 @@ public final class UnitImageAnimation {
}
icon.setImage(image);
gui.paintImmediatelyCanvasIn(getDirtyAnimationArea());
-
+
time = ievent.getDurationInMs()
- (System.nanoTime() - time) / 1000000;
if (time > 0) {
@@ -96,9 +94,8 @@ public final class UnitImageAnimation {
}
}
}
- }
- }
- });
+ }
+ });
}
protected Rectangle getDirtyAnimationArea() {
diff --git a/src/net/sf/freecol/client/gui/animation/UnitMoveAnimation.java b/src/net/sf/freecol/client/gui/animation/UnitMoveAnimation.java
index 28e950934..39682d9ff 100644
--- a/src/net/sf/freecol/client/gui/animation/UnitMoveAnimation.java
+++ b/src/net/sf/freecol/client/gui/animation/UnitMoveAnimation.java
@@ -24,8 +24,9 @@ import java.awt.Rectangle;
import javax.swing.JLabel;
-import net.sf.freecol.client.gui.GUI;
-import net.sf.freecol.client.gui.OutForAnimationCallback;
+import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
@@ -41,23 +42,22 @@ final class UnitMoveAnimation {
*/
private static final int ANIMATION_DELAY = 33;
+ private final FreeColClient freeColClient;
private final Unit unit;
private final Tile sourceTile;
private final Tile destinationTile;
- private final GUI gui;
-
/**
* Constructor
*
- * @param gui The GUI
to display on.
+ * @param freeColClient The enclosing FreeColClient
.
* @param unit The Unit
to be animated.
* @param sourceTile The Tile
the unit is moving from.
* @param destinationTile The Tile
the unit is moving to.
*/
- public UnitMoveAnimation(GUI gui, Unit unit,
+ public UnitMoveAnimation(FreeColClient freeColClient, Unit unit,
Tile sourceTile, Tile destinationTile) {
- this.gui = gui;
+ this.freeColClient = freeColClient;
this.unit = unit;
this.sourceTile = sourceTile;
this.destinationTile = destinationTile;
@@ -68,7 +68,9 @@ final class UnitMoveAnimation {
* Do the animation.
*/
public void animate() {
- final int movementSpeed = gui.getAnimationSpeed(unit);
+ final int movementSpeed
+ = freeColClient.getAnimationSpeed(unit.getOwner());
+ final SwingGUI gui = (SwingGUI)freeColClient.getGUI();
final Point srcP = gui.getTilePosition(sourceTile);
final Point dstP = gui.getTilePosition(destinationTile);
@@ -81,58 +83,55 @@ final class UnitMoveAnimation {
final Rectangle bounds = r1.union(r2);
gui.executeWithUnitOutForAnimation(unit, sourceTile,
- new OutForAnimationCallback() {
- @Override
- public void executeWithUnitOutForAnimation(final JLabel unitLabel) {
- final Point srcPoint
- = gui.calculateUnitLabelPositionInTile(unitLabel, srcP);
- final Point dstPoint
- = gui.calculateUnitLabelPositionInTile(unitLabel, dstP);
- final double xratio = gui.getTileWidthHeightRatio();
- final int stepX = (srcPoint.getX() == dstPoint.getX()) ? 0
- : (srcPoint.getX() > dstPoint.getX()) ? -1 : 1;
- final int stepY = (srcPoint.getY() == dstPoint.getY()) ? 0
- : (srcPoint.getY() > dstPoint.getY()) ? -1 : 1;
-
- // Painting the whole screen once to get rid of
- // disposed dialog-boxes.
- gui.paintImmediatelyCanvasInItsBounds();
-
- int dropFrames = 0;
- Point point = srcPoint;
- while (!point.equals(dstPoint)) {
- long time = System.currentTimeMillis();
-
- point.x += stepX * xratio * movementRatio;
- point.y += stepY * movementRatio;
- if ((stepX < 0 && point.x < dstPoint.x)
- || (stepX > 0 && point.x > dstPoint.x)) {
- point.x = dstPoint.x;
- }
- if ((stepY < 0 && point.y < dstPoint.y)
- || (stepY > 0 && point.y > dstPoint.y)) {
- point.y = dstPoint.y;
- }
- if (dropFrames <= 0) {
- unitLabel.setLocation(point);
- gui.paintImmediatelyCanvasIn(bounds);
+ (JLabel unitLabel) -> {
+ final int labelWidth = unitLabel.getWidth();
+ final int labelHeight = unitLabel.getHeight();
+ final Point srcPoint = gui.calculateUnitLabelPositionInTile(labelWidth, labelHeight, srcP);
+ final Point dstPoint = gui.calculateUnitLabelPositionInTile(labelWidth, labelHeight, dstP);
+ final double xratio = ImageLibrary.TILE_SIZE.width
+ / (double)ImageLibrary.TILE_SIZE.height;
+ final int stepX = (srcPoint.getX() == dstPoint.getX()) ? 0
+ : (srcPoint.getX() > dstPoint.getX()) ? -1 : 1;
+ final int stepY = (srcPoint.getY() == dstPoint.getY()) ? 0
+ : (srcPoint.getY() > dstPoint.getY()) ? -1 : 1;
+
+ // Painting the whole screen once to get rid of
+ // disposed dialog-boxes.
+ gui.paintImmediatelyCanvasInItsBounds();
+
+ int dropFrames = 0;
+ Point point = srcPoint;
+ while (!point.equals(dstPoint)) {
+ long time = System.currentTimeMillis();
+
+ point.x += stepX * xratio * movementRatio;
+ point.y += stepY * movementRatio;
+ if ((stepX < 0 && point.x < dstPoint.x)
+ || (stepX > 0 && point.x > dstPoint.x)) {
+ point.x = dstPoint.x;
+ }
+ if ((stepY < 0 && point.y < dstPoint.y)
+ || (stepY > 0 && point.y > dstPoint.y)) {
+ point.y = dstPoint.y;
+ }
+ if (dropFrames <= 0) {
+ unitLabel.setLocation(point);
+ gui.paintImmediatelyCanvasIn(bounds);
- int timeTaken = (int)(System.currentTimeMillis()
- - time);
- final int waitTime = ANIMATION_DELAY - timeTaken;
- if (waitTime > 0) {
- try {
- Thread.sleep(waitTime);
- } catch (InterruptedException ex) {
- //ignore
- }
- dropFrames = 0;
- } else {
- dropFrames = timeTaken / ANIMATION_DELAY - 1;
+ int timeTaken = (int)(System.currentTimeMillis() - time);
+ final int waitTime = ANIMATION_DELAY - timeTaken;
+ if (waitTime > 0) {
+ try {
+ Thread.sleep(waitTime);
+ } catch (InterruptedException ex) {
+ //ignore
}
+ dropFrames = 0;
} else {
- dropFrames--;
+ dropFrames = timeTaken / ANIMATION_DELAY - 1;
}
+ } else {
+ dropFrames--;
}
}
});
diff --git a/src/net/sf/freecol/client/gui/menu/DebugMenu.java b/src/net/sf/freecol/client/gui/menu/DebugMenu.java
index d3d63aab3..a891c19dd 100644
--- a/src/net/sf/freecol/client/gui/menu/DebugMenu.java
+++ b/src/net/sf/freecol/client/gui/menu/DebugMenu.java
@@ -21,12 +21,8 @@ package net.sf.freecol.client.gui.menu;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
@@ -50,6 +46,7 @@ import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.resources.ImageResource;
import net.sf.freecol.common.resources.ResourceManager;
+
import static net.sf.freecol.common.util.CollectionUtils.*;
@@ -100,43 +97,34 @@ public class DebugMenu extends JMenu {
sc.setOpaque(false);
sc.setMnemonic(KeyEvent.VK_S);
this.add(sc);
- sc.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- boolean val = ((JCheckBoxMenuItem)e.getSource()).isSelected();
- FreeColDebugger.setDebugDisplayCoordinates(val);
- gui.refresh();
- }
+ sc.addActionListener((ActionEvent ae) -> {
+ boolean val = ((JCheckBoxMenuItem)ae.getSource()).isSelected();
+ FreeColDebugger.setDebugDisplayCoordinates(val);
+ gui.refresh();
});
sc.setEnabled(true);
final JMenuItem reveal
= Utility.localizedCheckBoxMenuItem("menuBar.debug.revealEntireMap",
- false);
+ false);
reveal.setOpaque(false);
reveal.setMnemonic(KeyEvent.VK_R);
this.add(reveal);
- reveal.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.revealMap(freeColClient, true);
- reveal.setEnabled(false);
- }
+ reveal.addActionListener((ActionEvent ae) -> {
+ DebugUtils.revealMap(freeColClient, true);
+ reveal.setEnabled(false);
});
reveal.setEnabled(hasServer);
final JMenuItem hide
= Utility.localizedCheckBoxMenuItem("menuBar.debug.hideEntireMap",
- false);
+ false);
hide.setOpaque(false);
//hide.setMnemonic(KeyEvent.VK_R);
this.add(hide);
- hide.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.revealMap(freeColClient, false);
- hide.setEnabled(false);
- }
+ hide.addActionListener((ActionEvent ae) -> {
+ DebugUtils.revealMap(freeColClient, false);
+ hide.setEnabled(false);
});
hide.setEnabled(hasServer);
@@ -146,12 +134,9 @@ public class DebugMenu extends JMenu {
game.getMap().getSearchTrace());
searchTrace.setOpaque(false);
this.add(searchTrace);
- searchTrace.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- boolean val = ((JCheckBoxMenuItem)e.getSource()).isSelected();
- game.getMap().setSearchTrace(val);
- }
+ searchTrace.addActionListener((ActionEvent ae) -> {
+ boolean val = ((JCheckBoxMenuItem)ae.getSource()).isSelected();
+ game.getMap().setSearchTrace(val);
});
final JMenu cvpMenu
@@ -165,30 +150,24 @@ public class DebugMenu extends JMenu {
cv1.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv1);
bg.add(cv1);
- cv1.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- FreeColDebugger.setDebugDisplayColonyValuePlayer(null);
- gui.refresh();
- }
+ cv1.addActionListener((ActionEvent ae) -> {
+ FreeColDebugger.setDebugDisplayColonyValuePlayer(null);
+ gui.refresh();
});
this.add(cvpMenu);
cvpMenu.addSeparator();
for (Player p : game.getLiveEuropeanPlayers(null)) {
final JRadioButtonMenuItem cv2
- = Utility.localizedRadioButtonMenuItem(p.getNationName(),
+ = Utility.localizedRadioButtonMenuItem(p.getCountryLabel(),
FreeColDebugger.debugDisplayColonyValuePlayer() == p);
cv2.setOpaque(false);
//cv2.setMnemonic(KeyEvent.VK_C);
cvpMenu.add(cv2);
bg.add(cv2);
final Player fp = p;
- cv2.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- FreeColDebugger.setDebugDisplayColonyValuePlayer(fp);
- gui.refresh();
- }
+ cv2.addActionListener((ActionEvent ae) -> {
+ FreeColDebugger.setDebugDisplayColonyValuePlayer(fp);
+ gui.refresh();
});
}
@@ -198,11 +177,8 @@ public class DebugMenu extends JMenu {
skipTurns.setOpaque(false);
skipTurns.setMnemonic(KeyEvent.VK_T);
this.add(skipTurns);
- skipTurns.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.skipTurns(freeColClient);
- }
+ skipTurns.addActionListener((ActionEvent ae) -> {
+ DebugUtils.skipTurns(freeColClient);
});
DebugUtils.addSkipChangeListener(freeColClient, this, skipTurns);
skipTurns.setEnabled(hasServer);
@@ -211,11 +187,8 @@ public class DebugMenu extends JMenu {
addBuilding.setOpaque(false);
addBuilding.setMnemonic(KeyEvent.VK_B);
this.add(addBuilding);
- addBuilding.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.addBuildings(freeColClient, addBuilding.getText());
- }
+ addBuilding.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addBuildings(freeColClient, addBuilding.getText());
});
addBuilding.setEnabled(hasServer);
@@ -223,11 +196,8 @@ public class DebugMenu extends JMenu {
addFather.setOpaque(false);
addFather.setMnemonic(KeyEvent.VK_F);
this.add(addFather);
- addFather.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.addFathers(freeColClient, addFather.getText());
- }
+ addFather.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addFathers(freeColClient, addFather.getText());
});
addFather.setEnabled(hasServer);
@@ -235,11 +205,8 @@ public class DebugMenu extends JMenu {
runMonarch.setOpaque(false);
runMonarch.setMnemonic(KeyEvent.VK_M);
this.add(runMonarch);
- runMonarch.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.setMonarchAction(freeColClient, runMonarch.getText());
- }
+ runMonarch.addActionListener((ActionEvent ae) -> {
+ DebugUtils.setMonarchAction(freeColClient, runMonarch.getText());
});
runMonarch.setEnabled(hasServer);
@@ -247,11 +214,8 @@ public class DebugMenu extends JMenu {
addGold.setOpaque(false);
addGold.setMnemonic(KeyEvent.VK_G);
this.add(addGold);
- addGold.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.addGold(freeColClient);
- }
+ addGold.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addGold(freeColClient);
});
addGold.setEnabled(hasServer);
@@ -259,11 +223,8 @@ public class DebugMenu extends JMenu {
addCrosses.setOpaque(false);
addCrosses.setMnemonic(KeyEvent.VK_I);
this.add(addCrosses);
- addCrosses.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.addImmigration(freeColClient);
- }
+ addCrosses.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addImmigration(freeColClient);
});
addCrosses.setEnabled(hasServer);
@@ -271,11 +232,8 @@ public class DebugMenu extends JMenu {
giveBells.setOpaque(false);
giveBells.setMnemonic(KeyEvent.VK_L);
this.add(giveBells);
- giveBells.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.addLiberty(freeColClient);
- }
+ giveBells.addActionListener((ActionEvent ae) -> {
+ DebugUtils.addLiberty(freeColClient);
});
giveBells.setEnabled(hasServer);
@@ -284,11 +242,8 @@ public class DebugMenu extends JMenu {
rng.setOpaque(false);
rng.setMnemonic(KeyEvent.VK_X);
this.add(rng);
- rng.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.stepRNG(freeColClient);
- }
+ rng.addActionListener((ActionEvent ae) -> {
+ DebugUtils.stepRNG(freeColClient);
});
rng.setEnabled(hasServer);
@@ -296,11 +251,8 @@ public class DebugMenu extends JMenu {
final JMenuItem du = Utility.localizedMenuItem("menuBar.debug.displayUnits");
du.setOpaque(false);
this.add(du);
- du.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.displayUnits(freeColClient);
- }
+ du.addActionListener((ActionEvent ae) -> {
+ DebugUtils.displayUnits(freeColClient);
});
du.setEnabled(true);
@@ -310,21 +262,17 @@ public class DebugMenu extends JMenu {
panelMenu.setOpaque(false);
final JMenuItem monarchDialog = Utility.localizedMenuItem("menuBar.debug.displayMonarchPanel");
- monarchDialog.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- gui.showMonarchDialog(Monarch.MonarchAction.RAISE_TAX_WAR,
- null, player.getMonarchKey());
- }
+ monarchDialog.addActionListener((ActionEvent ae) -> {
+ gui.showMonarchDialog(
+ Monarch.MonarchAction.RAISE_TAX_WAR, null, player.getMonarchKey(),
+ (Boolean b) ->
+ freeColClient.getInGameController().monarchAction(Monarch.MonarchAction.RAISE_TAX_WAR, b));
});
panelMenu.add(monarchDialog);
final JMenuItem errorMessage = Utility.localizedMenuItem("menuBar.debug.displayErrorMessage");
- errorMessage.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- gui.showErrorMessage(ERROR_MESSAGE);
- }
+ errorMessage.addActionListener((ActionEvent ae) -> {
+ gui.showErrorMessage(ERROR_MESSAGE);
});
panelMenu.add(errorMessage);
@@ -334,11 +282,8 @@ public class DebugMenu extends JMenu {
europeStatus.setOpaque(false);
europeStatus.setMnemonic(KeyEvent.VK_E);
this.add(europeStatus);
- europeStatus.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.displayEurope(freeColClient);
- }
+ europeStatus.addActionListener((ActionEvent ae) -> {
+ DebugUtils.displayEurope(freeColClient);
});
europeStatus.setEnabled(hasServer);
@@ -351,14 +296,11 @@ public class DebugMenu extends JMenu {
dam.setOpaque(false);
dam.setMnemonic(KeyEvent.VK_A);
this.add(dam);
- dam.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- boolean val = ((JCheckBoxMenuItem) e.getSource()).isSelected();
- FreeColDebugger.setDebugShowMission(val);
- dami.setEnabled(val);
- gui.refresh();
- }
+ dam.addActionListener((ActionEvent ae) -> {
+ boolean val = ((JCheckBoxMenuItem)ae.getSource()).isSelected();
+ FreeColDebugger.setDebugShowMission(val);
+ dami.setEnabled(val);
+ gui.refresh();
});
dam.setEnabled(true);
@@ -369,25 +311,19 @@ public class DebugMenu extends JMenu {
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(useAI);
- useAI.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.useAI(freeColClient);
- }
+ useAI.addActionListener((ActionEvent ae) -> {
+ DebugUtils.useAI(freeColClient);
});
useAI.setEnabled(hasServer);
dami.setOpaque(false);
dami.setMnemonic(KeyEvent.VK_I);
this.add(dami);
- dami.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- boolean val = ((JCheckBoxMenuItem) e.getSource()).isSelected();
- FreeColDebugger.setDebugShowMissionInfo(val);
- dami.setEnabled(val);
- gui.refresh();
- }
+ dami.addActionListener((ActionEvent ae) -> {
+ boolean val = ((JCheckBoxMenuItem)ae.getSource()).isSelected();
+ FreeColDebugger.setDebugShowMissionInfo(val);
+ dami.setEnabled(val);
+ gui.refresh();
});
dami.setEnabled(FreeColDebugger.debugShowMissionInfo());
@@ -400,11 +336,8 @@ public class DebugMenu extends JMenu {
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
| InputEvent.ALT_MASK));
this.add(compareMaps);
- compareMaps.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- DebugUtils.checkDesyncAction(freeColClient);
- }
+ compareMaps.addActionListener((ActionEvent ae) -> {
+ DebugUtils.checkDesyncAction(freeColClient);
});
compareMaps.setEnabled(hasServer);
@@ -412,22 +345,19 @@ public class DebugMenu extends JMenu {
showResourceKeys.setOpaque(false);
//showResourceKeys.setMnemonic(KeyEvent.VK_R);
this.add(showResourceKeys);
- showResourceKeys.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- StringBuilder builder = new StringBuilder();
- Map resources
- = ResourceManager.getImageResources();
- for (Entry en
- : mapEntriesByKey(resources)) {
- builder.append(en.getKey());
- builder.append(" (");
- builder.append(en.getValue().getCount());
- builder.append(")");
- builder.append("\n");
- }
- gui.showInformationMessage(builder.toString());
+ showResourceKeys.addActionListener((ActionEvent ae) -> {
+ StringBuilder builder = new StringBuilder();
+ Map resources
+ = ResourceManager.getImageResources();
+ for (Entry en
+ : mapEntriesByKey(resources)) {
+ builder.append(en.getKey());
+ builder.append(" (");
+ builder.append(en.getValue().getCount());
+ builder.append(")");
+ builder.append("\n");
}
+ gui.showInformationMessage(builder.toString());
});
showResourceKeys.setEnabled(true);
@@ -436,11 +366,8 @@ public class DebugMenu extends JMenu {
statistics.setOpaque(false);
//statistics.setMnemonic(KeyEvent.VK_I);
this.add(statistics);
- statistics.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- gui.showStatisticsPanel();
- }
+ statistics.addActionListener((ActionEvent ae) -> {
+ gui.showStatisticsPanel();
});
statistics.setEnabled(true);
@@ -449,11 +376,8 @@ public class DebugMenu extends JMenu {
gc.setOpaque(false);
//gc.setMnemonic(KeyEvent.VK_G);
this.add(gc);
- gc.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- System.gc();
- }
+ gc.addActionListener((ActionEvent ae) -> {
+ System.gc();
});
gc.setEnabled(true);
diff --git a/src/net/sf/freecol/client/gui/menu/FreeColMenuTest.java b/src/net/sf/freecol/client/gui/menu/FreeColMenuTest.java
index 6e065fe0b..0e73821fa 100644
--- a/src/net/sf/freecol/client/gui/menu/FreeColMenuTest.java
+++ b/src/net/sf/freecol/client/gui/menu/FreeColMenuTest.java
@@ -79,8 +79,8 @@ public class FreeColMenuTest implements ActionListener, ItemListener {
}
@Override
- public void actionPerformed(ActionEvent e) {
- JMenuItem source = (JMenuItem)(e.getSource());
+ public void actionPerformed(ActionEvent ae) {
+ JMenuItem source = (JMenuItem)ae.getSource();
String s = "Action event detected."
+ newline
+ " Event source: " + source.getText()
@@ -154,11 +154,6 @@ public class FreeColMenuTest implements ActionListener, ItemListener {
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- createAndShowGUI();
- }
- });
+ javax.swing.SwingUtilities.invokeLater(() -> { createAndShowGUI(); });
}
}
diff --git a/src/net/sf/freecol/client/gui/menu/InGameMenuBar.java b/src/net/sf/freecol/client/gui/menu/InGameMenuBar.java
index 2ef09b563..8faaf69fb 100644
--- a/src/net/sf/freecol/client/gui/menu/InGameMenuBar.java
+++ b/src/net/sf/freecol/client/gui/menu/InGameMenuBar.java
@@ -23,6 +23,7 @@ import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
+import java.awt.event.MouseMotionListener;
import java.awt.geom.Rectangle2D;
import java.util.logging.Logger;
@@ -30,10 +31,8 @@ import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.MapViewer;
import net.sf.freecol.client.gui.action.*;
import net.sf.freecol.client.gui.action.DisplayTileTextAction.DisplayText;
-import net.sf.freecol.client.gui.menu.DebugMenu;
import net.sf.freecol.client.gui.panel.Utility;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
@@ -61,9 +60,10 @@ public class InGameMenuBar extends FreeColMenuBar {
* Creates a new FreeColMenuBar
. This menu bar will include
* all of the submenus and items.
*
- * @param f The main controller.
+ * @param freeColClient The main controller.
+ * @param listener An optional mouse motion listener.
*/
- public InGameMenuBar(FreeColClient f, MapViewer mapViewer) {
+ public InGameMenuBar(FreeColClient freeColClient, MouseMotionListener listener) {
// FIXME: FreeColClient should not have to be passed in to
// this class. This is only a menu bar, it doesn't need a
// reference to the main controller. The only reason it has
@@ -79,11 +79,11 @@ public class InGameMenuBar extends FreeColMenuBar {
// Okay, I lied.. the update() and paintComponent() methods in
// this MenuBar use freeColClient, too. But so what. Move
// those to another class too. :)
- super(f);
+ super(freeColClient);
// Add a mouse listener so that autoscrolling can happen in
// this menubar
- this.addMouseMotionListener(new MenuMouseMotionListener(f, mapViewer));
+ this.addMouseMotionListener(listener);
reset();
}
@@ -277,7 +277,7 @@ public class InGameMenuBar extends FreeColMenuBar {
freeColClient.getGame().getTurn().getLabel()));
Rectangle2D displayStringBounds
= g2d.getFontMetrics().getStringBounds(displayString, g);
- int y = Math.round(12f*freeColClient.getGUI().getImageLibrary().getScalingFactor())
+ int y = Math.round(12f*freeColClient.getGUI().getImageLibrary().getScaleFactor())
+ 3 + getInsets().top;
g2d.drawString(displayString, getWidth() - 10 - (int) displayStringBounds.getWidth(), y);
}
diff --git a/src/net/sf/freecol/client/gui/menu/MapEditorMenuBar.java b/src/net/sf/freecol/client/gui/menu/MapEditorMenuBar.java
index 70c7395e2..153c7543f 100644
--- a/src/net/sf/freecol/client/gui/menu/MapEditorMenuBar.java
+++ b/src/net/sf/freecol/client/gui/menu/MapEditorMenuBar.java
@@ -20,8 +20,8 @@
package net.sf.freecol.client.gui.menu;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
+import java.awt.event.MouseMotionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.logging.Logger;
@@ -31,7 +31,6 @@ import javax.swing.JMenu;
import javax.swing.JMenuItem;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.MapViewer;
import net.sf.freecol.client.gui.action.*;
import net.sf.freecol.client.gui.action.DisplayTileTextAction.DisplayText;
import net.sf.freecol.client.gui.panel.Utility;
@@ -62,12 +61,13 @@ public class MapEditorMenuBar extends FreeColMenuBar {
* all of the submenus and items.
*
* @param freeColClient The FreeColClient
for the game.
+ * @param listener An optional mouse motion listener.
*/
- public MapEditorMenuBar(final FreeColClient freeColClient, MapViewer mapViewer) {
+ public MapEditorMenuBar(final FreeColClient freeColClient, MouseMotionListener listener) {
super(freeColClient);
// Add a mouse listener so that autoscrolling can happen in this menubar
- this.addMouseMotionListener(new MenuMouseMotionListener(freeColClient, mapViewer));
+ this.addMouseMotionListener(listener);
reset();
}
@@ -101,24 +101,20 @@ public class MapEditorMenuBar extends FreeColMenuBar {
menu.add(getMenuItem(OpenAction.id));
menu.add(getMenuItem(SaveAction.id));
JMenuItem playItem = Utility.localizedMenuItem("startGame");
- playItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- File startFile = FreeColDirectories.getStartMapFile();
- freeColClient.getMapEditorController()
- .saveGame(startFile);
- OptionGroup options = freeColClient.getGame()
- .getMapGeneratorOptions();
- FileOption fileOption = (FileOption)options
- .getOption(MapGeneratorOptions.IMPORT_FILE);
- fileOption.setValue(startFile);
- File mapOptionsFile = FreeColDirectories
- .getOptionsFile(FreeColDirectories.MAP_GENERATOR_OPTIONS_FILE_NAME);
- try {
- options.save(mapOptionsFile);
- } catch (FileNotFoundException fnfe) {}
- freeColClient.newGame();
- }
+ playItem.addActionListener((ActionEvent ae) -> {
+ File startFile = FreeColDirectories.getStartMapFile();
+ freeColClient.getMapEditorController().saveGame(startFile);
+ OptionGroup options = freeColClient.getGame()
+ .getMapGeneratorOptions();
+ FileOption fileOption = (FileOption)options
+ .getOption(MapGeneratorOptions.IMPORT_FILE);
+ fileOption.setValue(startFile);
+ File mapOptionsFile = FreeColDirectories
+ .getOptionsFile(FreeColDirectories.MAP_GENERATOR_OPTIONS_FILE_NAME);
+ try {
+ options.save(mapOptionsFile);
+ } catch (FileNotFoundException fnfe) {}
+ freeColClient.newGame(true);
});
menu.add(playItem);
menu.addSeparator();
diff --git a/src/net/sf/freecol/client/gui/menu/MenuMouseMotionListener.java b/src/net/sf/freecol/client/gui/menu/MenuMouseMotionListener.java
index 1e7df06dd..d94a40b6b 100644
--- a/src/net/sf/freecol/client/gui/menu/MenuMouseMotionListener.java
+++ b/src/net/sf/freecol/client/gui/menu/MenuMouseMotionListener.java
@@ -24,7 +24,7 @@ import java.awt.event.MouseMotionListener;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.AbstractCanvasListener;
-import net.sf.freecol.client.gui.MapViewer;
+import net.sf.freecol.client.gui.Canvas;
/**
@@ -47,8 +47,8 @@ public class MenuMouseMotionListener extends AbstractCanvasListener
*
* @param freeColClient The enclosing FreeColClient
.
*/
- public MenuMouseMotionListener(FreeColClient freeColClient, MapViewer mapViewer) {
- super(freeColClient, mapViewer);
+ public MenuMouseMotionListener(FreeColClient freeColClient, Canvas canvas) {
+ super(freeColClient, canvas);
}
@@ -57,7 +57,7 @@ public class MenuMouseMotionListener extends AbstractCanvasListener
*/
@Override
public void mouseDragged(MouseEvent e) {
- return; //Do nothing
+ //Do nothing
}
/**
diff --git a/src/net/sf/freecol/client/gui/option/AudioMixerOptionUI.java b/src/net/sf/freecol/client/gui/option/AudioMixerOptionUI.java
index f342428de..550d3e651 100644
--- a/src/net/sf/freecol/client/gui/option/AudioMixerOptionUI.java
+++ b/src/net/sf/freecol/client/gui/option/AudioMixerOptionUI.java
@@ -49,23 +49,6 @@ public final class AudioMixerOptionUI extends OptionUI {
private final JButton button2;
private final JLabel currentMixerLabel;
- private final ActionListener aHandler = new ActionListener () {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (e.getSource() == button1) {
- gui.playSound("sound.event.buildingComplete");
- } else if (e.getSource() == button2) {
- gui.playSound("sound.intro.general");
- } else if (e.getSource() == cbox) {
- MixerWrapper value = (MixerWrapper) cbox.getSelectedItem();
- if (getOption().getValue() != value) {
- getOption().setValue(value);
- updateMixerLabel();
- }
- }
- }
- };
-
/**
* Creates a new AudioMixerOptionUI
for the given
@@ -95,18 +78,31 @@ public final class AudioMixerOptionUI extends OptionUI {
button1 = Utility.localizedButton("test");
panel.add(button1);
- button1.addActionListener(aHandler);
button2 = Utility.localizedButton("music");
panel.add(button2);
- button2.addActionListener(aHandler);
cbox.add(super.getJLabel());
cbox.setModel(new DefaultComboBoxModel<>(getOption().getChoices()
.toArray(new MixerWrapper[0])));
reset();
-
cbox.setEnabled(editable);
+
+ ActionListener aHandler = (ActionEvent ae) -> {
+ if (ae.getSource() == button1) {
+ gui.playSound("sound.event.buildingComplete");
+ } else if (ae.getSource() == button2) {
+ gui.playSound("sound.intro.general");
+ } else if (ae.getSource() == cbox) {
+ MixerWrapper value = (MixerWrapper) cbox.getSelectedItem();
+ if (getOption().getValue() != value) {
+ getOption().setValue(value);
+ updateMixerLabel();
+ }
+ }
+ };
+ button1.addActionListener(aHandler);
+ button2.addActionListener(aHandler);
cbox.addActionListener(aHandler);
initialize();
diff --git a/src/net/sf/freecol/client/gui/option/FileOptionUI.java b/src/net/sf/freecol/client/gui/option/FileOptionUI.java
index 195a87424..3c018d196 100644
--- a/src/net/sf/freecol/client/gui/option/FileOptionUI.java
+++ b/src/net/sf/freecol/client/gui/option/FileOptionUI.java
@@ -20,7 +20,6 @@
package net.sf.freecol.client.gui.option;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.awt.Color;
import java.io.File;
@@ -63,23 +62,17 @@ public final class FileOptionUI extends OptionUI {
JButton browse = Utility.localizedButton("browse");
if (editable) {
- browse.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- File file = gui.showLoadSaveFileDialog();
- if (file != null) setValue(file);
- }
+ browse.addActionListener((ActionEvent ae) -> {
+ File f = gui.showLoadSaveFileDialog();
+ if (f != null) setValue(f);
});
}
panel.add(browse);
JButton remove = Utility.localizedButton("remove");
if (editable) {
- remove.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- setValue(null);
- }
+ remove.addActionListener((ActionEvent ae) -> {
+ setValue(null);
});
}
panel.add(remove);
diff --git a/src/net/sf/freecol/client/gui/option/FreeColActionUI.java b/src/net/sf/freecol/client/gui/option/FreeColActionUI.java
index b8eff5c79..43db00be3 100644
--- a/src/net/sf/freecol/client/gui/option/FreeColActionUI.java
+++ b/src/net/sf/freecol/client/gui/option/FreeColActionUI.java
@@ -168,11 +168,11 @@ public final class FreeColActionUI extends OptionUI
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent evt) {
- if (evt.getSource() == recordButton) {
+ public void actionPerformed(ActionEvent ae) {
+ if (ae.getSource() == recordButton) {
bl.startBlinking();
bl.requestFocus();
- } else if (evt.getSource() == removeButton) {
+ } else if (ae.getSource() == removeButton) {
bl.stopBlinking();
bl.setText(" ");
keyStroke = null;
@@ -264,7 +264,7 @@ public final class FreeColActionUI extends OptionUI
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
if (!hasFocus()) stopBlinking();
if (blinkOn) {
diff --git a/src/net/sf/freecol/client/gui/option/ListOptionUI.java b/src/net/sf/freecol/client/gui/option/ListOptionUI.java
index ff1157f50..247327d72 100644
--- a/src/net/sf/freecol/client/gui/option/ListOptionUI.java
+++ b/src/net/sf/freecol/client/gui/option/ListOptionUI.java
@@ -20,7 +20,6 @@
package net.sf.freecol.client.gui.option;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
@@ -110,66 +109,49 @@ public final class ListOptionUI extends OptionUI>
this.panel.add(button);
}
- addButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- AbstractOption oldValue
- = list.getSelectedValue();
- if (oldValue == null) oldValue = option.getTemplate();
- try {
- AbstractOption newValue = (oldValue == null) ? null
- : oldValue.clone();
- if (gui.showEditOptionDialog(newValue)) {
- if (option.canAdd(newValue)) {
- model.addElement(newValue);
- list.setSelectedValue(newValue, true);
- list.repaint();
- }
- }
- } catch (CloneNotSupportedException e) {
- logger.log(Level.WARNING, "Can not clone: " + oldValue,
- e);
- }
- }
- });
- editButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- Object object = list.getSelectedValue();
- if (object != null) {
- if (gui.showEditOptionDialog((Option)object)) {
+ addButton.addActionListener((ActionEvent ae) -> {
+ AbstractOption oldValue = list.getSelectedValue();
+ if (oldValue == null) oldValue = option.getTemplate();
+ try {
+ AbstractOption newValue = (oldValue == null) ? null
+ : oldValue.clone();
+ if (gui.showEditOptionDialog(newValue)) {
+ if (option.canAdd(newValue)) {
+ model.addElement(newValue);
+ list.setSelectedValue(newValue, true);
list.repaint();
}
}
+ } catch (CloneNotSupportedException e) {
+ logger.log(Level.WARNING, "Can not clone: " + oldValue, e);
}
});
- removeButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- model.removeElementAt(list.getSelectedIndex());
+ editButton.addActionListener((ActionEvent ae) -> {
+ Object object = list.getSelectedValue();
+ if (object != null) {
+ if (gui.showEditOptionDialog((Option)object)) {
+ list.repaint();
+ }
}
});
- upButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (list.getSelectedIndex() == 0) return;
- final int index = list.getSelectedIndex();
- final AbstractOption temp = model.getElementAt(index);
- model.setElementAt(model.getElementAt(index-1), index);
- model.setElementAt(temp, index-1);
- list.setSelectedIndex(index-1);
- }
+ removeButton.addActionListener((ActionEvent ae) -> {
+ model.removeElementAt(list.getSelectedIndex());
});
- downButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (list.getSelectedIndex() == model.getSize() - 1) return;
- final int index = list.getSelectedIndex();
- final AbstractOption temp = model.getElementAt(index);
- model.setElementAt(model.getElementAt(index+1), index);
- model.setElementAt(temp, index+1);
- list.setSelectedIndex(index+1);
- }
+ upButton.addActionListener((ActionEvent ae) -> {
+ if (list.getSelectedIndex() == 0) return;
+ final int index = list.getSelectedIndex();
+ final AbstractOption temp = model.getElementAt(index);
+ model.setElementAt(model.getElementAt(index-1), index);
+ model.setElementAt(temp, index-1);
+ list.setSelectedIndex(index-1);
+ });
+ downButton.addActionListener((ActionEvent ae) -> {
+ if (list.getSelectedIndex() == model.getSize() - 1) return;
+ final int index = list.getSelectedIndex();
+ final AbstractOption temp = model.getElementAt(index);
+ model.setElementAt(model.getElementAt(index+1), index);
+ model.setElementAt(temp, index+1);
+ list.setSelectedIndex(index+1);
});
list.addListSelectionListener(this);
diff --git a/src/net/sf/freecol/client/gui/panel/AboutPanel.java b/src/net/sf/freecol/client/gui/panel/AboutPanel.java
index 16206315a..8506a6b29 100644
--- a/src/net/sf/freecol/client/gui/panel/AboutPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/AboutPanel.java
@@ -38,7 +38,6 @@ import net.miginfocom.swing.MigLayout;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.FontLibrary;
-import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.resources.ResourceManager;
@@ -72,13 +71,15 @@ import net.sf.freecol.common.resources.ResourceManager;
*/
public final class AboutPanel extends FreeColPanel {
- private static final Logger logger = Logger
- .getLogger(AboutPanel.class.getName());
+ private static final Logger logger = Logger.getLogger(AboutPanel.class.getName());
public static final String SITE_URL
= "http://www.freecol.org";
public static final String PROJECT_URL
= "http://sourceforge.net/projects/freecol/";
+ private static final String MANUAL_URL
+ = "http://www.freecol.org/documentation/freecol-user-manual.html";
+
/**
* The constructor that will add the items to this panel.
@@ -99,9 +100,9 @@ public final class AboutPanel extends FreeColPanel {
// Create available Font choices
Font fontBold = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.TINY, Font.BOLD,
- getImageLibrary().getScalingFactor());
+ getImageLibrary().getScaleFactor());
Font fontNormal = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, getImageLibrary().getScalingFactor());
+ FontLibrary.FontSize.TINY, getImageLibrary().getScaleFactor());
// Version
JLabel apVersion = Utility.localizedLabel("aboutPanel.version");
@@ -131,6 +132,15 @@ public final class AboutPanel extends FreeColPanel {
apProjectURL.setFont(fontNormal);
add(apProjectURL, "newline");
+ // Manual
+ JLabel apManual = Utility.localizedLabel("aboutPanel.manual");
+ apManual.setFont(fontBold);
+ add(apManual, "newline 10");
+ JButton apManualURL = Utility.getLinkButton(MANUAL_URL, null,
+ MANUAL_URL);
+ apManualURL.addActionListener(this);
+ add(apManualURL, "newline");
+
// License Disclaimer
JTextArea apLegal
= Utility.localizedTextArea("aboutPanel.legalDisclaimer");
@@ -149,12 +159,12 @@ public final class AboutPanel extends FreeColPanel {
/**
* {@inheritDoc}
- * @param event
*/
@Override
- public void actionPerformed(ActionEvent event) {
- String url = event.getActionCommand();
- if (SITE_URL.equals(url) || PROJECT_URL.equals(url)) {
+ public void actionPerformed(ActionEvent ae) {
+ final String url = ae.getActionCommand();
+ if (SITE_URL.equals(url) || PROJECT_URL.equals(url)
+ || MANUAL_URL.equals(url)) {
String os = System.getProperty("os.name");
// FIXME: move this to OS utilities
String[] cmd = null;
@@ -181,7 +191,7 @@ public final class AboutPanel extends FreeColPanel {
// couldn't start browser
}
} else {
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/AbstractGoodsLabel.java b/src/net/sf/freecol/client/gui/panel/AbstractGoodsLabel.java
index 8699a22af..ae67389b4 100644
--- a/src/net/sf/freecol/client/gui/panel/AbstractGoodsLabel.java
+++ b/src/net/sf/freecol/client/gui/panel/AbstractGoodsLabel.java
@@ -38,6 +38,8 @@ public class AbstractGoodsLabel extends JLabel {
private boolean partialChosen = false;
+ private boolean fullChosen = false;
+
/**
* Initializes this JLabel with the given goods data.
@@ -72,6 +74,24 @@ public class AbstractGoodsLabel extends JLabel {
this.partialChosen = partialChosen;
}
+ /**
+ * Has full amount been selected?
+ *
+ * @return True if a full amount has been selected.
+ */
+ public boolean isFullChosen() {
+ return fullChosen;
+ }
+
+ /**
+ * Set the full amount state.
+ *
+ * @param fullChosen The new full amount state.
+ */
+ public void setFullChosen(boolean fullChosen) {
+ this.fullChosen = fullChosen;
+ }
+
/**
* Get the goods data.
*
diff --git a/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java b/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java
index 1395a6884..8f57b3cd0 100644
--- a/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/BuildQueuePanel.java
@@ -32,6 +32,7 @@ import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
@@ -85,7 +86,7 @@ import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Turn;
import net.sf.freecol.common.model.UnitType;
-
+import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
@@ -164,10 +165,7 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
*/
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
- for (DataFlavor myFlavor : supportedFlavors) {
- if (myFlavor.equals(flavor)) return true;
- }
- return false;
+ return any(supportedFlavors, f -> f.equals(flavor));
}
}
@@ -338,11 +336,8 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
*/
@Override
public boolean canImport(JComponent comp, DataFlavor[] flavors) {
- if (flavors == null) return false;
- for (DataFlavor flavor : flavors) {
- if (flavor.equals(BUILD_LIST_FLAVOR)) return true;
- }
- return false;
+ return flavors != null
+ && any(flavors, f -> f.equals(BUILD_LIST_FLAVOR));
}
/**
@@ -552,15 +547,15 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
BuildQueueMouseAdapter adapter = new BuildQueueMouseAdapter(true);
Action addAction = new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
JList bql
= BuildQueuePanel.this.buildQueueList;
DefaultListModel model
= (DefaultListModel)bql.getModel();
JList extends BuildableType> btl
- = (e.getSource() == BuildQueuePanel.this.unitList)
+ = (ae.getSource() == BuildQueuePanel.this.unitList)
? BuildQueuePanel.this.unitList
- : (e.getSource() == BuildQueuePanel.this.buildingList)
+ : (ae.getSource() == BuildQueuePanel.this.buildingList)
? BuildQueuePanel.this.buildingList
: null;
if (btl != null) {
@@ -575,12 +570,12 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
// Create Font choice
Font fontSubHead = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.SMALLER, Font.BOLD,
- getImageLibrary().getScalingFactor());
+ getImageLibrary().getScaleFactor());
// Create the components
- JLabel header = Utility.localizedLabel("buildQueuePanel.buildQueue");
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.BIG));
+ JLabel header = Utility.localizedHeaderLabel(
+ "buildQueuePanel.buildQueue",
+ SwingConstants.LEADING, FontLibrary.FontSize.BIG);
// JLabel SubHeads
JLabel bqpUnits = Utility.localizedLabel("buildQueuePanel.units");
@@ -619,7 +614,7 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
this.buildQueueList.getActionMap().put("delete",
new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
JList bql = BuildQueuePanel.
this.buildQueueList;
for (BuildableType bt : bql.getSelectedValuesList()) {
@@ -946,18 +941,6 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
return result;
}
- private List getBuildableTypes(Object[] objects) {
- List result = new ArrayList<>();
- if (objects != null) {
- for (Object object : objects) {
- if (object instanceof BuildableType) {
- result.add((BuildableType) object);
- }
- }
- }
- return result;
- }
-
private int getMinimumIndex(BuildableType buildableType) {
ListModel buildQueue = this.buildQueueList.getModel();
if (buildableType instanceof UnitType) {
@@ -1073,10 +1056,10 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
+ public void actionPerformed(ActionEvent ae) {
final String FAIL = "FAIL";
if (this.colony.getOwner() == getMyPlayer()) {
- String command = event.getActionCommand();
+ String command = ae.getActionCommand();
List buildables = getBuildableTypes(this
.buildQueueList);
while (!buildables.isEmpty()
@@ -1098,7 +1081,7 @@ public class BuildQueuePanel extends FreeColPanel implements ItemListener {
igc().payForBuilding(this.colony);
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/BuildingDetailPanel.java b/src/net/sf/freecol/client/gui/panel/BuildingDetailPanel.java
index 3e398f080..71c4ad5be 100644
--- a/src/net/sf/freecol/client/gui/panel/BuildingDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/BuildingDetailPanel.java
@@ -21,7 +21,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import java.awt.Font;
-import java.awt.Image;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@@ -53,7 +52,6 @@ import net.sf.freecol.common.model.Modifier;
import net.sf.freecol.common.model.ProductionType;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.UnitType;
-import net.sf.freecol.common.resources.ResourceManager;
/**
@@ -74,21 +72,22 @@ public class BuildingDetailPanel
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
- DefaultMutableTreeNode parent =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(), getName(), null));
+ DefaultMutableTreeNode parent
+ = new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(),
+ getName(), null));
List buildingTypes = new ArrayList<>();
- Map buildingHash = new HashMap<>();
- for (BuildingType buildingType : getSpecification().getBuildingTypeList()) {
+ Map buildingHash
+ = new HashMap<>();
+ for (BuildingType buildingType
+ : getSpecification().getBuildingTypeList()) {
if (buildingType.getUpgradesFrom() == null) {
String name = Messages.getName(buildingType);
DefaultMutableTreeNode item =
@@ -124,24 +123,16 @@ public class BuildingDetailPanel
}
/**
- * Builds the details panel for the BuildingType with the given
- * identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (getId().equals(id)) {
- return;
- }
+ if (getId().equals(id)) return;
BuildingType buildingType = getSpecification().getBuildingType(id);
panel.setLayout(new MigLayout("wrap 7, gapx 20", "", ""));
- JLabel name = Utility.localizedLabel(buildingType);
- name.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel name = Utility.localizedHeaderLabel(buildingType, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
// Requires - prerequisites to build
@@ -280,5 +271,4 @@ public class BuildingDetailPanel
panel.add(Utility.localizedTextArea(Messages.descriptionKey(buildingType)),
"span, growx");
}
-
}
diff --git a/src/net/sf/freecol/client/gui/panel/BuildingPanel.java b/src/net/sf/freecol/client/gui/panel/BuildingPanel.java
index 81f1b805e..d1bb7a56a 100644
--- a/src/net/sf/freecol/client/gui/panel/BuildingPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/BuildingPanel.java
@@ -262,7 +262,7 @@ public class BuildingPanel extends MigPanel implements PropertyChangeListener {
Integer.toString(number), getForeground(),
FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
FontLibrary.FontSize.TINY, Font.BOLD,
- lib.getScalingFactor()));
+ lib.getScaleFactor()));
g.drawImage(image,
(getIcon().getIconWidth() - image.getWidth(null))/2,
(getIcon().getIconHeight() - image.getHeight(null))/2, null);
diff --git a/src/net/sf/freecol/client/gui/panel/BuildingToolTip.java b/src/net/sf/freecol/client/gui/panel/BuildingToolTip.java
index fc799398c..1f248371f 100644
--- a/src/net/sf/freecol/client/gui/panel/BuildingToolTip.java
+++ b/src/net/sf/freecol/client/gui/panel/BuildingToolTip.java
@@ -72,7 +72,7 @@ public class BuildingToolTip extends JToolTip {
if (arrow == null) {
arrow = new JLabel(ResourceManager.getString("arrow.E"));
arrow.setFont(FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.SMALL, Font.BOLD, lib.getScalingFactor()));
+ FontLibrary.FontSize.SMALL, Font.BOLD, lib.getScaleFactor()));
}
String columns = "[align center]";
@@ -86,42 +86,46 @@ public class BuildingToolTip extends JToolTip {
JLabel buildingName = new JLabel(Messages.getName(building));
buildingName.setFont(FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.SMALLER, Font.BOLD, lib.getScalingFactor()));
+ FontLibrary.FontSize.SMALLER, Font.BOLD, lib.getScaleFactor()));
add(buildingName, "span");
ProductionInfo info = building.getProductionInfo();
- if (info == null || info.getProduction().isEmpty()) {
+ AbstractGoods production
+ = (info == null || info.getProduction().isEmpty()) ? null
+ : info.getProduction().get(0);
+ AbstractGoods consumption
+ = (info == null || info.getConsumption().isEmpty()) ? null
+ : info.getConsumption().get(0);
+ if (production == null || production.getAmount() <= 0) {
add(new JLabel(), "span");
} else {
- AbstractGoods production = info.getProduction().get(0);
+ AbstractGoods maxProduction = (info == null
+ || info.getMaximumProduction().isEmpty()) ? null
+ : info.getMaximumProduction().get(0);
ProductionLabel productionOutput
= new ProductionLabel(freeColClient, production,
- ((info.getMaximumProduction().isEmpty())
- ? production
- : info.getMaximumProduction().get(0))
- .getAmount());
- if (info.getConsumption().isEmpty()) {
+ ((maxProduction == null) ? production
+ : maxProduction).getAmount());
+ if (consumption == null) {
add(productionOutput, "span");
+ } else if (consumption.getAmount() > 0) {
+ AbstractGoods maxConsumption = (info == null
+ || info.getMaximumConsumption().isEmpty()) ? null
+ : info.getMaximumConsumption().get(0);
+ ProductionLabel productionInput
+ = new ProductionLabel(freeColClient, consumption,
+ ((maxConsumption == null) ? consumption
+ : maxConsumption).getAmount());
+ add(productionInput, "span, split 3");
+ add(arrow);
+ add(productionOutput);
} else {
- AbstractGoods consumption = info.getConsumption().get(0);
- if (consumption.getAmount() > 0) {
- ProductionLabel productionInput
- = new ProductionLabel(freeColClient, consumption,
- ((info.getMaximumConsumption().isEmpty())
- ? consumption
- : info.getMaximumConsumption().get(0))
- .getAmount());
- add(productionInput, "span, split 3");
- add(arrow);
- add(productionOutput);
- } else {
- add(new JLabel(new ImageIcon(
- lib.getIconImage(consumption.getType()))),
- "span, split 3");
- add(arrow);
- add(new JLabel(new ImageIcon(
- lib.getIconImage(production.getType()))));
- }
+ add(new JLabel(new ImageIcon(lib
+ .getIconImage(consumption.getType()))),
+ "span, split 3");
+ add(arrow);
+ add(new JLabel(new ImageIcon(lib
+ .getIconImage(production.getType()))));
}
}
@@ -129,11 +133,11 @@ public class BuildingToolTip extends JToolTip {
for (Unit unit : building.getUnitList()) {
UnitLabel unitLabel = new UnitLabel(freeColClient, unit, false);
- int production = building.getUnitProduction(unit, output);
- if (production > 0) {
+ int amount = building.getUnitProduction(unit, output);
+ if (amount > 0) {
add(unitLabel);
JLabel pLabel = new ProductionLabel(freeColClient,
- new AbstractGoods(output, production));
+ new AbstractGoods(output, amount));
add(pLabel, "split 2");
add(new JLabel());
} else if (building.canTeach() && unit.getStudent() != null) {
diff --git a/src/net/sf/freecol/client/gui/panel/CaptureGoodsDialog.java b/src/net/sf/freecol/client/gui/panel/CaptureGoodsDialog.java
index b4dfa4d13..b0c6609ef 100644
--- a/src/net/sf/freecol/client/gui/panel/CaptureGoodsDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/CaptureGoodsDialog.java
@@ -21,7 +21,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Component;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
@@ -38,6 +37,7 @@ import javax.swing.ListCellRenderer;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.Unit;
@@ -126,31 +126,25 @@ public final class CaptureGoodsDialog extends FreeColDialog> {
this.maxCargo = winner.getSpaceLeft();
this.allButton = Utility.localizedButton("all");
- this.allButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- JList gl = CaptureGoodsDialog.this.goodsList;
- for (int i = 0; i < gl.getModel().getSize()
- && i < CaptureGoodsDialog.this.maxCargo; i++) {
- GoodsItem gi = gl.getModel().getElementAt(i);
- gi.setSelected(true);
- updateComponents();
- }
+ this.allButton.addActionListener((ActionEvent ae) -> {
+ JList gl = CaptureGoodsDialog.this.goodsList;
+ for (int i = 0; i < gl.getModel().getSize()
+ && i < CaptureGoodsDialog.this.maxCargo; i++) {
+ GoodsItem gi = gl.getModel().getElementAt(i);
+ gi.setSelected(true);
+ updateComponents();
}
});
this.allButton.setMnemonic('a');
this.allButton.setActionCommand(this.allButton.getText());
this.noneButton = Utility.localizedButton("none");
- this.noneButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- JList gl = CaptureGoodsDialog.this.goodsList;
- for (int i = 0; i < gl.getModel().getSize(); i++) {
- GoodsItem gi = gl.getModel().getElementAt(i);
- gi.setSelected(false);
- updateComponents();
- }
+ this.noneButton.addActionListener((ActionEvent ae) -> {
+ JList gl = CaptureGoodsDialog.this.goodsList;
+ for (int i = 0; i < gl.getModel().getSize(); i++) {
+ GoodsItem gi = gl.getModel().getElementAt(i);
+ gi.setSelected(false);
+ updateComponents();
}
});
this.noneButton.setMnemonic('n');
diff --git a/src/net/sf/freecol/client/gui/panel/ChatPanel.java b/src/net/sf/freecol/client/gui/panel/ChatPanel.java
index df9fbe9ae..66cb416c8 100644
--- a/src/net/sf/freecol/client/gui/panel/ChatPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ChatPanel.java
@@ -95,8 +95,8 @@ public final class ChatPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
try {
switch (Integer.parseInt(command)) {
case CHAT:
@@ -106,7 +106,7 @@ public final class ChatPanel extends FreeColPanel {
getGUI().removeFromCanvas(this);
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
} catch (NumberFormatException e) {
logger.warning("Invalid ActionEvent, not a number: " + command);
diff --git a/src/net/sf/freecol/client/gui/panel/ChooseFoundingFatherDialog.java b/src/net/sf/freecol/client/gui/panel/ChooseFoundingFatherDialog.java
index 72e5f2b0d..a9bd946c1 100644
--- a/src/net/sf/freecol/client/gui/panel/ChooseFoundingFatherDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/ChooseFoundingFatherDialog.java
@@ -30,6 +30,7 @@ import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.FoundingFather;
diff --git a/src/net/sf/freecol/client/gui/panel/ColonyPanel.java b/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
index 092480df5..380320dd9 100644
--- a/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ColonyPanel.java
@@ -274,15 +274,28 @@ public final class ColonyPanel extends PortPanel
selectedUnitLabel = null;
// Make the colony label
- this.nameBox.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL, getImageLibrary().getScalingFactor()));
+ Font nameBoxFont = FontLibrary.createFont(FontLibrary.FontType.HEADER,
+ FontLibrary.FontSize.SMALL, getImageLibrary().getScaleFactor());
+ boolean incompatibleFont = false;
if (editable) {
for (Colony c : freeColClient.getMySortedColonies()) {
this.nameBox.addItem(c);
+ if(!incompatibleFont &&
+ nameBoxFont.canDisplayUpTo(c.getName()) != -1) {
+ incompatibleFont = true;
+ }
}
} else { // When spying, only add the given colony.
this.nameBox.addItem(colony);
+ if(nameBoxFont.canDisplayUpTo(colony.getName()) != -1)
+ incompatibleFont = true;
}
+ if(incompatibleFont) {
+ nameBoxFont = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
+ FontLibrary.FontSize.SMALL,
+ getImageLibrary().getScaleFactor());
+ }
+ this.nameBox.setFont(nameBoxFont);
this.nameBox.setSelectedItem(colony);
this.nameBox.getInputMap().put(KeyStroke.getKeyStroke("LEFT"),
"selectPrevious2");
@@ -342,7 +355,7 @@ public final class ColonyPanel extends PortPanel
JComponent.WHEN_IN_FOCUSED_WINDOW, nameIM);
initialize(colony);
- float scale = getImageLibrary().getScalingFactor();
+ float scale = getImageLibrary().getScaleFactor();
getGUI().restoreSavedSize(this, 200 + (int)(scale*850), 200 + (int)(scale*525));
}
@@ -401,13 +414,10 @@ public final class ColonyPanel extends PortPanel
final GUI gui = getGUI();
this.nameBox.setEnabled(isEditable());
- this.nameBox.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- final Colony newColony = (Colony)nameBox.getSelectedItem();
- closeColonyPanel();
- gui.showColonyPanel(newColony, null);
- }
+ this.nameBox.addActionListener((ActionEvent ae) -> {
+ final Colony newColony = (Colony)nameBox.getSelectedItem();
+ closeColonyPanel();
+ gui.showColonyPanel(newColony, null);
});
updateNetProductionPanel();
@@ -422,7 +432,7 @@ public final class ColonyPanel extends PortPanel
add(this.nameBox, "height 42:, grow");
int tmp = (int)(ImageLibrary.ICON_SIZE.height
- * gui.getImageLibrary().getScalingFactor());
+ * gui.getImageLibrary().getScaleFactor());
add(netProductionPanel,
"grow, height " + (tmp+10) + ":" + (2*tmp+10) + ":" + (2*tmp+10));
add(tilesScroll, "width 390!, height 200!, top");
@@ -644,7 +654,7 @@ public final class ColonyPanel extends PortPanel
.template(goodsType)
.addAmount("%amount%", producing));
sb.append(unit.getDescription())
- .append(" ").append(Messages.message("producing.name"))
+ .append(" ").append(Messages.message("colonyPanel.producing"))
.append(" ").append(producing)
.append(" ").append(nominative);
} else if (workingInBuilding != null && goodsType != null) {
@@ -664,12 +674,9 @@ public final class ColonyPanel extends PortPanel
}
String menuTitle = sb.toString();
subMenu = new JMenuItem(menuTitle, unitIcon);
- subMenu.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- unitMenu.addMenuItems(new UnitLabel(freeColClient, unit));
- unitMenu.show(getGUI().getCanvas(), 0, 0);
- }
+ subMenu.addActionListener((ActionEvent ae) -> {
+ unitMenu.addMenuItems(new UnitLabel(freeColClient, unit));
+ unitMenu.show(getGUI().getCanvas(), 0, 0);
});
unitNumber++;
colonyUnitsMenu.add(subMenu);
@@ -681,13 +688,10 @@ public final class ColonyPanel extends PortPanel
String menuTitle = unit.getDescription()
+ " " + Messages.message("colonyPanel.inPort");
subMenu = new JMenuItem(menuTitle, unitIcon);
- subMenu.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
+ subMenu.addActionListener((ActionEvent ae) -> {
unitMenu.addMenuItems(new UnitLabel(freeColClient, unit));
unitMenu.show(getGUI().getCanvas(), 0, 0);
- }
- });
+ });
unitNumber++;
colonyUnitsMenu.add(subMenu);
if (unit.getUnitList() != null) {
@@ -697,13 +701,10 @@ public final class ColonyPanel extends PortPanel
+ " " + Messages.message("cargoOnCarrier")
+ " " + unit.getDescription();
subMenu = new JMenuItem(menuTitle, unitIcon);
- subMenu.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
+ subMenu.addActionListener((ActionEvent ae) -> {
unitMenu.addMenuItems(new UnitLabel(freeColClient, innerUnit));
unitMenu.show(getGUI().getCanvas(), 0, 0);
- }
- });
+ });
unitNumber++;
colonyUnitsMenu.add(subMenu);
}
@@ -711,15 +712,12 @@ public final class ColonyPanel extends PortPanel
} else if (!unit.isOnCarrier()) {
unitIcon = new ImageIcon(lib.getSmallerUnitImage(unit));
String menuTitle = unit.getDescription()
- + " " + Messages.message("colonyPanel.outsideOfColony");
+ + " " + Messages.message("colonyPanel.outsideColony");
subMenu = new JMenuItem(menuTitle, unitIcon);
- subMenu.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
+ subMenu.addActionListener((ActionEvent ae) -> {
unitMenu.addMenuItems(new UnitLabel(freeColClient, unit));
unitMenu.show(getGUI().getCanvas(), 0, 0);
- }
- });
+ });
unitNumber++;
colonyUnitsMenu.add(subMenu);
}
@@ -893,7 +891,7 @@ public final class ColonyPanel extends PortPanel
final Colony colony = getColony();
boolean abandon = false;
if (colony.getUnitCount() == 0 && getMyPlayer().owns(colony)) {
- if (!getGUI().confirm(true, null,
+ if (!getGUI().confirm(null,
StringTemplate.key("abandonColony.text"),
"abandonColony.yes",
"abandonColony.no")) return;
@@ -903,7 +901,7 @@ public final class ColonyPanel extends PortPanel
BuildableType buildable = colony.getCurrentlyBuilding();
if (buildable != null
&& buildable.getRequiredPopulation() > colony.getUnitCount()
- && !getGUI().confirm(true, null, StringTemplate
+ && !getGUI().confirm(null, StringTemplate
.template("colonyPanel.reducePopulation")
.addName("%colony%", colony.getName())
.addAmount("%number%", buildable.getRequiredPopulation())
@@ -916,7 +914,6 @@ public final class ColonyPanel extends PortPanel
cleanup();
getGUI().removeFromCanvas(this);
- getGUI().restartBlinking();
getGUI().updateMapControls();
// Talk to the controller last, allow all the cleanup to happen first.
@@ -953,9 +950,9 @@ public final class ColonyPanel extends PortPanel
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
+ public void actionPerformed(ActionEvent ae) {
final Colony colony = getColony();
- final String command = event.getActionCommand();
+ final String command = ae.getActionCommand();
final Unit unit = getSelectedUnit();
if (OK.equals(command)) {
@@ -1017,7 +1014,7 @@ public final class ColonyPanel extends PortPanel
colony.setOccupationTrace(!colony.getOccupationTrace());
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
}
}
@@ -1075,6 +1072,8 @@ public final class ColonyPanel extends PortPanel
updateInPortPanel();
updatePopulationPanel();
updateWarehousePanel();// Role change changes equipment goods
+ } else if (Unit.MOVE_CHANGE.equals(property)) {
+ updateOutsideColonyPanel();
} else {
// ColonyTiles and Buildings now have their own
// propertyChangeListeners so {ColonyTile,Building}.UNIT_CHANGE
@@ -1208,10 +1207,9 @@ public final class ColonyPanel extends PortPanel
public void update() {
final Colony colony = getColony();
if (colony == null) return;
- final ImageLibrary lib = getGUI().getColonyTileMapViewer()
- .getImageLibrary();
+ final ImageLibrary lib = getGUI().getTileImageLibrary();
final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.SMALLER, lib.getScalingFactor());
+ FontLibrary.FontSize.SMALLER, lib.getScaleFactor());
final int uc = colony.getUnitCount();
final int solPercent = colony.getSoL();
final int rebels = Colony.calculateRebels(uc, solPercent);
@@ -1911,8 +1909,8 @@ public final class ColonyPanel extends PortPanel
/**
* A panel that displays the tiles in the immediate area around the colony.
- * TilesPanel class must use the ImageLibrary inside
- * getGUI().getColonyTileMapViewer() for everything.
+ * TilesPanel class must use the ImageLibrary inside SwingGUI.tileMapViewer
+ * for everything.
*/
public final class TilesPanel extends JPanel {
@@ -2001,8 +1999,7 @@ public final class ColonyPanel extends PortPanel
g.fillRect(0, 0, getWidth(), getHeight());
if (colony == null) return;
- getGUI().getColonyTileMapViewer().displayColonyTiles(
- (Graphics2D)g, tiles, colony);
+ getGUI().displayColonyTiles((Graphics2D)g, tiles, colony);
}
/**
@@ -2030,8 +2027,8 @@ public final class ColonyPanel extends PortPanel
setLayout(new FlowLayout(FlowLayout.CENTER, 0, 0));
setOpaque(false);
// Size and position:
- Dimension size = getGUI().getColonyTileMapViewer()
- .getImageLibrary().calculateTileSize(colonyTile.getTile());
+ Dimension size = getGUI().getTileImageLibrary()
+ .scaleDimension(ImageLibrary.TILE_SIZE);
setSize(size);
setLocation(((2 - x) + y) * size.width / 2,
(x + y) * size.height / 2);
@@ -2099,8 +2096,7 @@ public final class ColonyPanel extends PortPanel
for (AbstractGoods ag : info.getProduction()) {
ProductionLabel productionLabel
= new ProductionLabel(getFreeColClient(),
- getGUI().getColonyTileMapViewer()
- .getImageLibrary(),
+ getGUI().getTileImageLibrary(),
ag);
productionLabel.addMouseListener(pressListener);
add(productionLabel);
diff --git a/src/net/sf/freecol/client/gui/panel/ColopediaGameObjectTypePanel.java b/src/net/sf/freecol/client/gui/panel/ColopediaGameObjectTypePanel.java
index 932355cae..e82589620 100644
--- a/src/net/sf/freecol/client/gui/panel/ColopediaGameObjectTypePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ColopediaGameObjectTypePanel.java
@@ -19,7 +19,6 @@
package net.sf.freecol.client.gui.panel;
-import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
@@ -60,10 +59,20 @@ public abstract class ColopediaGameObjectTypePanel {
+ /** The enclosing colopedia panel. */
+ private ColopediaPanel colopediaPanel;
+
+ /** The specific panel id. */
private final String id;
- private ColopediaPanel colopediaPanel;
+ /**
+ * Create a new Colopedia game object type panel.
+ *
+ * @param freeColClient The FreeColClient
for the game.
+ * @param colopediaPanel The parent ColopediaPanel
.
+ * @param id The panel type identifier.
+ */
public ColopediaGameObjectTypePanel(FreeColClient freeColClient,
ColopediaPanel colopediaPanel,
String id) {
@@ -73,21 +82,27 @@ public abstract class ColopediaGameObjectTypePanel types) {
+ public void addSubTrees(DefaultMutableTreeNode root, String id,
+ List types) {
String name = getName();
- DefaultMutableTreeNode node =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, id, name, null));
+ ColopediaTreeItem cti = new ColopediaTreeItem(this, id, name, null);
+ DefaultMutableTreeNode node = new DefaultMutableTreeNode(cti);
int width = ImageLibrary.ICON_SIZE.width;
int height = ImageLibrary.ICON_SIZE.height;
for (FreeColGameObjectType type : types) {
Image image = (type instanceof GoodsType)
- ? ImageLibrary.getMiscImage("image.icon." + type.getId(), ImageLibrary.ICON_SIZE)
+ ? ImageLibrary.getMiscImage("image.icon." + type.getId(),
+ ImageLibrary.ICON_SIZE)
: (type instanceof ResourceType)
- ? ImageLibrary.getMiscImage("image.tileitem." + type.getId(), ImageLibrary.ICON_SIZE)
- : (type instanceof Nation)
- ? ImageLibrary.getMiscIconImage(type, ImageLibrary.ICON_SIZE)
- : (type instanceof BuildableType)
- ? ImageLibrary.getBuildableImage((BuildableType)type, ImageLibrary.ICON_SIZE)
- : ImageLibrary.getMiscImage(ResourceManager.REPLACEMENT_IMAGE, ImageLibrary.ICON_SIZE);
+ ? ImageLibrary.getMiscImage("image.tileitem." + type.getId(),
+ ImageLibrary.ICON_SIZE)
+ : (type instanceof Nation)
+ ? ImageLibrary.getMiscIconImage(type, ImageLibrary.ICON_SIZE)
+ : (type instanceof BuildableType)
+ ? ImageLibrary.getBuildableImage((BuildableType)type,
+ ImageLibrary.ICON_SIZE)
+ : ImageLibrary.getMiscImage(ResourceManager.REPLACEMENT_IMAGE,
+ ImageLibrary.ICON_SIZE);
int x = (width - image.getWidth(null)) / 2;
int y = (height - image.getHeight(null)) / 2;
- BufferedImage centeredImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
+ BufferedImage centeredImage
+ = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = centeredImage.createGraphics();
g.drawImage(image, x, y, null);
g.dispose();
@@ -132,21 +153,23 @@ public abstract class ColopediaGameObjectTypePanelTreeSelectionEvent
.
*/
@Override
public void valueChanged(TreeSelectionEvent event) {
- DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
+ DefaultMutableTreeNode node
+ = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent();
if (node != null) {
- showDetails((ColopediaTreeItem) node.getUserObject());
+ showDetails((ColopediaTreeItem)node.getUserObject());
}
}
@@ -221,8 +223,8 @@ public final class ColopediaPanel extends FreeColPanel
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (OK.equals(command)) {
getGUI().removeFromCanvas(this);
} else {
diff --git a/src/net/sf/freecol/client/gui/panel/ColopediaTreeCellRenderer.java b/src/net/sf/freecol/client/gui/panel/ColopediaTreeCellRenderer.java
index bd3307ef8..2a1e62146 100644
--- a/src/net/sf/freecol/client/gui/panel/ColopediaTreeCellRenderer.java
+++ b/src/net/sf/freecol/client/gui/panel/ColopediaTreeCellRenderer.java
@@ -43,25 +43,25 @@ public class ColopediaTreeCellRenderer extends DefaultTreeCellRenderer {
setBackgroundNonSelectionColor(new Color(0,0,0,1));
}
+
/**
- * Returns the rendered Component
- *
- * @return the rendered item's Component
+ * {@inheritDoc}
*/
@Override
- public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected,
- boolean expanded, boolean leaf, int row, boolean hasFocus) {
+ public Component getTreeCellRendererComponent(JTree tree, Object value,
+ boolean selected, boolean expanded, boolean leaf, int row,
+ boolean hasFocus) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
- super.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus);
+ super.getTreeCellRendererComponent(tree, value, selected, expanded,
+ leaf, row, hasFocus);
ColopediaTreeItem nodeItem = (ColopediaTreeItem)node.getUserObject();
-
if (nodeItem.getIcon() != null) {
setIcon(nodeItem.getIcon());
- } else if (expanded) {
- setIcon(new ImageIcon(ResourceManager.getImage("image.icon.Colopedia.openSection")));
} else {
- setIcon(new ImageIcon(ResourceManager.getImage("image.icon.Colopedia.closedSection")));
+ String key = "image.icon.Colopedia."
+ + ((expanded) ? "open" : "closed") + "Section";
+ setIcon(new ImageIcon(ResourceManager.getImage(key)));
}
return this;
}
diff --git a/src/net/sf/freecol/client/gui/panel/ColopediaTreeItem.java b/src/net/sf/freecol/client/gui/panel/ColopediaTreeItem.java
index 4e56a3515..383ad64ff 100644
--- a/src/net/sf/freecol/client/gui/panel/ColopediaTreeItem.java
+++ b/src/net/sf/freecol/client/gui/panel/ColopediaTreeItem.java
@@ -28,22 +28,24 @@ import javax.swing.ImageIcon;
*/
class ColopediaTreeItem {
- private final ColopediaDetailPanel panelType;
+ private final ColopediaDetailPanel detailPanel;
private final String id;
private final String text;
private final ImageIcon icon;
+
/**
* The default constructor for a ColopediaTreeItem that
* corresponds to a leaf node.
*
- * @param panelType a ColopediaDetailPanel
value
+ * @param detailPanel A ColopediaDetailPanel
value.
* @param id The object identifier.
* @param text a String
value
* @param icon an ImageIcon
value
*/
- ColopediaTreeItem(ColopediaDetailPanel panelType, String id, String text, ImageIcon icon) {
- this.panelType = panelType;
+ ColopediaTreeItem(ColopediaDetailPanel detailPanel, String id, String text,
+ ImageIcon icon) {
+ this.detailPanel = detailPanel;
this.id = id;
this.text = text;
this.icon = icon;
@@ -55,7 +57,7 @@ class ColopediaTreeItem {
* @return the panel type this item belongs to.
*/
public ColopediaDetailPanel getPanelType() {
- return panelType;
+ return detailPanel;
}
public String getId() {
diff --git a/src/net/sf/freecol/client/gui/panel/ColorCellEditor.java b/src/net/sf/freecol/client/gui/panel/ColorCellEditor.java
index b7bb89202..52a2f6b4f 100644
--- a/src/net/sf/freecol/client/gui/panel/ColorCellEditor.java
+++ b/src/net/sf/freecol/client/gui/panel/ColorCellEditor.java
@@ -32,7 +32,7 @@ import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.SwingGUI;
/**
@@ -96,9 +96,9 @@ public final class ColorCellEditor extends AbstractCellEditor
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
- GUI gui = freeColClient.getGUI();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
+ SwingGUI gui = (SwingGUI)freeColClient.getGUI();
if (null != command) switch (command) {
case EDIT:
this.colorChooserPanel = gui.showColorChooserPanel(this);
diff --git a/src/net/sf/freecol/client/gui/panel/CompactLabourReport.java b/src/net/sf/freecol/client/gui/panel/CompactLabourReport.java
index 6634c9452..fb1418195 100644
--- a/src/net/sf/freecol/client/gui/panel/CompactLabourReport.java
+++ b/src/net/sf/freecol/client/gui/panel/CompactLabourReport.java
@@ -128,11 +128,8 @@ public final class CompactLabourReport extends ReportPanel {
}
}
- return createButton(text, new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
+ return createButton(text, (ActionEvent ae) -> {
getGUI().showColonyPanel(colony, null);
- }
});
}
@@ -397,32 +394,34 @@ public final class CompactLabourReport extends ReportPanel {
int row = 1;
JLabel summaryLabel = Utility.localizedLabel("report.labour.summary");
summaryLabel.setBorder(Utility.LEFTCELLBORDER);
- reportPanel.add(summaryLabel, "cell " + COLONY_COLUMN + " " + row + " 1 " + unitTotal.getRowCount());
+ reportPanel.add(summaryLabel, "cell " + COLONY_COLUMN + " " + row
+ + " 1 " + unitTotal.getRowCount());
row = addLocationData(unitTotal, null, row);
for (Colony colony : getFreeColClient().getMySortedColonies()) {
- LabourData.LocationData colonyData = unitData.getDetails().get(colony);
+ LabourData.LocationData colonyData
+ = unitData.getDetails().get(colony);
if (colonyData != null) {
- reportPanel.add(createColonyButton(colony), "cell " + COLONY_COLUMN + " "
- + row + " 1 " + colonyData.getRowCount());
+ reportPanel.add(createColonyButton(colony),
+ "cell " + COLONY_COLUMN + " " + row
+ + " 1 " + colonyData.getRowCount());
row = addLocationData(colonyData, colony, row);
}
}
LabourData.LocationData europe = unitData.getUnitsInEurope();
if (europe.getRowCount() > 0) {
- JButton button = createButton(Messages.getName(getMyPlayer().getEurope()),
- new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- getGUI().showEuropePanel();
- }
- });
- reportPanel.add(button, "cell " + COLONY_COLUMN + " " + row + " 1 " + europe.getRowCount());
+ String nam = Messages.getName(getMyPlayer().getEurope());
+ JButton button = createButton(nam,
+ (ActionEvent ae) -> { getGUI().showEuropePanel(); });
+ reportPanel.add(button, "cell " + COLONY_COLUMN + " " + row
+ + " 1 " + europe.getRowCount());
row = addLocationData(europe, null, row);
}
- row = addNonLinkedLocation(unitData.getUnitsOnLand(), "report.labour.onLand", row);
- row = addNonLinkedLocation(unitData.getUnitsAtSea(), "report.labour.atSea", row);
+ row = addNonLinkedLocation(unitData.getUnitsOnLand(),
+ "report.labour.onLand", row);
+ row = addNonLinkedLocation(unitData.getUnitsAtSea(),
+ "report.labour.atSea", row);
reportPanel.add(Utility.localizedLabel("report.labour.canTrain"),
"cell 1 " + row + " " + COLUMNS + " 1");
@@ -590,7 +589,8 @@ public final class CompactLabourReport extends ReportPanel {
}
private JLabel createNonCountedLabel(int otherAmateurs) {
- JLabel label = createNumberLabel(otherAmateurs, "report.labour.notCounted.tooltip");
+ JLabel label = createNumberLabel(otherAmateurs,
+ "report.labour.notCounted.tooltip");
label.setForeground(Color.GRAY);
return label;
}
@@ -603,13 +603,11 @@ public final class CompactLabourReport extends ReportPanel {
return label;
}
- private JButton createUnitNameButton(String name, final LabourData.UnitData unitData) {
- JButton button = createButton(name, new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
+ private JButton createUnitNameButton(String name,
+ LabourData.UnitData unitData) {
+ JButton button = createButton(name, (ActionEvent ae) -> {
getGUI().showCompactLabourReport(unitData);
- }
- });
+ });
if (!unitData.isSummary()) {
button.setIcon(new ImageIcon(
@@ -620,18 +618,23 @@ public final class CompactLabourReport extends ReportPanel {
}
private GoodsType getGoodsType() {
- return isSummary() ? null : unitData.getUnitType().getExpertProduction();
+ return (isSummary()) ? null
+ : unitData.getUnitType().getExpertProduction();
}
/**
- * @return if this is the location summary, grouped by unit type
+ * Is this an overview/location summary?
+ *
+ * @return True if this is the location summary.
*/
private boolean isOverview() {
return unitData == null;
}
/**
- * @return if we are any summary
+ * Is this a summary?
+ *
+ * @return True if this is any sort of summary.
*/
private boolean isSummary() {
return isOverview() || unitData.isSummary();
diff --git a/src/net/sf/freecol/client/gui/panel/ConceptDetailPanel.java b/src/net/sf/freecol/client/gui/panel/ConceptDetailPanel.java
index 598da6f62..db500e80d 100644
--- a/src/net/sf/freecol/client/gui/panel/ConceptDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ConceptDetailPanel.java
@@ -30,6 +30,7 @@ import java.util.List;
import javax.swing.JEditorPane;
import javax.swing.JLabel;
import javax.swing.JPanel;
+import javax.swing.SwingConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import net.miginfocom.swing.MigLayout;
@@ -60,13 +61,8 @@ public class ConceptDetailPanel extends FreeColPanel
};
private static final Comparator nodeComparator
- = new Comparator() {
- @Override
- public int compare(DefaultMutableTreeNode node1, DefaultMutableTreeNode node2) {
- return ((ColopediaTreeItem) node1.getUserObject()).getText()
- .compareTo(((ColopediaTreeItem) node2.getUserObject()).getText());
- }
- };
+ = Comparator.comparing(tn ->
+ ((ColopediaTreeItem)tn.getUserObject()).getText());
private ColopediaPanel colopediaPanel;
@@ -89,22 +85,22 @@ public class ConceptDetailPanel extends FreeColPanel
return Messages.getName(id);
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
- DefaultMutableTreeNode node =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, id, getName(), null));
+ DefaultMutableTreeNode node
+ = new DefaultMutableTreeNode(new ColopediaTreeItem(this, id,
+ getName(), null));
List nodes = new ArrayList<>();
for (String concept : concepts) {
String nodeId = "colopedia.concepts." + concept;
String nodeName = Messages.getName(nodeId);
- nodes.add(new DefaultMutableTreeNode(new ColopediaTreeItem(this, nodeId, nodeName, null)));
+ nodes.add(new DefaultMutableTreeNode(new ColopediaTreeItem(this,
+ nodeId, nodeName, null)));
}
Collections.sort(nodes, nodeComparator);
for (DefaultMutableTreeNode n : nodes) {
@@ -114,25 +110,20 @@ public class ConceptDetailPanel extends FreeColPanel
}
/**
- * Builds the details panel for the given identifier.
- *
- * @param id The object identifier to display.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (ConceptDetailPanel.id.equals(id)) {
- return;
- }
+ if (this.id.equals(id)) return;
panel.setLayout(new MigLayout("wrap 1, center"));
- JLabel header = Utility.localizedLabel(Messages.nameKey(id));
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel header = Utility.localizedHeaderLabel(Messages.nameKey(id),
+ SwingConstants.LEADING, FontLibrary.FontSize.SMALL);
panel.add(header, "align center, wrap 20");
- JEditorPane editorPane = new JEditorPane("text/html", Messages.getDescription(id)) {
+ JEditorPane editorPane = new JEditorPane("text/html",
+ Messages.getDescription(id)) {
@Override
public void paintComponent(Graphics g) {
@@ -145,11 +136,9 @@ public class ConceptDetailPanel extends FreeColPanel
graphics2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
*/
-
super.paintComponent(graphics2d);
}
};
-
editorPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES,
Boolean.TRUE);
editorPane.setFont(panel.getFont());
@@ -158,19 +147,5 @@ public class ConceptDetailPanel extends FreeColPanel
editorPane.addHyperlinkListener(colopediaPanel);
panel.add(editorPane, "width 95%");
-
- }
-
- // Override Component
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void removeNotify() {
- super.removeNotify();
-
- removeAll();
- colopediaPanel = null;
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/ConfirmDeclarationDialog.java b/src/net/sf/freecol/client/gui/panel/ConfirmDeclarationDialog.java
index 58ba4c9bf..c974d8429 100644
--- a/src/net/sf/freecol/client/gui/panel/ConfirmDeclarationDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/ConfirmDeclarationDialog.java
@@ -42,7 +42,7 @@ import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.panel.Flag.Background;
import net.sf.freecol.client.gui.panel.Flag.Decoration;
import net.sf.freecol.client.gui.panel.Flag.UnionPosition;
@@ -271,7 +271,7 @@ public class ConfirmDeclarationDialog extends FreeColDialog>
StringTemplate nation = StringTemplate
.template("confirmDeclarationDialog.defaultNation")
- .addStringTemplate("%nation%", player.getNationName());
+ .addStringTemplate("%nation%", player.getNationLabel());
this.nationField = new JTextField(Messages.message(nation), 20);
this.label = new JLabel();
@@ -392,8 +392,8 @@ public class ConfirmDeclarationDialog extends FreeColDialog>
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
- ColorButton button = (ColorButton)e.getSource();
+ public void actionPerformed(ActionEvent ae) {
+ ColorButton button = (ColorButton)ae.getSource();
Color color = JColorChooser.showDialog(this, this.label.getText(),
button.getBackground());
button.setColor(color);
diff --git a/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java b/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java
index 3e4924b94..bb27083ca 100644
--- a/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ConstructionPanel.java
@@ -35,13 +35,15 @@ import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.FontLibrary;
import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.BuildableType;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Turn;
-import static net.sf.freecol.common.util.StringUtils.*;
+
+import static net.sf.freecol.common.util.StringUtils.getBreakingPoint;
/**
@@ -109,7 +111,7 @@ public class ConstructionPanel extends MigPanel
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
- freeColClient.getGUI().showBuildQueuePanel(colony);
+ ((SwingGUI)freeColClient.getGUI()).showBuildQueuePanel(colony);
}
});
}
@@ -132,10 +134,10 @@ public class ConstructionPanel extends MigPanel
public void update(BuildableType buildable) {
removeAll();
- final ImageLibrary lib = freeColClient.getGUI()
- .getColonyTileMapViewer().getImageLibrary();
+ final ImageLibrary lib = ((SwingGUI)freeColClient.getGUI())
+ .getTileImageLibrary();
final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.SMALLER, lib.getScalingFactor());
+ FontLibrary.FontSize.SMALLER, lib.getScaleFactor());
if (buildable == null) {
String clickToBuild = Messages.message(getDefaultLabel());
diff --git a/src/net/sf/freecol/client/gui/panel/DeclarationPanel.java b/src/net/sf/freecol/client/gui/panel/DeclarationPanel.java
index 386450c57..04d4c1687 100644
--- a/src/net/sf/freecol/client/gui/panel/DeclarationPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/DeclarationPanel.java
@@ -95,11 +95,8 @@ public final class DeclarationPanel extends FreeColPanel {
add(signaturePanel);
- Timer t = new Timer(START_DELAY, new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- signaturePanel.startAnimation();
- }
+ Timer t = new Timer(START_DELAY, (ActionEvent ae) -> {
+ signaturePanel.startAnimation();
});
t.setRepeats(false);
t.start();
@@ -112,19 +109,16 @@ public final class DeclarationPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (ANIMATION_STOPPED.equals(command)) {
- Timer t = new Timer(FINISH_DELAY, new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- getGUI().removeFromCanvas(DeclarationPanel.this);
- }
+ Timer t = new Timer(FINISH_DELAY, (x) -> {
+ getGUI().removeFromCanvas(DeclarationPanel.this);
});
t.setRepeats(false);
t.start();
} else {
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
}
@@ -151,7 +145,8 @@ public final class DeclarationPanel extends FreeColPanel {
private final FAFile faFile;
- private final ArrayList actionListeners = new ArrayList<>();
+ private final ArrayList actionListeners
+ = new ArrayList<>();
private Point[] points = null;
@@ -258,22 +253,19 @@ public final class DeclarationPanel extends FreeColPanel {
* @see #addActionListener(ActionListener)
*/
public void startAnimation() {
- ActionListener taskPerformer = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- if (counter < points.length - 1) {
- counter += 20;
- if (counter > points.length) {
- counter = points.length - 1;
- ((Timer) evt.getSource()).stop();
- notifyStopped();
- }
- validate();
- repaint();
- } else {
- ((Timer)evt.getSource()).stop();
+ ActionListener taskPerformer = (ActionEvent ae) -> {
+ if (counter < points.length - 1) {
+ counter += 20;
+ if (counter > points.length) {
+ counter = points.length - 1;
+ ((Timer)ae.getSource()).stop();
notifyStopped();
}
+ validate();
+ repaint();
+ } else {
+ ((Timer)ae.getSource()).stop();
+ notifyStopped();
}
};
new Timer(ANIMATION_DELAY, taskPerformer).start();
diff --git a/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java b/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java
index 7441a93ac..cb1e23196 100644
--- a/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java
+++ b/src/net/sf/freecol/client/gui/panel/DefaultTransferHandler.java
@@ -37,6 +37,7 @@ import java.awt.dnd.DragSourceListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
+import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -48,8 +49,8 @@ import javax.swing.JPanel;
import javax.swing.TransferHandler;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.Goods;
@@ -58,6 +59,7 @@ import net.sf.freecol.common.model.GoodsLocation;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Role;
import net.sf.freecol.common.model.Unit;
+import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -235,7 +237,7 @@ public final class DefaultTransferHandler extends TransferHandler {
private final FreeColClient freeColClient;
- private final GUI gui;
+ private final SwingGUI gui;
private final FreeColPanel parentPanel;
@@ -249,7 +251,7 @@ public final class DefaultTransferHandler extends TransferHandler {
public DefaultTransferHandler(FreeColClient freeColClient,
FreeColPanel parentPanel) {
this.freeColClient = freeColClient;
- this.gui = freeColClient.getGUI();
+ this.gui = (SwingGUI)freeColClient.getGUI();
this.parentPanel = parentPanel;
}
@@ -277,14 +279,8 @@ public final class DefaultTransferHandler extends TransferHandler {
*/
@Override
public boolean canImport(JComponent comp, DataFlavor[] flavor) {
- if (comp instanceof JPanel || comp instanceof JLabel) {
- for (DataFlavor aFlavor : flavor) {
- if (aFlavor.equals(DefaultTransferHandler.flavor)) {
- return true;
- }
- }
- }
- return false;
+ return (comp instanceof JPanel || comp instanceof JLabel)
+ && any(flavor, f -> f.equals(DefaultTransferHandler.flavor));
}
/**
@@ -393,6 +389,7 @@ public final class DefaultTransferHandler extends TransferHandler {
defaultAmount, false);
if (amount <= 0) return false;
goods.setAmount(amount);
+ } else if (label.isFullChosen()) {
} else if (goods.getAmount() > GoodsContainer.CARGO_SIZE) {
goods.setAmount(GoodsContainer.CARGO_SIZE);
}
diff --git a/src/net/sf/freecol/client/gui/panel/DifficultyDialog.java b/src/net/sf/freecol/client/gui/panel/DifficultyDialog.java
index d1423f0e8..6fe88f897 100644
--- a/src/net/sf/freecol/client/gui/panel/DifficultyDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/DifficultyDialog.java
@@ -20,7 +20,6 @@
package net.sf.freecol.client.gui.panel;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.io.File;
import java.util.logging.Logger;
@@ -29,13 +28,14 @@ import javax.swing.JFrame;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileFilter;
+import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.io.FreeColDirectories;
-import net.sf.freecol.common.io.FreeColFileFilter;
+import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.option.OptionGroup;
@@ -50,9 +50,8 @@ public final class DifficultyDialog extends OptionsDialog
private static final Logger logger = Logger.getLogger(DifficultyDialog.class.getName());
- private static final FileFilter[] filters = {
- FreeColFileFilter.freeColXMLFilter
- };
+ /** File filters array to filter for XML files. */
+ private static final FileFilter[] filters = { null };
/** The currently selected subgroup. */
private OptionGroup selected;
@@ -126,11 +125,8 @@ public final class DifficultyDialog extends OptionsDialog
* @param button The JButton
to add the action to.
*/
private void addResetAction(JButton button) {
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- getOptionUI().reset();
- }
+ button.addActionListener((ActionEvent ae) -> {
+ getOptionUI().reset();
});
}
@@ -140,16 +136,14 @@ public final class DifficultyDialog extends OptionsDialog
* @param button The JButton
to add the action to.
*/
private void addLoadAction(JButton button) {
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- File dir = FreeColDirectories.getOptionsDirectory();
- File file = getGUI().showLoadDialog(dir, filters);
- if (file != null && load(file)) {
- invalidate();
- validate();
- repaint();
- }
+ initializeFilters();
+ button.addActionListener((ActionEvent ae) -> {
+ File dir = FreeColDirectories.getOptionsDirectory();
+ File file = getGUI().showLoadDialog(dir, filters);
+ if (file != null && load(file)) {
+ invalidate();
+ validate();
+ repaint();
}
});
}
@@ -160,20 +154,30 @@ public final class DifficultyDialog extends OptionsDialog
* @param button The JButton
to add the action to.
*/
private void addSaveAction(JButton button) {
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- File dir = FreeColDirectories.getOptionsDirectory();
- File file = getGUI().showSaveDialog(dir, filters,
- getDefaultFileName(), ".xml");
- if (file != null) {
- getOptionUI().updateOption();
- save(file);
- }
+ initializeFilters();
+ button.addActionListener((ActionEvent ae) -> {
+ File dir = FreeColDirectories.getOptionsDirectory();
+ File file = getGUI().showSaveDialog(dir, filters,
+ getDefaultFileName());
+ if (file != null) {
+ getOptionUI().updateOption();
+ save(file);
}
});
}
+ /**
+ * Initialize the XML file filter.
+ */
+ private void initializeFilters() {
+ synchronized (filters) {
+ if (filters[0] == null) {
+ String desc = Messages.message("filter.xml");
+ filters[0] = new FileNameExtensionFilter(desc, "xml");
+ }
+ }
+ }
+
// Implement TreeSelectionListener
diff --git a/src/net/sf/freecol/client/gui/panel/DragListener.java b/src/net/sf/freecol/client/gui/panel/DragListener.java
index d9ead3167..084292395 100644
--- a/src/net/sf/freecol/client/gui/panel/DragListener.java
+++ b/src/net/sf/freecol/client/gui/panel/DragListener.java
@@ -29,7 +29,7 @@ import javax.swing.JPopupMenu;
import javax.swing.TransferHandler;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.model.Unit;
@@ -89,7 +89,7 @@ public final class DragListener extends MouseAdapter {
menu.remove(lastIdx);
if (menu.getComponentCount() <= 0) return;
- final GUI gui = freeColClient.getGUI();
+ final SwingGUI gui = (SwingGUI)freeColClient.getGUI();
boolean windows = System.getProperty("os.name").startsWith("Windows");
boolean small = Toolkit.getDefaultToolkit()
.getScreenSize().getHeight() < 768;
@@ -112,6 +112,8 @@ public final class DragListener extends MouseAdapter {
AbstractGoodsLabel label = (AbstractGoodsLabel)comp;
if (e.isShiftDown()) {
label.setPartialChosen(true);
+ } else if (e.isControlDown()) {
+ label.setFullChosen(true);
} else {
label.setPartialChosen(false);
label.setDefaultAmount();
diff --git a/src/net/sf/freecol/client/gui/panel/DumpCargoDialog.java b/src/net/sf/freecol/client/gui/panel/DumpCargoDialog.java
index 64d87cd64..af9b45f4a 100644
--- a/src/net/sf/freecol/client/gui/panel/DumpCargoDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/DumpCargoDialog.java
@@ -30,6 +30,7 @@ import javax.swing.JFrame;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.Unit;
diff --git a/src/net/sf/freecol/client/gui/panel/EditSettlementDialog.java b/src/net/sf/freecol/client/gui/panel/EditSettlementDialog.java
index 6def7e01b..223c717c3 100644
--- a/src/net/sf/freecol/client/gui/panel/EditSettlementDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/EditSettlementDialog.java
@@ -37,7 +37,8 @@ import javax.swing.SpinnerNumberModel;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.ChoiceItem;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.client.gui.plaf.FreeColComboBoxRenderer;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.IndianNationType;
@@ -49,6 +50,7 @@ import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.RandomChoice;
import net.sf.freecol.server.model.ServerUnit;
@@ -151,11 +153,9 @@ public final class EditSettlementDialog extends FreeColDialog
}
private Player getOwnerPlayer() {
- Nation n = getOwnerNation();
- for (Player player : settlement.getGame().getLivePlayers(null)) {
- if (player.getNationId().equals(n.getId())) return player;
- }
- return null;
+ final Nation n = getOwnerNation();
+ return find(settlement.getGame().getLivePlayers(null),
+ p -> p.getNationId().equals(n.getId()));
}
private SettlementType getSettlementType() {
@@ -205,7 +205,7 @@ public final class EditSettlementDialog extends FreeColDialog
@Override
public IndianSettlement getResponse() {
final Specification spec = freeColClient.getGame().getSpecification();
- final GUI gui = freeColClient.getGUI();
+ final SwingGUI gui = getGUI();
IndianSettlement ret = null;
Set tiles = settlement.getOwnedTiles();
Object value = getValue();
@@ -263,8 +263,8 @@ public final class EditSettlementDialog extends FreeColDialog
ret = settlement;
} else if (options.get(1).equals(value)) {
- if (!getGUI().confirm("editSettlementDialog.removeSettlement.text",
- "ok", "cancel")) {
+ if (!gui.confirm("editSettlementDialog.removeSettlement.text",
+ "ok", "cancel")) {
return settlement;
}
// Dispose of units and settlement on tile
diff --git a/src/net/sf/freecol/client/gui/panel/EmigrationDialog.java b/src/net/sf/freecol/client/gui/panel/EmigrationDialog.java
index 8355357f0..edf5f227b 100644
--- a/src/net/sf/freecol/client/gui/panel/EmigrationDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/EmigrationDialog.java
@@ -29,6 +29,7 @@ import javax.swing.JTextArea;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Europe;
diff --git a/src/net/sf/freecol/client/gui/panel/EndTurnDialog.java b/src/net/sf/freecol/client/gui/panel/EndTurnDialog.java
index 6b17190cb..f3f0a6a16 100644
--- a/src/net/sf/freecol/client/gui/panel/EndTurnDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/EndTurnDialog.java
@@ -165,7 +165,7 @@ public final class EndTurnDialog extends FreeColConfirmDialog {
"select");
this.unitList.getActionMap().put("select", new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
selectUnit();
}
});
@@ -173,7 +173,7 @@ public final class EndTurnDialog extends FreeColConfirmDialog {
"quit");
this.unitList.getActionMap().put("quit", new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
EndTurnDialog.this.setValue(options.get(1));
}
});
diff --git a/src/net/sf/freecol/client/gui/panel/ErrorPanel.java b/src/net/sf/freecol/client/gui/panel/ErrorPanel.java
index 05d809799..939a478c6 100644
--- a/src/net/sf/freecol/client/gui/panel/ErrorPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ErrorPanel.java
@@ -105,12 +105,12 @@ public final class ErrorPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (SHOW.equals(command)) {
getGUI().showLogFilePanel();
} else {
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/EuropePanel.java b/src/net/sf/freecol/client/gui/panel/EuropePanel.java
index 849b49c1e..b38c97d3f 100644
--- a/src/net/sf/freecol/client/gui/panel/EuropePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/EuropePanel.java
@@ -49,8 +49,6 @@ import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.InGameController.BoycottAction;
-import net.sf.freecol.client.gui.Canvas;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Europe;
@@ -183,7 +181,7 @@ public final class EuropePanel extends PortPanel {
&& unit.hasSpaceLeft()) {
StringTemplate locName = destination
.getLocationLabelFor(unit.getOwner());
- if (!getGUI().confirm(true, null, StringTemplate
+ if (!getGUI().confirm(null, StringTemplate
.template("europePanel.leaveColonists")
.addStringTemplate("%newWorld%", locName),
unit, "ok", "cancel")) return null;
@@ -568,9 +566,9 @@ public final class EuropePanel extends PortPanel {
* The constructor for a EuropePanel.
*
* @param freeColClient The FreeColClient
for the game.
- * @param canvas The enclosing Canvas
.
+ * @param header True when a header should be added.
*/
- public EuropePanel(FreeColClient freeColClient, Canvas canvas) {
+ public EuropePanel(FreeColClient freeColClient, boolean header) {
super(freeColClient, new MigLayout("wrap 3, fill",
"[30%:][30%:][15%:]"));
@@ -678,7 +676,7 @@ public final class EuropePanel extends PortPanel {
initialize(europe);
- if (canvas.getHeight() > 780) {
+ if(header) {
add(Utility.localizedHeader(europe.getNameKey(), false),
"span, top, center");
}
@@ -699,7 +697,7 @@ public final class EuropePanel extends PortPanel {
setSelectedUnitLabel(null);
- float scale = getImageLibrary().getScalingFactor();
+ float scale = getImageLibrary().getScaleFactor();
getGUI().restoreSavedSize(this, 200 + (int)(scale*850), 200 + (int)(scale*525));
}
@@ -839,8 +837,8 @@ public final class EuropePanel extends PortPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
EuropeAction act = EuropeAction.valueOf(command);
switch (act) {
case EXIT:
@@ -862,7 +860,7 @@ public final class EuropePanel extends PortPanel {
unloadAction();
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/EventPanel.java b/src/net/sf/freecol/client/gui/panel/EventPanel.java
index b853aa6c2..911c2f339 100644
--- a/src/net/sf/freecol/client/gui/panel/EventPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/EventPanel.java
@@ -52,8 +52,8 @@ public final class EventPanel extends FreeColPanel {
super(freeColClient, new MigLayout("wrap 1", "[center]", "[]20"));
JLabel headerLabel = new JLabel(header);
- headerLabel.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.MEDIUM));
+ headerLabel.setFont(FontLibrary.createCompatibleFont(header,
+ FontLibrary.FontType.HEADER, FontLibrary.FontSize.MEDIUM));
JLabel imageLabel
= new JLabel(new ImageIcon(ResourceManager.getImage(key)));
diff --git a/src/net/sf/freecol/client/gui/panel/FatherDetailPanel.java b/src/net/sf/freecol/client/gui/panel/FatherDetailPanel.java
index a03967eb2..f698c9758 100644
--- a/src/net/sf/freecol/client/gui/panel/FatherDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/FatherDetailPanel.java
@@ -29,6 +29,7 @@ import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
+import javax.swing.SwingConstants;
import javax.swing.tree.DefaultMutableTreeNode;
import net.miginfocom.swing.MigLayout;
@@ -40,6 +41,7 @@ import net.sf.freecol.client.gui.action.ColopediaAction.PanelType;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.FoundingFather.FoundingFatherType;
+import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Turn;
import net.sf.freecol.common.resources.ResourceManager;
@@ -64,33 +66,33 @@ public class FatherDetailPanel
}
+ // Implelement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
- DefaultMutableTreeNode parent =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(), getName(), null));
+ final Specification spec = getSpecification();
+ DefaultMutableTreeNode parent
+ = new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(),
+ getName(), null));
- EnumMap> fathersByType =
- new EnumMap<>(FoundingFatherType.class);
+ EnumMap> fathersByType
+ = new EnumMap<>(FoundingFatherType.class);
for (FoundingFatherType fatherType : FoundingFatherType.values()) {
fathersByType.put(fatherType, new ArrayList());
}
- for (FoundingFather foundingFather : getSpecification().getFoundingFathers()) {
+ for (FoundingFather foundingFather : spec.getFoundingFathers()) {
fathersByType.get(foundingFather.getType()).add(foundingFather);
}
ImageIcon icon = new ImageIcon(ImageLibrary.getMiscImage(ImageLibrary.BELLS, ImageLibrary.ICON_SIZE));
for (FoundingFatherType fatherType : FoundingFatherType.values()) {
String id = FoundingFather.getTypeKey(fatherType);
String typeName = Messages.message(id);
- DefaultMutableTreeNode node =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, id, typeName, null));
-
+ DefaultMutableTreeNode node
+ = new DefaultMutableTreeNode(new ColopediaTreeItem(this, id,
+ typeName, null));
parent.add(node);
for (FoundingFather father : fathersByType.get(fatherType)) {
node.add(buildItem(father, icon));
@@ -100,11 +102,7 @@ public class FatherDetailPanel
}
/**
- * Builds the details panel for the FoundingFather with the given
- * identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
@@ -114,15 +112,16 @@ public class FatherDetailPanel
} catch (IllegalArgumentException e) {
// this is not a founding father
panel.setLayout(new MigLayout("wrap 1, align center", "align center"));
- JLabel header = Utility.localizedLabel(Messages.nameKey(id));
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
- panel.add(header, "align center, wrap 20");
if (getId().equals(id)) {
+ JLabel header = Utility.localizedHeaderLabel(Messages.nameKey(id),
+ SwingConstants.LEADING, FontLibrary.FontSize.SMALL);
+ panel.add(header, "align center, wrap 20");
panel.add(Utility.localizedTextArea("colopedia.foundingFather.description", 40));
} else {
+ JLabel header = Utility.localizedHeaderLabel(Messages.message(id),
+ SwingConstants.LEADING, FontLibrary.FontSize.SMALL);
+ panel.add(header, "align center, wrap 20");
Image image = ResourceManager.getImage("image.flavor." + id);
- header.setText(Messages.message(id));
panel.add(new JLabel(new ImageIcon(image)));
}
}
@@ -139,9 +138,10 @@ public class FatherDetailPanel
String name = Messages.getName(father);
String type = Messages.message(father.getTypeKey());
- JLabel header = new JLabel(name + " (" + type + ")");
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ String text = name + " (" + type + ")";
+ JLabel header = new JLabel(text);
+ header.setFont(FontLibrary.createCompatibleFont(text,
+ FontLibrary.FontType.HEADER, FontLibrary.FontSize.SMALL));
Image image = ImageLibrary.getFoundingFatherImage(father, false);
JLabel label = new JLabel(new ImageIcon(image));
diff --git a/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java b/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
index 30a3d3aa2..ec9a09edf 100644
--- a/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/FindSettlementPanel.java
@@ -76,7 +76,7 @@ public final class FindSettlementPanel extends FreeColPanel
.addName("%name%", value.getName())
.addName("%capital%", ((value.isCapital()) ? "*" : ""))
.addStringTemplate("%nation%",
- value.getOwner().getNationName());
+ value.getOwner().getNationLabel());
label.setText(Messages.message(template));
label.setIcon(new ImageIcon(ImageLibrary.getSettlementImage(value,
new Dimension(64, -1))));
@@ -111,7 +111,7 @@ public final class FindSettlementPanel extends FreeColPanel
this.settlementList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Action selectAction = new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
selectSettlement();
}
};
@@ -120,7 +120,7 @@ public final class FindSettlementPanel extends FreeColPanel
this.settlementList.getActionMap().put("select", selectAction);
Action quitAction = new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().removeFromCanvas(FindSettlementPanel.this);
}
};
diff --git a/src/net/sf/freecol/client/gui/panel/FirstContactDialog.java b/src/net/sf/freecol/client/gui/panel/FirstContactDialog.java
index 08bd079a6..362d51e23 100644
--- a/src/net/sf/freecol/client/gui/panel/FirstContactDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/FirstContactDialog.java
@@ -23,6 +23,7 @@ import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
+import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
@@ -64,18 +65,19 @@ public class FirstContactDialog extends FreeColConfirmDialog {
MigPanel panel
= new MigPanel(new MigLayout("wrap 1", "[center]", "[]20"));
+ panel.setOpaque(false);
- String headerKey = BASE_KEY + other.getNationNameKey();
- String imageKey = IMAGE_BASE_KEY + other.getNationNameKey();
+ String headerKey = BASE_KEY + other.getNation().getSuffix();
+ String imageKey = IMAGE_BASE_KEY + other.getNationResourceKey();
if (!Messages.containsKey(headerKey)) {
headerKey = BASE_KEY + NATIVES_KEY;
imageKey = IMAGE_BASE_KEY + NATIVES_KEY;
}
- JLabel header = Utility.localizedLabel(headerKey);
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.MEDIUM));
+ JLabel header = Utility.localizedHeaderLabel(headerKey,
+ SwingConstants.LEADING, FontLibrary.FontSize.MEDIUM);
JLabel image
= new JLabel(new ImageIcon(ResourceManager.getImage(imageKey)));
+ image.setOpaque(false);
JTextArea tutorial = null;
if (!player.hasContactedIndians() && freeColClient.tutorialMode()) {
@@ -89,7 +91,7 @@ public class FirstContactDialog extends FreeColConfirmDialog {
.getSettlementTypeKey(true);
JTextArea text = Utility.localizedTextArea(StringTemplate
.template(messageId)
- .addStringTemplate("%nation%", other.getNationName())
+ .addStringTemplate("%nation%", other.getNationLabel())
.addName("%camps%", Integer.toString(settlementCount))
.add("%settlementType%", type));
diff --git a/src/net/sf/freecol/client/gui/panel/FreeColChoiceDialog.java b/src/net/sf/freecol/client/gui/panel/FreeColChoiceDialog.java
index ce334ccea..565c639c7 100644
--- a/src/net/sf/freecol/client/gui/panel/FreeColChoiceDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/FreeColChoiceDialog.java
@@ -25,6 +25,7 @@ import javax.swing.ImageIcon;
import javax.swing.JFrame;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
diff --git a/src/net/sf/freecol/client/gui/panel/FreeColConfirmDialog.java b/src/net/sf/freecol/client/gui/panel/FreeColConfirmDialog.java
index 103fc80e9..1a4152de3 100644
--- a/src/net/sf/freecol/client/gui/panel/FreeColConfirmDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/FreeColConfirmDialog.java
@@ -25,6 +25,7 @@ import javax.swing.ImageIcon;
import javax.swing.JFrame;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
diff --git a/src/net/sf/freecol/client/gui/panel/FreeColDialog.java b/src/net/sf/freecol/client/gui/panel/FreeColDialog.java
index d75bc8fbe..c4df42e99 100644
--- a/src/net/sf/freecol/client/gui/panel/FreeColDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/FreeColDialog.java
@@ -37,17 +37,21 @@ import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
+import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
+import javax.swing.JLabel;
import javax.swing.JOptionPane;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.InGameController;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.client.gui.plaf.FreeColOptionPaneUI;
-import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Specification;
@@ -141,11 +145,7 @@ public class FreeColDialog extends JDialog implements PropertyChangeListener
* @return An array of enabled options.
*/
private Object[] selectOptions() {
- List> actual = new ArrayList<>();
- for (ChoiceItem c : this.options) {
- if (c.isEnabled()) actual.add(c);
- }
- return actual.toArray();
+ return this.options.stream().filter(ChoiceItem::isEnabled).toArray();
}
/**
@@ -173,11 +173,14 @@ public class FreeColDialog extends JDialog implements PropertyChangeListener
int def = selectDefault(options);
ChoiceItem ci = (def >= 0) ? options.get(def) : null;
if (obj instanceof StringTemplate) {
- obj = Messages.message((StringTemplate)obj);
+ obj = Utility.localizedTextArea((StringTemplate)obj);
+ } else if(obj instanceof String) {
+ obj = Utility.getDefaultTextArea((String)obj);
}
this.pane = new JOptionPane(obj, paneType, JOptionPane.DEFAULT_OPTION,
icon, selectOptions(), ci);
this.pane.setBorder(Utility.DIALOG_BORDER);
+ this.pane.setOpaque(false);
this.pane.setName("FreeColDialog");
this.pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
this.pane.addPropertyChangeListener(this);
@@ -190,6 +193,8 @@ public class FreeColDialog extends JDialog implements PropertyChangeListener
setResizable(false);
setUndecorated(true);
setModal(modal);
+
+ setSubcomponentsNotOpaque(this.pane);
try { // Layout failures might not get logged.
pack();
} catch (Exception e) {
@@ -257,6 +262,36 @@ public class FreeColDialog extends JDialog implements PropertyChangeListener
});
}
+ public static void setSubcomponentsNotOpaque(JComponent j) {
+ synchronized(j.getTreeLock()) {
+ iterateOverOpaqueLayersComponents(j);
+ }
+ }
+
+ private static void iterateOverOpaqueLayersComponents(JComponent j){
+ if (j instanceof JPanel || j instanceof JOptionPane) {
+ Component[] componentes = j.getComponents();
+ for (Component componente : componentes) {
+ setOpaqueLayerRecursive(componente);
+ }
+ }
+ }
+
+ private static void setOpaqueLayerRecursive(Component opaqueComponent) {
+ if (opaqueComponent instanceof JTextArea ||
+ opaqueComponent instanceof JLabel) {
+ if (opaqueComponent.isOpaque()) {
+ ((JComponent) opaqueComponent).setOpaque(false);
+ }
+ } else if (opaqueComponent instanceof JPanel) {
+ JComponent panel = (JComponent)opaqueComponent;
+ if (panel.isOpaque()) {
+ panel.setOpaque(false);
+ }
+ iterateOverOpaqueLayersComponents(panel);
+ }
+ }
+
/**
* Get the FreeColClient.
*
@@ -271,8 +306,8 @@ public class FreeColDialog extends JDialog implements PropertyChangeListener
*
* @return The GUI
.
*/
- protected GUI getGUI() {
- return freeColClient.getGUI();
+ protected SwingGUI getGUI() {
+ return (SwingGUI)freeColClient.getGUI();
}
/**
@@ -428,7 +463,7 @@ public class FreeColDialog extends JDialog implements PropertyChangeListener
public void removeNotify() {
super.removeNotify();
- freeColClient.getGUI().dialogRemove(FreeColDialog.this);
+ getGUI().dialogRemove(FreeColDialog.this);
removeAll();
if (this.pane != null) {
diff --git a/src/net/sf/freecol/client/gui/panel/FreeColInputDialog.java b/src/net/sf/freecol/client/gui/panel/FreeColInputDialog.java
index 3083e03e9..fcc6460d4 100644
--- a/src/net/sf/freecol/client/gui/panel/FreeColInputDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/FreeColInputDialog.java
@@ -19,14 +19,14 @@
package net.sf.freecol.client.gui.panel;
-import javax.swing.ImageIcon;
-
import java.util.List;
import java.util.logging.Logger;
+import javax.swing.ImageIcon;
import javax.swing.JFrame;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
diff --git a/src/net/sf/freecol/client/gui/panel/FreeColPanel.java b/src/net/sf/freecol/client/gui/panel/FreeColPanel.java
index 16d04e250..faa7e0f3a 100644
--- a/src/net/sf/freecol/client/gui/panel/FreeColPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/FreeColPanel.java
@@ -39,8 +39,8 @@ import javax.swing.KeyStroke;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.InGameController;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.Player;
@@ -128,8 +128,8 @@ public abstract class FreeColPanel extends MigPanel implements ActionListener {
*
* @return The current GUI
.
*/
- protected GUI getGUI() {
- return freeColClient.getGUI();
+ protected SwingGUI getGUI() {
+ return (SwingGUI)freeColClient.getGUI();
}
/**
@@ -220,6 +220,7 @@ public abstract class FreeColPanel extends MigPanel implements ActionListener {
public void propertyChange(PropertyChangeEvent e) {
if ("closing".equals(e.getPropertyName())) {
runnable.run();
+ // Lambda unsuitable due to use of "this"
FreeColPanel.this.removePropertyChangeListener(this);
}
}
@@ -232,8 +233,8 @@ public abstract class FreeColPanel extends MigPanel implements ActionListener {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (OK.equals(command)) {
getGUI().removeFromCanvas(this);
} else {
diff --git a/src/net/sf/freecol/client/gui/panel/FreeColStringInputDialog.java b/src/net/sf/freecol/client/gui/panel/FreeColStringInputDialog.java
index 53f6362e1..a47a5dd47 100644
--- a/src/net/sf/freecol/client/gui/panel/FreeColStringInputDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/FreeColStringInputDialog.java
@@ -54,12 +54,14 @@ public final class FreeColStringInputDialog extends FreeColInputDialog {
super(freeColClient, frame);
textField = new JTextField(defaultValue);
+ textField.setOpaque(false);
JPanel panel = new JPanel(new BorderLayout()) {
@Override
public void requestFocus() {
textField.requestFocus();
}
};
+ panel.setOpaque(false);
panel.add(Utility.getDefaultTextArea(text));
panel.add(textField, BorderLayout.SOUTH);
diff --git a/src/net/sf/freecol/client/gui/panel/GoodsDetailPanel.java b/src/net/sf/freecol/client/gui/panel/GoodsDetailPanel.java
index 2cd3ce340..4036e8098 100644
--- a/src/net/sf/freecol/client/gui/panel/GoodsDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/GoodsDetailPanel.java
@@ -63,12 +63,10 @@ public class GoodsDetailPanel extends ColopediaGameObjectTypePanel {
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
@@ -76,23 +74,16 @@ public class GoodsDetailPanel extends ColopediaGameObjectTypePanel {
}
/**
- * Builds the details panel for the GoodsType with the given identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (getId().equals(id)) {
- return;
- }
+ if (getId().equals(id)) return;
GoodsType type = getSpecification().getGoodsType(id);
panel.setLayout(new MigLayout("wrap 4", "[]20[]"));
- JLabel name = Utility.localizedLabel(type);
- name.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel name = Utility.localizedHeaderLabel(type, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
if (type.isFarmed()) {
@@ -217,17 +208,16 @@ public class GoodsDetailPanel extends ColopediaGameObjectTypePanel {
}
- private boolean filterBuildables(List input, List output, GoodsType type) {
+ private boolean filterBuildables(List input,
+ List output, GoodsType type) {
boolean result = true;
- for (T buildableType : input) {
- if (buildableType.needsGoodsToBuild()) {
- AbstractGoods goods = AbstractGoods.findByType(type,
- buildableType.getRequiredGoods());
- if (goods != null) {
- output.add(buildableType);
- continue;
+ for (T bt : input) {
+ if (bt.needsGoodsToBuild()) {
+ if (AbstractGoods.containsType(type, bt.getRequiredGoods())) {
+ output.add(bt);
+ } else {
+ result = false;
}
- result = false;
}
}
return result;
diff --git a/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java b/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java
index afd4b5c58..07b7f7009 100644
--- a/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/IndianSettlementPanel.java
@@ -71,7 +71,7 @@ public final class IndianSettlementPanel extends FreeColPanel {
.template(settlement.isCapital()
? "indianSettlementPanel.indianCapital"
: "indianSettlementPanel.indianSettlement")
- .addStringTemplate("%nation%", indian.getNationName()));
+ .addStringTemplate("%nation%", indian.getNationLabel()));
Tension tension = settlement.getAlarm(player);
if (tension != null) text += " (" + Messages.getName(tension) + ")";
if (settlement.worthScouting(player)) {
diff --git a/src/net/sf/freecol/client/gui/panel/InfoPanel.java b/src/net/sf/freecol/client/gui/panel/InfoPanel.java
index a30637022..46b804f74 100644
--- a/src/net/sf/freecol/client/gui/panel/InfoPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/InfoPanel.java
@@ -44,21 +44,20 @@ import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.FontLibrary;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
-import net.sf.freecol.client.gui.MapViewer;
import net.sf.freecol.client.gui.action.EndTurnAction;
import net.sf.freecol.client.gui.panel.MapEditorTransformPanel.MapTransform;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
-import net.sf.freecol.common.model.Modifier;
+import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
-import net.sf.freecol.common.model.TileImprovement;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.resources.ResourceManager;
-import static net.sf.freecol.common.util.StringUtils.*;
+
+import static net.sf.freecol.common.util.StringUtils.splitText;
/**
@@ -88,10 +87,9 @@ public final class InfoPanel extends FreeColPanel {
public EndTurnPanel() {
super(new MigLayout("wrap 1, center", "[center]", ""));
- final ImageLibrary lib = getGUI().getColonyTileMapViewer()
- .getImageLibrary();
+ final ImageLibrary lib = getGUI().getTileImageLibrary();
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor());
+ FontLibrary.FontSize.TINY, lib.getScaleFactor());
String labelString = Messages.message("infoPanel.endTurn");
for (String s : splitText(labelString, " /",
@@ -144,18 +142,12 @@ public final class InfoPanel extends FreeColPanel {
removeAll();
- final MapViewer mapViewer = getGUI().getColonyTileMapViewer();
- final ImageLibrary lib = mapViewer.getImageLibrary();
+ final ImageLibrary lib = getGUI().getTileImageLibrary();
final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor());
- if (tile != null && tile.getType() != null) {
+ FontLibrary.FontSize.TINY, lib.getScaleFactor());
+ if (tile != null) {
final int width = getWidth() - SLACK;
- List production = tile.getType()
- .getPossibleProduction(true);
- if (production.size() > PRODUCTION) {
- production = production.subList(0, PRODUCTION);
- }
- BufferedImage image = mapViewer.createTileImageWithBeachBorderAndItems(tile);
+ BufferedImage image = getGUI().createTileImageWithBeachBorderAndItems(tile);
if (tile.isExplored()) {
String text = Messages.message(tile.getLabel());
for (String s : splitText(text, " /",
@@ -168,8 +160,10 @@ public final class InfoPanel extends FreeColPanel {
add(new JLabel(new ImageIcon(image)), "spany");
final Player owner = tile.getOwner();
- if (owner != null) {
- StringTemplate t = owner.getNationName();
+ if (owner == null) {
+ add(new JLabel(), "span " + PRODUCTION);
+ } else {
+ StringTemplate t = owner.getNationLabel();
add(Utility.localizedLabel(t), "span " + PRODUCTION);
}
@@ -187,16 +181,21 @@ public final class InfoPanel extends FreeColPanel {
List produce = tile.getType()
.getPossibleProduction(true);
- Collections.sort(produce,
- AbstractGoods.abstractGoodsComparator);
- for (AbstractGoods goods : produce) {
- JLabel goodsLabel = new JLabel(
- String.valueOf(tile.getPotentialProduction(goods.getType(), null)),
- new ImageIcon(lib.getSmallIconImage(goods.getType())),
- JLabel.RIGHT);
- goodsLabel.setToolTipText(Messages.getName(goods.getType()));
- goodsLabel.setFont(font);
- add(goodsLabel);
+ if (produce.isEmpty()) {
+ add(new JLabel(), "span " + PRODUCTION);
+ } else {
+ Collections.sort(produce,
+ AbstractGoods.abstractGoodsComparator);
+ for (AbstractGoods ag : produce) {
+ GoodsType type = ag.getType();
+ int n = tile.getPotentialProduction(type, null);
+ JLabel label = new JLabel(String.valueOf(n),
+ new ImageIcon(lib.getSmallIconImage(type)),
+ JLabel.RIGHT);
+ label.setToolTipText(Messages.getName(type));
+ label.setFont(font);
+ add(label);
+ }
}
} else {
add(Utility.localizedLabel("unexplored"),
@@ -234,7 +233,7 @@ public final class InfoPanel extends FreeColPanel {
* Create a new unit information panel.
*/
public UnitInfoPanel() {
- super(new MigLayout("wrap 6, fill, gap 0 0", "", ""));
+ super(new MigLayout("wrap 5, fill, gap 0 0", "", ""));
setSize(260, 130);
setOpaque(false);
@@ -267,9 +266,17 @@ public final class InfoPanel extends FreeColPanel {
GoodsContainer gc = unit.getGoodsContainer();
if (gc != null) gc.addPropertyChangeListener(this);
}
+ logger.info("Switching UnitInfoPanel from " +
+ (this.unit == null ? "null" :
+ (this.unit.getId() + " " + this.unit.getDescription() +
+ " " + this.unit.getMovesAsString())) +
+ " to " +
+ (unit == null ? "null" :
+ (unit.getId() + " " + unit.getDescription() +
+ " " + unit.getMovesAsString())));
this.unit = unit;
- update();
}
+ update();
}
/**
@@ -278,10 +285,9 @@ public final class InfoPanel extends FreeColPanel {
public void update() {
removeAll();
- final ImageLibrary lib = getGUI().getColonyTileMapViewer()
- .getImageLibrary();
+ final ImageLibrary lib = getGUI().getTileImageLibrary();
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor());
+ FontLibrary.FontSize.TINY, lib.getScaleFactor());
String text;
JLabel textLabel;
if (unit != null) {
@@ -309,8 +315,17 @@ public final class InfoPanel extends FreeColPanel {
ImageIcon icon;
JLabel label;
for (Goods goods : unit.getGoodsList()) {
- icon = new ImageIcon(lib.getSmallIconImage(goods.getType()));
- label = new JLabel(icon);
+ int amount = goods.getAmount();
+ GoodsType gt = goods.getType();
+ // FIXME: Get size of full stack from appropriate place.
+ if(amount == 100) {
+ icon = new ImageIcon(lib.getIconImage(gt));
+ label = new JLabel(icon);
+ } else {
+ icon = new ImageIcon(lib.getSmallIconImage(gt));
+ label = new JLabel(String.valueOf(amount),
+ icon, JLabel.RIGHT);
+ }
text = Messages.message(goods.getLabel(true));
label.setFont(font);
label.setToolTipText(text);
@@ -434,17 +449,15 @@ public final class InfoPanel extends FreeColPanel {
* @return The panel mode.
*/
private InfoPanelMode getMode() {
- Player player;
return (getFreeColClient().isMapEditor())
? InfoPanelMode.MAP
: (getGUI().getViewMode() == GUI.VIEW_TERRAIN_MODE)
? InfoPanelMode.TILE
: (unitInfoPanel.hasUnit())
? InfoPanelMode.UNIT
- : ((player = getFreeColClient().getMyPlayer()) != null
- && !player.hasNextActiveUnit())
- ? InfoPanelMode.END
- : InfoPanelMode.NONE;
+ : (getFreeColClient().getMyPlayer() == null)
+ ? InfoPanelMode.NONE
+ : InfoPanelMode.END;
}
/**
@@ -496,7 +509,13 @@ public final class InfoPanel extends FreeColPanel {
*/
public void update() {
InfoPanelMode newMode = getMode();
+ if(newMode == InfoPanelMode.END &&
+ getFreeColClient().getMyPlayer().hasNextActiveUnit()) {
+ logger.warning("Inconsistent InfoPanel status");
+ }
if (this.mode != newMode) {
+ logger.info("Switching InfoPanel mode from " + mode +
+ " to " + newMode);
switch (this.mode = newMode) {
case END:
this.mapEditorPanel.setVisible(false);
diff --git a/src/net/sf/freecol/client/gui/panel/InformationPanel.java b/src/net/sf/freecol/client/gui/panel/InformationPanel.java
index 075869f74..2e1d7a9b5 100644
--- a/src/net/sf/freecol/client/gui/panel/InformationPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/InformationPanel.java
@@ -22,7 +22,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
@@ -33,7 +32,7 @@ import javax.swing.JScrollPane;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.StringTemplate;
@@ -75,7 +74,7 @@ public class InformationPanel extends FreeColPanel {
super(freeColClient, new MigLayout("wrap 1, insets 200 10 10 10",
"[510]", "[242]20[20]"));
- final GUI gui = getGUI();
+ final SwingGUI gui = getGUI();
JPanel textPanel = new MigPanel();
textPanel.setOpaque(false);
textPanel.setLayout(new MigLayout("wrap 2", "", "top"));
@@ -94,11 +93,8 @@ public class InformationPanel extends FreeColPanel {
.template("informationPanel.display")
.addStringTemplate("%object%", disp));
final FreeColObject fco = fcos[i];
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- gui.displayObject(fco);
- }
+ button.addActionListener((ActionEvent ae) -> {
+ gui.displayObject(fco);
});
textPanel.add(button, "skip");
}
diff --git a/src/net/sf/freecol/client/gui/panel/LabourData.java b/src/net/sf/freecol/client/gui/panel/LabourData.java
index 21eca2446..b5da7c793 100644
--- a/src/net/sf/freecol/client/gui/panel/LabourData.java
+++ b/src/net/sf/freecol/client/gui/panel/LabourData.java
@@ -19,11 +19,11 @@
package net.sf.freecol.client.gui.panel;
-import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.i18n.Messages;
@@ -451,14 +451,9 @@ public class LabourData {
}
public static List getLabourTypes(Player player) {
- List unitTypes = player.getSpecification().getUnitTypeList();
- ArrayList labourTypes = new ArrayList<>();
- for (UnitType unitType : unitTypes) {
- if (unitType.hasSkill() && unitType.isAvailableTo(player)) {
- labourTypes.add(unitType);
- }
- }
- return labourTypes;
+ return player.getSpecification().getUnitTypeList().stream()
+ .filter(ut -> ut.hasSkill() && ut.isAvailableTo(player))
+ .collect(Collectors.toList());
}
private void summarize() {
diff --git a/src/net/sf/freecol/client/gui/panel/LoadDialog.java b/src/net/sf/freecol/client/gui/panel/LoadDialog.java
index 0d5cfd3d0..ab76981b8 100644
--- a/src/net/sf/freecol/client/gui/panel/LoadDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/LoadDialog.java
@@ -20,15 +20,15 @@
package net.sf.freecol.client.gui.panel;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.io.File;
import java.util.List;
-import javax.swing.filechooser.FileFilter;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
+import javax.swing.filechooser.FileFilter;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
@@ -67,15 +67,12 @@ public final class LoadDialog extends FreeColDialog {
fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileHidingEnabled(false);
- fileChooser.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- final String cmd = event.getActionCommand();
- File value = (JFileChooser.APPROVE_SELECTION.equals(cmd))
- ? ((JFileChooser)event.getSource()).getSelectedFile()
- : cancelFile;
- setValue(value);
- }
+ fileChooser.addActionListener((ActionEvent ae) -> {
+ final String cmd = ae.getActionCommand();
+ File value = (JFileChooser.APPROVE_SELECTION.equals(cmd))
+ ? ((JFileChooser)ae.getSource()).getSelectedFile()
+ : cancelFile;
+ setValue(value);
});
List> c = choices();
diff --git a/src/net/sf/freecol/client/gui/panel/LoadingSavegameDialog.java b/src/net/sf/freecol/client/gui/panel/LoadingSavegameDialog.java
index 82d5e263e..6744e2ab1 100644
--- a/src/net/sf/freecol/client/gui/panel/LoadingSavegameDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/LoadingSavegameDialog.java
@@ -35,6 +35,7 @@ import javax.swing.SpinnerNumberModel;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.FontLibrary;
+import net.sf.freecol.client.gui.LoadingSavegameInfo;
import net.sf.freecol.common.i18n.Messages;
@@ -70,9 +71,9 @@ public final class LoadingSavegameDialog extends FreeColConfirmDialog {
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setOpaque(false);
- JLabel header = Utility.localizedLabel(Messages.nameKey("loadingSavegameDialog"), JLabel.CENTER);
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.MEDIUM));
+ JLabel header = Utility.localizedHeaderLabel(
+ Messages.nameKey("loadingSavegameDialog"), JLabel.CENTER,
+ FontLibrary.FontSize.MEDIUM);
header.setBorder(Utility.blankBorder(20, 0, 0, 0));
JPanel p1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
@@ -146,6 +147,15 @@ public final class LoadingSavegameDialog extends FreeColConfirmDialog {
return serverNameField.getName();
}
+ /**
+ * Get all important information at once.
+ *
+ * @return A LoadingSavegameInfo.
+ */
+ public LoadingSavegameInfo getInfo() {
+ return new LoadingSavegameInfo(isSinglePlayer(), getPort(), getServerName());
+ }
+
/**
* Reset the dialog to a given state.
*
diff --git a/src/net/sf/freecol/client/gui/panel/MainPanel.java b/src/net/sf/freecol/client/gui/panel/MainPanel.java
index a6808604b..5a9288efc 100644
--- a/src/net/sf/freecol/client/gui/panel/MainPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/MainPanel.java
@@ -98,7 +98,7 @@ public final class MainPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
+ public void actionPerformed(ActionEvent ae) {
// The actions are handled implicitly by the JButton/FreeColActions
getGUI().removeFromCanvas(this);
}
diff --git a/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java b/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java
index 43c1cefc9..64db864ba 100644
--- a/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/MapEditorTransformPanel.java
@@ -21,10 +21,10 @@ package net.sf.freecol.client.gui.panel;
import java.awt.BorderLayout;
import java.awt.Color;
+import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
@@ -38,12 +38,14 @@ import javax.swing.JToggleButton;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.MapEditorController;
+import net.sf.freecol.client.control.MapEditorController.IMapTransform;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.ImageLibrary;
-import net.sf.freecol.client.gui.MapViewer;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.i18n.Messages;
+import net.sf.freecol.common.model.Direction;
import net.sf.freecol.common.model.IndianNationType;
import net.sf.freecol.common.model.LostCityRumour;
-import net.sf.freecol.common.model.Direction;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.Player;
@@ -116,15 +118,17 @@ public final class MapEditorTransformPanel extends FreeColPanel {
private void buildList() {
final Specification spec = getSpecification();
List tileList = spec.getTileTypeList();
+ Dimension terrainSize = ImageLibrary.scaleDimension(ImageLibrary.TILE_OVERLAY_SIZE, 0.5f);
for (TileType type : tileList) {
- listPanel.add(buildButton(MapViewer.createTileImageWithOverlayAndForest(type, 0.5f),
+ listPanel.add(buildButton(SwingGUI.createTileImageWithOverlayAndForest(type, terrainSize),
Messages.getName(type),
new TileTypeTransform(type)));
}
- listPanel.add(buildButton(ImageLibrary.getRiverImage("0101", 0.5f),
+ Dimension riverSize = ImageLibrary.scaleDimension(ImageLibrary.TILE_SIZE, 0.5f);
+ listPanel.add(buildButton(ImageLibrary.getRiverImage("0101", riverSize),
Messages.message("mapEditorTransformPanel.minorRiver"),
new RiverTransform(TileImprovement.SMALL_RIVER)));
- listPanel.add(buildButton(ImageLibrary.getRiverImage("0202", 0.5f),
+ listPanel.add(buildButton(ImageLibrary.getRiverImage("0202", riverSize),
Messages.message("mapEditorTransformPanel.majorRiver"),
new RiverTransform(TileImprovement.LARGE_RIVER)));
listPanel.add(buildButton(ImageLibrary.getMiscImage("image.tileitem."
@@ -161,19 +165,18 @@ public final class MapEditorTransformPanel extends FreeColPanel {
button.setToolTipText(text);
button.setOpaque(false);
group.add(button);
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- MapEditorController ctlr = getFreeColClient().getMapEditorController();
- MapTransform newMapTransform = null;
- if(ctlr.getMapTransform() != mt){
- newMapTransform = mt;
- }
- ctlr.setMapTransform(newMapTransform);
- if(newMapTransform == null && mt != null){
- //select the invisible button, de-selecting all others
- group.setSelected(group.getElements().nextElement().getModel(),true);
- }
+ button.addActionListener((ActionEvent ae) -> {
+ MapEditorController ctlr
+ = getFreeColClient().getMapEditorController();
+ MapTransform newMapTransform = null;
+ if (ctlr.getMapTransform() != mt) {
+ newMapTransform = mt;
+ }
+ ctlr.setMapTransform(newMapTransform);
+ if (newMapTransform == null && mt != null) {
+ //select the invisible button, de-selecting all others
+ group.setSelected(group.getElements().nextElement()
+ .getModel(), true);
}
});
button.setBorder(null);
@@ -195,7 +198,7 @@ public final class MapEditorTransformPanel extends FreeColPanel {
*
* @see #transform(Tile)
*/
- public abstract class MapTransform {
+ public abstract class MapTransform implements IMapTransform {
/**
* A panel with information about this transformation.
@@ -311,9 +314,9 @@ public final class MapEditorTransformPanel extends FreeColPanel {
String name = Messages.getName(rt);
choices.add(new ChoiceItem<>(name, rt));
}
- ResourceType choice = getGUI().getChoice(true, null,
+ ResourceType choice = getGUI().getChoice(null,
Messages.message("mapEditorTransformPanel.chooseResource"),
- null, "cancel", choices);
+ "cancel", choices);
if (choice != null) {
t.addResource(new Resource(t.getGame(), t, choice,
choice.getMaxValue()));
@@ -345,7 +348,7 @@ public final class MapEditorTransformPanel extends FreeColPanel {
|| nativeNation == null) return;
UnitType skill = ((IndianNationType)nativeNation.getType())
.getSkills().get(0).getObject();
- Player nativePlayer = getGame().getPlayer(nativeNation.getId());
+ Player nativePlayer = getGame().getPlayerByNation(nativeNation);
if (nativePlayer == null) return;
String name = nativePlayer.getSettlementName(null);
ServerIndianSettlement settlement
diff --git a/src/net/sf/freecol/client/gui/panel/MapGeneratorOptionsDialog.java b/src/net/sf/freecol/client/gui/panel/MapGeneratorOptionsDialog.java
index fc85817ac..7da9f2f8d 100644
--- a/src/net/sf/freecol/client/gui/panel/MapGeneratorOptionsDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/MapGeneratorOptionsDialog.java
@@ -22,7 +22,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.io.File;
import java.util.Arrays;
import java.util.Comparator;
@@ -37,7 +36,6 @@ import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
-import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.option.BooleanOptionUI;
@@ -81,7 +79,7 @@ public final class MapGeneratorOptionsDialog extends OptionsDialog {
// FIXME: The update should be solved by PropertyEvent.
File mapDirectory = FreeColDirectories.getMapsDirectory();
if (mapDirectory.isDirectory()) {
- File[] files = mapDirectory.listFiles(FreeCol.freeColSaveFileFilter);
+ File[] files = mapDirectory.listFiles(FreeColSavegameFile.getFileFilter());
Arrays.sort(files, new Comparator() {
@Override
public int compare(File f1, File f2) {
@@ -92,11 +90,8 @@ public final class MapGeneratorOptionsDialog extends OptionsDialog {
for (final File file : files) {
JButton mapButton = makeMapButton(file);
if (mapButton == null) continue;
- mapButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- updateFile(file);
- }
+ mapButton.addActionListener((ActionEvent ae) -> {
+ updateFile(file);
});
mapPanel.add(mapButton);
}
diff --git a/src/net/sf/freecol/client/gui/panel/MiniMap.java b/src/net/sf/freecol/client/gui/panel/MiniMap.java
index d1b15e9af..80dcbc318 100644
--- a/src/net/sf/freecol/client/gui/panel/MiniMap.java
+++ b/src/net/sf/freecol/client/gui/panel/MiniMap.java
@@ -21,9 +21,9 @@ package net.sf.freecol.client.gui.panel;
import java.awt.BasicStroke;
import java.awt.Color;
+import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
-import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
@@ -349,12 +349,11 @@ public final class MiniMap extends JPanel implements MouseInputListener {
* Use miniRectWidth/Height / 2 to get the upper left corner.
* x/yTiles are the number of tiles that fit on the large map */
if (getParent() != null) {
- TileType tileType = freeColClient.getGame().getSpecification().getTileTypeList().get(0);
int miniRectX = (gui.getFocus().getX() - firstColumn) * tileSize;
int miniRectY = (gui.getFocus().getY() - firstRow) * tileSize / 4;
- Image image = library.getTerrainImage(tileType, 0, 0);
- int miniRectWidth = (getParent().getWidth() / image.getWidth(null) + 1) * tileSize;
- int miniRectHeight = (getParent().getHeight() / image.getHeight(null) + 1) * tileSize / 2;
+ Dimension mapTileSize = library.scaleDimension(ImageLibrary.TILE_SIZE);
+ int miniRectWidth = (getParent().getWidth() / mapTileSize.width + 1) * tileSize;
+ int miniRectHeight = (getParent().getHeight() / mapTileSize.height + 1) * tileSize / 2;
if (miniRectX + miniRectWidth / 2 > width) {
miniRectX = width - miniRectWidth / 2 - 1;
} else if (miniRectX - miniRectWidth / 2 < 0) {
diff --git a/src/net/sf/freecol/client/gui/panel/ModifierFormat.java b/src/net/sf/freecol/client/gui/panel/ModifierFormat.java
index cbada3ef1..86c7714aa 100644
--- a/src/net/sf/freecol/client/gui/panel/ModifierFormat.java
+++ b/src/net/sf/freecol/client/gui/panel/ModifierFormat.java
@@ -20,6 +20,8 @@
package net.sf.freecol.client.gui.panel;
import java.text.DecimalFormat;
+import java.util.Arrays;
+import java.util.stream.Collectors;
import javax.swing.JLabel;
@@ -99,12 +101,8 @@ public class ModifierFormat {
FreeColGameObjectType fcgot,
Turn turn) {
String sourceName = getSourceName(modifier.getSource());
- if (fcgot != null) {
- for (Scope scope : modifier.getScopes()) {
- if (scope.appliesTo(fcgot)) {
- sourceName += " (" + Messages.getName(fcgot) + ")";
- }
- }
+ if (fcgot != null && modifier.appliesTo(fcgot)) {
+ sourceName += " (" + Messages.getName(fcgot) + ")";
}
float value = modifier.getValue(turn);
String[] bonus = getModifierStrings(value, modifier.getType());
@@ -116,33 +114,22 @@ public class ModifierFormat {
}
public static String getFeatureAsString(Feature feature) {
- String label = Messages.getName(feature) + ":";
- if (feature.hasScope()) {
- for (Scope scope : feature.getScopes()) {
- String key = null;
- if (scope.getType() != null) {
- key = scope.getType();
- } else if (scope.getAbilityId() != null) {
- key = scope.getAbilityId();
- } else if (scope.getMethodName() != null) {
- key = "model.scope." + scope.getMethodName();
- }
- if (key != null) {
- label += (scope.isMatchNegated() ? " !" : " ")
- + Messages.getName(key) + ",";
- }
- }
- }
- return label.substring(0, label.length() - 1);
+ return Messages.getName(feature) + ":"
+ + ((!feature.hasScope()) ? ""
+ : feature.getScopes().stream().map(scope -> {
+ String k = scope.getKey();
+ if (k == null) {
+ k = "";
+ } else {
+ k = Messages.getName(k);
+ if (scope.isMatchNegated()) k = "!" + k;
+ }
+ return k;
+ }).collect(Collectors.joining()));
}
public static String getModifierAsString(Modifier modifier) {
- String result = "";
- for (String string : getModifierStrings(modifier)) {
- if (string != null) {
- result += string;
- }
- }
- return result;
+ return Arrays.stream(getModifierStrings(modifier))
+ .filter(s -> s != null).collect(Collectors.joining());
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/MonarchDialog.java b/src/net/sf/freecol/client/gui/panel/MonarchDialog.java
index 690746ba7..9e4b1bad2 100644
--- a/src/net/sf/freecol/client/gui/panel/MonarchDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/MonarchDialog.java
@@ -20,18 +20,19 @@
package net.sf.freecol.client.gui.panel;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.ImageIcon;
-
import javax.swing.JButton;
import javax.swing.JFrame;
+import javax.swing.JLabel;
import javax.swing.JTextArea;
+import javax.swing.SwingConstants;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.FontLibrary;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.common.i18n.Messages;
@@ -77,9 +78,8 @@ public final class MonarchDialog extends FreeColDialog {
if (!Messages.containsKey(hdrKey)) {
hdrKey = "monarchDialog.default";
}
- JTextArea header = Utility.localizedTextArea(hdrKey);
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.MEDIUM));
+ JLabel header = Utility.localizedHeaderLabel(hdrKey,
+ SwingConstants.LEADING, FontLibrary.FontSize.MEDIUM);
MigPanel panel = new MigPanel(new MigLayout("wrap 2, insets 10",
"[]20[]"));
@@ -87,11 +87,8 @@ public final class MonarchDialog extends FreeColDialog {
if (action == MonarchAction.RAISE_TAX_ACT
|| action == MonarchAction.RAISE_TAX_WAR) {
JButton helpButton = Utility.localizedButton("help");
- helpButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- getGUI().showColopediaPanel("colopedia.concepts.taxes");
- }
+ helpButton.addActionListener((ActionEvent ae) -> {
+ getGUI().showColopediaPanel("colopedia.concepts.taxes");
});
panel.add(helpButton, "tag help");
}
diff --git a/src/net/sf/freecol/client/gui/panel/NationDetailPanel.java b/src/net/sf/freecol/client/gui/panel/NationDetailPanel.java
index ebcc7c97c..6392ca6a5 100644
--- a/src/net/sf/freecol/client/gui/panel/NationDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/NationDetailPanel.java
@@ -56,12 +56,10 @@ public class NationDetailPanel extends ColopediaGameObjectTypePanel {
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
@@ -72,10 +70,7 @@ public class NationDetailPanel extends ColopediaGameObjectTypePanel {
}
/**
- * Builds the details panel for the Nation with the given identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
@@ -92,9 +87,7 @@ public class NationDetailPanel extends ColopediaGameObjectTypePanel {
panel.setLayout(new MigLayout("wrap 3, fillx, gapx 20", "", ""));
- JLabel name = Utility.localizedLabel(nation);
- name.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel name = Utility.localizedHeaderLabel(nation, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
JLabel artLabel = new JLabel(new ImageIcon(ImageLibrary.getMonarchImage(nation)));
diff --git a/src/net/sf/freecol/client/gui/panel/NationTypeDetailPanel.java b/src/net/sf/freecol/client/gui/panel/NationTypeDetailPanel.java
index 3ca5c1ca1..6e1b31b17 100644
--- a/src/net/sf/freecol/client/gui/panel/NationTypeDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/NationTypeDetailPanel.java
@@ -68,17 +68,16 @@ public class NationTypeDetailPanel
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
- DefaultMutableTreeNode parent =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(), getName(), null));
+ DefaultMutableTreeNode parent
+ = new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(),
+ getName(), null));
List nations = new ArrayList<>();
nations.addAll(getSpecification().getEuropeanNationTypes());
@@ -92,22 +91,17 @@ public class NationTypeDetailPanel
}
/**
- * Builds the details panel for the NationType with the given identifier.
- *
- * @param id The object identifier to display.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (getId().equals(id)) {
- return;
- }
+ if (getId().equals(id)) return;
NationType nationType = getSpecification().getNationType(id);
if (nationType instanceof EuropeanNationType) {
- buildEuropeanNationTypeDetail((EuropeanNationType) nationType, panel);
+ buildEuropeanNationTypeDetail((EuropeanNationType)nationType, panel);
} else if (nationType instanceof IndianNationType) {
- buildIndianNationTypeDetail((IndianNationType) nationType, panel);
+ buildIndianNationTypeDetail((IndianNationType)nationType, panel);
}
}
@@ -118,8 +112,8 @@ public class NationTypeDetailPanel
* @param nationType - the EuropeanNationType
* @param panel the panel to use
*/
- private void buildEuropeanNationTypeDetail(EuropeanNationType nationType, JPanel panel) {
-
+ private void buildEuropeanNationTypeDetail(EuropeanNationType nationType,
+ JPanel panel) {
Font boldFont = FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
FontLibrary.FontSize.SMALLER, Font.BOLD);
@@ -128,9 +122,7 @@ public class NationTypeDetailPanel
panel.setLayout(new MigLayout("wrap 2, gapx 20"));
- JLabel label = Utility.localizedLabel(nationType);
- label.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel label = Utility.localizedHeaderLabel(nationType, FontLibrary.FontSize.SMALL);
panel.add(label, "span, align center, wrap 40");
label = Utility.localizedLabel("colopedia.nationType.units");
@@ -171,25 +163,22 @@ public class NationTypeDetailPanel
}
}
-
/**
* Builds the details panel for the given nation type.
*
* @param nationType - the IndianNationType
* @param panel the panel to use
*/
- private void buildIndianNationTypeDetail(IndianNationType nationType, JPanel panel) {
-
+ private void buildIndianNationTypeDetail(IndianNationType nationType,
+ JPanel panel) {
List> skills = nationType.getSkills();
panel.setLayout(new MigLayout("wrap 2, gapx 20", "", ""));
- JLabel name = Utility.localizedLabel(nationType);
- name.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel name = Utility.localizedHeaderLabel(nationType, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
- panel.add(Utility.localizedLabel("colopedia.nationType.aggressionLevel"));
+ panel.add(Utility.localizedLabel("colopedia.nationType.aggression"));
panel.add(Utility.localizedLabel("colopedia.nationType."
+ nationType.getAggression().getKey()));
diff --git a/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java b/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java
index 1877a93f1..22b9bed67 100644
--- a/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/NegotiationDialog.java
@@ -24,7 +24,6 @@ import java.awt.Cursor;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
@@ -47,6 +46,7 @@ import javax.swing.SpinnerNumberModel;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.FontLibrary;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
@@ -100,7 +100,7 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
agreement.remove(item);
updateDialog();
}
@@ -193,8 +193,8 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null != command) switch (command) {
case ADD:
NegotiationDialog.this.addColonyTradeItem(source,
@@ -273,8 +273,8 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null != command) switch (command) {
case ADD:
int amount = ((Integer)spinner.getValue());
@@ -400,8 +400,8 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null != command) switch (command) {
case ADD:
NegotiationDialog.this.addGoodsTradeItem(source,
@@ -432,7 +432,7 @@ public final class NegotiationDialog extends FreeColDialog {
Player value, int index, boolean isSelected,
boolean cellHasFocus) {
setText((value == null) ? ""
- : Messages.message(value.getNationName()));
+ : Messages.message(value.getNationLabel()));
return this;
}
}
@@ -519,8 +519,8 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null != command) switch (command) {
case ADD:
Player victim = (Player)victimBox.getSelectedItem();
@@ -641,8 +641,8 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null != command) switch (command) {
case ADD:
Stance stance = (Stance)stanceBox.getSelectedItem();
@@ -761,8 +761,8 @@ public final class NegotiationDialog extends FreeColDialog {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null != command) switch (command) {
case ADD:
NegotiationDialog.this.addUnitTradeItem(source,
@@ -836,8 +836,8 @@ public final class NegotiationDialog extends FreeColDialog {
this.agreement = agreement;
this.comment = comment;
- StringTemplate nation = player.getNationName(),
- otherNation = otherPlayer.getNationName();
+ StringTemplate nation = player.getNationLabel(),
+ otherNation = otherPlayer.getNationLabel();
this.demand = StringTemplate.template("negotiationDialog.demand")
.addStringTemplate("%nation%", nation)
.addStringTemplate("%otherNation%", otherNation);
@@ -929,7 +929,7 @@ public final class NegotiationDialog extends FreeColDialog {
JTextArea labelDemandMessage = Utility.localizedTextArea(this.demand);
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.TINY, Font.BOLD,
- getImageLibrary().getScalingFactor());
+ getImageLibrary().getScaleFactor());
labelDemandMessage.setFont(font);
panel.add(labelDemandMessage);
JTextArea blank = new JTextArea(" ");
diff --git a/src/net/sf/freecol/client/gui/panel/NewPanel.java b/src/net/sf/freecol/client/gui/panel/NewPanel.java
index 4b503efd2..d1feec56f 100644
--- a/src/net/sf/freecol/client/gui/panel/NewPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/NewPanel.java
@@ -43,7 +43,7 @@ import net.sf.freecol.FreeCol;
import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.ConnectController;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.client.gui.plaf.FreeColComboBoxRenderer;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.ServerInfo;
@@ -217,11 +217,8 @@ public final class NewPanel extends FreeColPanel
this.serverPortLabel = Utility.localizedLabel("newPanel.startServerOnPort");
this.serverPortField
= new JTextField(Integer.toString(FreeCol.getServerPort()));
- this.serverPortField.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- getSelectedPort(NewPanel.this.serverPortField);
- }
+ this.serverPortField.addActionListener((ActionEvent ae) -> {
+ getSelectedPort(NewPanel.this.serverPortField);
});
this.rulesLabel = Utility.localizedLabel("rules");
@@ -264,11 +261,8 @@ public final class NewPanel extends FreeColPanel
this.joinPortLabel = Utility.localizedLabel("port");
this.joinPortField
= new JTextField(Integer.toString(FreeCol.getServerPort()));
- this.joinPortField.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- getSelectedPort(NewPanel.this.joinPortField);
- }
+ this.joinPortField.addActionListener((ActionEvent ae) -> {
+ getSelectedPort(NewPanel.this.joinPortField);
});
okButton.setActionCommand(String.valueOf(NewPanelAction.OK));
@@ -505,12 +499,11 @@ public final class NewPanel extends FreeColPanel
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
+ public void actionPerformed(ActionEvent ae) {
final ConnectController cc = getFreeColClient().getConnectController();
- final GUI gui = getGUI();
- final String command = event.getActionCommand();
+ final SwingGUI gui = getGUI();
+ final String command = ae.getActionCommand();
- int port;
switch (Enum.valueOf(NewPanelAction.class, command)) {
case OK:
FreeCol.setName(getSelectedName());
@@ -560,7 +553,7 @@ public final class NewPanel extends FreeColPanel
enableComponents();
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/NewUnitPanel.java b/src/net/sf/freecol/client/gui/panel/NewUnitPanel.java
index 17ae3d2bd..0cb4b23ab 100644
--- a/src/net/sf/freecol/client/gui/panel/NewUnitPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/NewUnitPanel.java
@@ -54,7 +54,7 @@ public class NewUnitPanel extends FreeColPanel {
/** The unit types corresponding to the buttons. */
private final List units = new ArrayList<>();
- /** A comparator for unit prices. */
+ /** A comparator by ascending unit price. */
private final Comparator priceComparator;
/** Is there at least one available unit? */
@@ -73,16 +73,11 @@ public class NewUnitPanel extends FreeColPanel {
String label, List units) {
super(freeColClient, layout);
- final Europe europe = getMyPlayer().getEurope();
-
this.question = new JLabel(label);
this.units.addAll(units);
- this.priceComparator = new Comparator() {
- @Override
- public int compare(final UnitType u1, final UnitType u2) {
- return europe.getUnitPrice(u1) - europe.getUnitPrice(u2);
- }
- };
+ final Europe europe = getMyPlayer().getEurope();
+ this.priceComparator = Comparator.comparingInt((UnitType ut) ->
+ europe.getUnitPrice(ut));
okButton.setText(Messages.message("close"));
@@ -142,10 +137,10 @@ public class NewUnitPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ String command = ae.getActionCommand();
if (OK.equals(command)) {
- super.actionPerformed(event);
+ super.actionPerformed(ae);
} else {
UnitType unitType = getSpecification().getUnitType(command);
igc().trainUnitInEurope(unitType);
diff --git a/src/net/sf/freecol/client/gui/panel/OptionsDialog.java b/src/net/sf/freecol/client/gui/panel/OptionsDialog.java
index 09edb1ceb..1bfde9548 100644
--- a/src/net/sf/freecol/client/gui/panel/OptionsDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/OptionsDialog.java
@@ -31,6 +31,7 @@ import net.miginfocom.swing.MigLayout;
import net.sf.freecol.FreeCol;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.option.OptionGroupUI;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.io.FreeColDirectories;
diff --git a/src/net/sf/freecol/client/gui/panel/ParametersDialog.java b/src/net/sf/freecol/client/gui/panel/ParametersDialog.java
index 6853edfa0..44468a15e 100644
--- a/src/net/sf/freecol/client/gui/panel/ParametersDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/ParametersDialog.java
@@ -32,6 +32,7 @@ import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
@@ -95,12 +96,9 @@ public class ParametersDialog extends FreeColDialog {
panel.add(heightPanel);
panel.setSize(panel.getPreferredSize());
- final ActionListener al = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- ParametersDialog.this.checkFields();
- }
- };
+ final ActionListener al = (ActionEvent ae) -> {
+ ParametersDialog.this.checkFields();
+ };
inputD.addActionListener(al);
inputM.addActionListener(al);
diff --git a/src/net/sf/freecol/client/gui/panel/PlayersTable.java b/src/net/sf/freecol/client/gui/panel/PlayersTable.java
index d37d95ef9..7ca54a395 100644
--- a/src/net/sf/freecol/client/gui/panel/PlayersTable.java
+++ b/src/net/sf/freecol/client/gui/panel/PlayersTable.java
@@ -46,6 +46,7 @@ import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
+import javax.swing.table.TableColumnModel;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.PreGameController;
@@ -209,12 +210,9 @@ public final class PlayersTable extends JTable {
= new JComboBox<>(NationState.values());
private JComboBox activeBox;
- private final ActionListener listener = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- stopCellEditing();
- }
- };
+ private final ActionListener listener = (ActionEvent ae) -> {
+ stopCellEditing();
+ };
public AvailableCellEditor() {
@@ -319,9 +317,10 @@ public final class PlayersTable extends JTable {
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Nation nation = (Nation) value;
- setText(Messages.getName(nation));
- setIcon(new ImageIcon(
- gui.getImageLibrary().getSmallerMiscIconImage(nation)));
+ setText(Messages.message(StringTemplate.template("countryName")
+ .add("%nation%", Messages.nameKey(nation.getId()))));
+ setIcon(new ImageIcon(gui.getImageLibrary()
+ .getSmallerMiscIconImage(nation)));
return this;
}
}
@@ -393,11 +392,8 @@ public final class PlayersTable extends JTable {
public PlayerCellEditor() {
- button.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- fireEditingStopped();
- }
+ button.addActionListener((ActionEvent ae) -> {
+ fireEditingStopped();
});
}
@@ -666,20 +662,14 @@ public final class PlayersTable extends JTable {
setRowHeight(47);
JButton nationButton = Utility.localizedButton("nation");
- nationButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.showColopediaPanel(PanelType.NATIONS.getKey());
- }
+ nationButton.addActionListener((ActionEvent ae) -> {
+ gui.showColopediaPanel(PanelType.NATIONS.getKey());
});
JLabel availabilityLabel = Utility.localizedLabel("playersTable.availability");
JButton advantageButton = Utility.localizedButton("playersTable.advantage");
- advantageButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.showColopediaPanel(PanelType.NATION_TYPES.getKey());
- }
+ advantageButton.addActionListener((ActionEvent ae) -> {
+ gui.showColopediaPanel(PanelType.NATION_TYPES.getKey());
});
JLabel colorLabel = Utility.localizedLabel("color");
@@ -693,17 +683,19 @@ public final class PlayersTable extends JTable {
JTableHeader header = getTableHeader();
header.addMouseListener(new HeaderListener(header, renderer));
- TableColumn nationColumn = getColumnModel().getColumn(NATION_COLUMN);
+ final TableColumnModel tcm = getColumnModel();
+
+ TableColumn nationColumn = tcm.getColumn(NATION_COLUMN);
nationColumn.setCellRenderer(new NationCellRenderer());
nationColumn.setHeaderRenderer(renderer);
+ nationColumn.setPreferredWidth(2 * tcm.getTotalColumnWidth()
+ / tcm.getColumnCount());
- TableColumn availableColumn
- = getColumnModel().getColumn(AVAILABILITY_COLUMN);
+ TableColumn availableColumn = tcm.getColumn(AVAILABILITY_COLUMN);
availableColumn.setCellRenderer(new AvailableCellRenderer());
availableColumn.setCellEditor(new AvailableCellEditor());
- TableColumn advantagesColumn
- = getColumnModel().getColumn(ADVANTAGE_COLUMN);
+ TableColumn advantagesColumn = tcm.getColumn(ADVANTAGE_COLUMN);
switch (nationOptions.getNationalAdvantages()) {
case SELECTABLE:
advantagesColumn.setCellEditor(new AdvantageCellEditor(spec
@@ -720,11 +712,11 @@ public final class PlayersTable extends JTable {
advantagesColumn.setCellRenderer(new AdvantageCellRenderer(nationOptions.getNationalAdvantages()));
advantagesColumn.setHeaderRenderer(renderer);
- TableColumn colorsColumn = getColumnModel().getColumn(COLOR_COLUMN);
+ TableColumn colorsColumn = tcm.getColumn(COLOR_COLUMN);
colorsColumn.setCellRenderer(new ColorCellRenderer(true));
colorsColumn.setCellEditor(new ColorCellEditor(freeColClient));
- TableColumn playerColumn = getColumnModel().getColumn(PLAYER_COLUMN);
+ TableColumn playerColumn = tcm.getColumn(PLAYER_COLUMN);
playerColumn.setCellEditor(new PlayerCellEditor());
playerColumn.setCellRenderer(new PlayerCellRenderer());
}
diff --git a/src/net/sf/freecol/client/gui/panel/PreCombatDialog.java b/src/net/sf/freecol/client/gui/panel/PreCombatDialog.java
index 3a07f2247..94e346b6d 100644
--- a/src/net/sf/freecol/client/gui/panel/PreCombatDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/PreCombatDialog.java
@@ -135,7 +135,7 @@ public class PreCombatDialog extends FreeColConfirmDialog {
}
Font bigFont = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.SMALLER, Font.BOLD, lib.getScalingFactor());
+ FontLibrary.FontSize.SMALLER, Font.BOLD, lib.getScaleFactor());
float offenceResult
= FeatureContainer.applyModifiers(0f, turn, attackModifiers);
JLabel finalOffenceLabel = Utility.localizedLabel("finalResult");
diff --git a/src/net/sf/freecol/client/gui/panel/ProductionLabel.java b/src/net/sf/freecol/client/gui/panel/ProductionLabel.java
index d8d70efb8..53b4d7e43 100644
--- a/src/net/sf/freecol/client/gui/panel/ProductionLabel.java
+++ b/src/net/sf/freecol/client/gui/panel/ProductionLabel.java
@@ -145,8 +145,9 @@ public final class ProductionLabel extends AbstractGoodsLabel {
logger.warning("Bad production label (no type)\n"
+ FreeColDebugger.stackTraceToString());
} else if (getAmount() == 0 && stockNumber < 0) {
- logger.warning("Bad production label (bad amount)\n"
- + FreeColDebugger.stackTraceToString());
+ logger.warning("Bad production label: " + ag
+ + " stock=" + stockNumber
+ + "\n" + FreeColDebugger.stackTraceToString());
}
this.maximumProduction = maximumProduction;
@@ -166,7 +167,7 @@ public final class ProductionLabel extends AbstractGoodsLabel {
: this.goodsIcon.getIconWidth() * 2;
setFont(FontLibrary.createFont(FontLibrary.FontType.SIMPLE,
- FontLibrary.FontSize.TINY, Font.BOLD, lib.getScalingFactor()));
+ FontLibrary.FontSize.TINY, Font.BOLD, lib.getScaleFactor()));
setForeground((getAmount() < 0) ? Color.RED : Color.WHITE);
setToolTipText((getType() == null || getAmount() == 0) ? null
: Messages.message(getAbstractGoods().getLabel()));
diff --git a/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java b/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java
index 66c83af98..293fe1d4f 100644
--- a/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java
+++ b/src/net/sf/freecol/client/gui/panel/QuickActionMenu.java
@@ -21,7 +21,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Font;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -43,8 +42,8 @@ import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.InGameController;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.client.gui.panel.ColonyPanel.TilesPanel.ASingleTilePanel;
import net.sf.freecol.client.gui.panel.UnitLabel.UnitAction;
import net.sf.freecol.common.debug.FreeColDebugger;
@@ -70,6 +69,7 @@ import net.sf.freecol.common.model.UnitLocation;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.UnitTypeChange.ChangeType;
import net.sf.freecol.common.model.WorkLocation;
+import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -83,7 +83,7 @@ public final class QuickActionMenu extends JPopupMenu {
private final FreeColClient freeColClient;
- private final GUI gui;
+ private final SwingGUI gui;
private final FreeColPanel parentPanel;
@@ -97,7 +97,7 @@ public final class QuickActionMenu extends JPopupMenu {
public QuickActionMenu(FreeColClient freeColClient,
FreeColPanel freeColPanel) {
this.freeColClient = freeColClient;
- this.gui = freeColClient.getGUI();
+ this.gui = (SwingGUI)freeColClient.getGUI();
this.parentPanel = freeColPanel;
}
@@ -206,11 +206,8 @@ public final class QuickActionMenu extends JPopupMenu {
.addStringTemplate("%unit%",
unit.getLabel(Unit.UnitLabelType.NATIONAL));
JMenuItem menuItem = Utility.localizedMenuItem(template);
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- igc.boardShip(tempUnit, unit);
- }
+ menuItem.addActionListener((ActionEvent ae) -> {
+ igc.boardShip(tempUnit, unit);
});
this.add(menuItem);
added = true;
@@ -230,14 +227,11 @@ public final class QuickActionMenu extends JPopupMenu {
.addStringTemplate("%unit%",
unit.getLabel(Unit.UnitLabelType.NATIONAL));
JMenuItem menuItem = Utility.localizedMenuItem(template);
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
- promptForGoods(goods);
- }
- igc.loadCargo(goods, unit);
+ menuItem.addActionListener((ActionEvent ae) -> {
+ if ((ae.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
+ promptForGoods(goods);
}
+ igc.loadCargo(goods, unit);
});
this.add(menuItem);
added = true;
@@ -388,11 +382,8 @@ public final class QuickActionMenu extends JPopupMenu {
if (current != null && unit.getWorkType() != null) {
JMenuItem ji = Utility.localizedMenuItem("showProductionModifiers");
- ji.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- gui.showWorkProductionPanel(unit);
- }
+ ji.addActionListener((ActionEvent ae) -> {
+ gui.showWorkProductionPanel(unit);
});
this.add(ji);
}
@@ -486,15 +477,12 @@ public final class QuickActionMenu extends JPopupMenu {
final boolean isUnitAtSea = tempUnit.isAtSea();
JMenuItem menuItem = Utility.localizedMenuItem("activateUnit");
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if (tempUnit.getState() != Unit.UnitState.ACTIVE) {
- freeColClient.getInGameController()
- .changeState(tempUnit, Unit.UnitState.ACTIVE);
- }
- gui.setActiveUnit(tempUnit);
+ menuItem.addActionListener((ActionEvent ae) -> {
+ if (tempUnit.getState() != Unit.UnitState.ACTIVE) {
+ freeColClient.getInGameController()
+ .changeState(tempUnit, Unit.UnitState.ACTIVE);
}
+ gui.setActiveUnit(tempUnit);
});
menuItem.setEnabled(!isUnitAtSea);
this.add(menuItem);
@@ -536,12 +524,9 @@ public final class QuickActionMenu extends JPopupMenu {
if (tempUnit.canCarryTreasure() && tempUnit.canCashInTreasureTrain()) {
menuItem = Utility.localizedMenuItem("cashInTreasureTrain");
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- freeColClient.getInGameController()
- .checkCashInTreasureTrain(tempUnit);
- }
+ menuItem.addActionListener((ActionEvent ae) -> {
+ freeColClient.getInGameController()
+ .checkCashInTreasureTrain(tempUnit);
});
menuItem.setEnabled(true);
this.add(menuItem);
@@ -604,12 +589,7 @@ public final class QuickActionMenu extends JPopupMenu {
change = need.get(0);
break;
default:
- for (AbstractGoods ag : need) {
- if (ag.getAmount() > 0) {
- change = ag;
- break;
- }
- }
+ change = find(need, ag -> ag.getAmount() > 0);
break;
}
Icon icon = (change == null) ? null : new ImageIcon(
@@ -617,15 +597,12 @@ public final class QuickActionMenu extends JPopupMenu {
JMenuItem item = new JMenuItem(text, icon);
final InGameController igc = freeColClient.getInGameController();
- item.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- igc.equipUnitForRole(unitLabel.getUnit(), to, toCount);
- unitLabel.updateIcon();
- // FIXME: fix the PCL handling so this can go away
- if (parentPanel instanceof ColonyPanel) {
- ((ColonyPanel)parentPanel).update();
- }
+ item.addActionListener((ActionEvent ae) -> {
+ igc.equipUnitForRole(unitLabel.getUnit(), to, toCount);
+ unitLabel.updateIcon();
+ // FIXME: fix the PCL handling so this can go away
+ if (parentPanel instanceof ColonyPanel) {
+ ((ColonyPanel)parentPanel).update();
}
});
return item;
@@ -706,11 +683,8 @@ public final class QuickActionMenu extends JPopupMenu {
Messages.getName(goods) + " (" + Messages.message("colopedia") + ")",
new ImageIcon(
gui.getImageLibrary().getSmallIconImage(goods.getType())));
- name.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- gui.showColopediaPanel(goods.getType().getId());
- }
+ name.addActionListener((ActionEvent ae) -> {
+ gui.showColopediaPanel(goods.getType().getId());
});
this.add(name);
@@ -743,14 +717,11 @@ public final class QuickActionMenu extends JPopupMenu {
|| (carrier.isInEurope()
&& player.canTrade(goods.getType()))) {
JMenuItem unload = Utility.localizedMenuItem("unload");
- unload.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
- promptForGoods(goods);
- }
- igc.unloadCargo(goods, false);
+ unload.addActionListener((ActionEvent ae) -> {
+ if ((ae.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
+ promptForGoods(goods);
}
+ igc.unloadCargo(goods, false);
});
this.add(unload);
} else {
@@ -760,19 +731,16 @@ public final class QuickActionMenu extends JPopupMenu {
}
JMenuItem dump = Utility.localizedMenuItem("dumpCargo");
- dump.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
- promptForGoods(goods);
- }
- igc.unloadCargo(goods, true);
- // FIXME: fix pcls so this hackery can go away
- if (parentPanel instanceof CargoPanel) {
- ((CargoPanel) parentPanel).initialize();
- }
- parentPanel.revalidate();
+ dump.addActionListener((ActionEvent ae) -> {
+ if ((ae.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
+ promptForGoods(goods);
}
+ igc.unloadCargo(goods, true);
+ // FIXME: fix pcls so this hackery can go away
+ if (parentPanel instanceof CargoPanel) {
+ ((CargoPanel) parentPanel).initialize();
+ }
+ parentPanel.revalidate();
});
this.add(dump);
}
@@ -788,17 +756,14 @@ public final class QuickActionMenu extends JPopupMenu {
final InGameController igc = freeColClient.getInGameController();
JMenuItem menuItem = Utility.localizedMenuItem("payArrears");
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- igc.payArrears(goodsType);
- // FIXME: fix pcls so this hackery can go away
- if (parentPanel instanceof CargoPanel) {
- CargoPanel cargoPanel = (CargoPanel) parentPanel;
- cargoPanel.initialize();
- }
- parentPanel.revalidate();
+ menuItem.addActionListener((ActionEvent ae) -> {
+ igc.payArrears(goodsType);
+ // FIXME: fix pcls so this hackery can go away
+ if (parentPanel instanceof CargoPanel) {
+ CargoPanel cargoPanel = (CargoPanel) parentPanel;
+ cargoPanel.initialize();
}
+ parentPanel.revalidate();
});
this.add(menuItem);
}
@@ -818,11 +783,8 @@ public final class QuickActionMenu extends JPopupMenu {
Messages.getName(ag) + " (" + Messages.message("colopedia") + ")",
new ImageIcon(
gui.getImageLibrary().getSmallIconImage(ag.getType())));
- name.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- gui.showColopediaPanel(ag.getType().getId());
- }
+ name.addActionListener((ActionEvent ae) -> {
+ gui.showColopediaPanel(ag.getType().getId());
});
this.add(name);
@@ -846,14 +808,11 @@ public final class QuickActionMenu extends JPopupMenu {
.addStringTemplate("%unit%",
unit.getLabel(Unit.UnitLabelType.NATIONAL));
JMenuItem menuItem = Utility.localizedMenuItem(template);
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
- promptForGoods(ag);
- }
- igc.buyGoods(ag.getType(), ag.getAmount(), unit);
+ menuItem.addActionListener((ActionEvent ae) -> {
+ if ((ae.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
+ promptForGoods(ag);
}
+ igc.buyGoods(ag.getType(), ag.getAmount(), unit);
});
this.add(menuItem);
added = true;
@@ -897,11 +856,8 @@ public final class QuickActionMenu extends JPopupMenu {
private void addTileItem(final Tile tile) {
if (tile != null) {
JMenuItem menuItem = new JMenuItem(Messages.getName(tile));
- menuItem.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
+ menuItem.addActionListener((ActionEvent ae) -> {
gui.showTilePanel(tile);
- }
});
this.add(menuItem);
}
diff --git a/src/net/sf/freecol/client/gui/panel/RecruitPanel.java b/src/net/sf/freecol/client/gui/panel/RecruitPanel.java
index fe31b73b9..a8a1475aa 100644
--- a/src/net/sf/freecol/client/gui/panel/RecruitPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/RecruitPanel.java
@@ -21,10 +21,11 @@ package net.sf.freecol.client.gui.panel;
import java.awt.event.ActionEvent;
import java.util.logging.Logger;
+
import javax.swing.ImageIcon;
import javax.swing.JButton;
-import javax.swing.JTextArea;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
@@ -119,10 +120,10 @@ public final class RecruitPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (OK.equals(command)) {
- super.actionPerformed(event);
+ super.actionPerformed(ae);
} else {
try {
int index = Integer.parseInt(command);
diff --git a/src/net/sf/freecol/client/gui/panel/ReportClassicColonyPanel.java b/src/net/sf/freecol/client/gui/panel/ReportClassicColonyPanel.java
index 1b701d7ad..a9e04c4e7 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportClassicColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportClassicColonyPanel.java
@@ -20,18 +20,19 @@
package net.sf.freecol.client.gui.panel;
import java.awt.GridLayout;
-import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
+import java.util.stream.Collectors;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
@@ -44,7 +45,6 @@ import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.Unit;
-import net.sf.freecol.common.model.WorkLocation;
/**
@@ -70,6 +70,7 @@ public final class ReportClassicColonyPanel extends ReportPanel
super(freeColClient, "reportColonyAction");
this.colonies.addAll(freeColClient.getMySortedColonies());
+ update();
}
private void update() {
@@ -103,21 +104,17 @@ public final class ReportClassicColonyPanel extends ReportPanel
JPanel colonistsPanel
= new JPanel(new GridLayout(0, COLONISTS_PER_ROW));
colonistsPanel.setOpaque(false);
- List unitList = colony.getUnitList();
- Collections.sort(unitList, getUnitTypeComparator());
- for (Unit unit : unitList) {
- UnitLabel unitLabel = new UnitLabel(getFreeColClient(), unit,
- true, true);
- colonistsPanel.add(unitLabel);
+ for (Unit u : colony.getUnitList().stream()
+ .sorted(Unit.typeRoleComparator).collect(Collectors.toList())) {
+ colonistsPanel.add(new UnitLabel(getFreeColClient(), u,
+ true, true));
}
JPanel unitsPanel = new JPanel(new GridLayout(0, UNITS_PER_ROW));
unitsPanel.setOpaque(false);
- unitList = colony.getTile().getUnitList();
- Collections.sort(unitList, getUnitTypeComparator());
- for (Unit unit : unitList) {
- UnitLabel unitLabel = new UnitLabel(getFreeColClient(), unit,
- true, true);
- unitsPanel.add(unitLabel);
+ for (Unit u : colony.getTile().getUnitList().stream()
+ .sorted(Unit.typeRoleComparator).collect(Collectors.toList())) {
+ unitsPanel.add(new UnitLabel(getFreeColClient(), u,
+ true, true));
}
if (buildableLabel != null
&& spec.getUnitTypeList().contains(currentType)) {
@@ -135,11 +132,8 @@ public final class ReportClassicColonyPanel extends ReportPanel
int newValue = colony.getNetProductionOf(gt);
int stockValue = colony.getGoodsCount(gt);
if (newValue != 0 || stockValue > 0) {
- int maxProduction = 0;
- for (WorkLocation wl
- : colony.getWorkLocationsForProducing(gt)) {
- maxProduction += wl.getMaximumProductionOf(gt);
- }
+ int maxProduction = colony.getWorkLocationsForProducing(gt).stream()
+ .mapToInt(wl -> wl.getMaximumProductionOf(gt)).sum();
ProductionLabel productionLabel
= new ProductionLabel(getFreeColClient(),
new AbstractGoods(gt, newValue),
diff --git a/src/net/sf/freecol/client/gui/panel/ReportCompactColonyPanel.java b/src/net/sf/freecol/client/gui/panel/ReportCompactColonyPanel.java
index 9da827587..8ee3331fe 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportCompactColonyPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportCompactColonyPanel.java
@@ -31,17 +31,17 @@ import java.util.Map;
import java.util.Map.Entry;
import java.util.HashMap;
import java.util.List;
+import java.util.function.BinaryOperator;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
-import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingConstants;
+
import net.miginfocom.swing.MigLayout;
-import net.sf.freecol.client.ClientOptions;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.common.i18n.Messages;
@@ -51,20 +51,15 @@ import net.sf.freecol.common.model.BuildableType;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Colony.TileImprovementSuggestion;
-import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.ExportData;
import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Game;
-import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
import net.sf.freecol.common.model.GoodsType;
-import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Market;
-import net.sf.freecol.common.model.Occupation;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.ProductionInfo;
import net.sf.freecol.common.model.Region;
-import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
@@ -75,7 +70,6 @@ import net.sf.freecol.common.model.WorkLocation;
import net.sf.freecol.common.model.WorkLocation.Suggestion;
import net.sf.freecol.common.resources.ResourceManager;
import static net.sf.freecol.common.util.CollectionUtils.*;
-import net.sf.freecol.common.util.CollectionUtils.Accumulator;
/**
@@ -101,21 +95,18 @@ public final class ReportCompactColonyPanel extends ReportPanel
CONSUMPTION, // Positive production but could consume more
};
- public static Accumulator goodsProductionAccumulator
- = new Accumulator() {
- public GoodsProduction accumulate(GoodsProduction g1,
- GoodsProduction g2) {
- g1.amount += g2.amount;
- g1.status = (g1.status == ProductionStatus.NONE
- && g2.status == ProductionStatus.NONE)
- ? ProductionStatus.NONE
- : (g1.amount < 0) ? ProductionStatus.BAD
- : (g1.amount > 0) ? ProductionStatus.GOOD
- : ProductionStatus.ZERO;
- g1.extra = 0;
- return g1;
- }
- };
+ public static BinaryOperator goodsProductionAccumulator
+ = (g1, g2) -> {
+ g1.amount += g2.amount;
+ g1.status = (g1.status == ProductionStatus.NONE
+ && g2.status == ProductionStatus.NONE)
+ ? ProductionStatus.NONE
+ : (g1.amount < 0) ? ProductionStatus.BAD
+ : (g1.amount > 0) ? ProductionStatus.GOOD
+ : ProductionStatus.ZERO;
+ g1.extra = 0;
+ return g1;
+ };
/** Container class for goods production. */
public static class GoodsProduction {
@@ -125,7 +116,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
public int extra;
public GoodsProduction(int amount, ProductionStatus status,
- int extra) {
+ int extra) {
this.amount = amount;
this.status = status;
this.extra = extra;
@@ -472,7 +463,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
}
private JLabel newLabel(String h, ImageIcon i, Color c, StringTemplate t) {
- h = (h != null && Messages.containsKey(h)) ? Messages.message(h) : "";
+ if (h != null && Messages.containsKey(h)) h = Messages.message(h);
JLabel l = newLabel(h, i, c);
if (t != null) Utility.localizeToolTip(l, t);
return l;
@@ -508,6 +499,8 @@ public final class ReportCompactColonyPanel extends ReportPanel
*/
private void updateColony(ColonySummary s) {
final String cac = s.colony.getId();
+ final UnitType defaultUnitType
+ = spec.getDefaultUnitType(s.colony.getOwner());
List buttons = new ArrayList<>();
JButton b;
Color c;
@@ -580,17 +573,27 @@ public final class ReportCompactColonyPanel extends ReportPanel
}
if (n > 0) {
c = cAlarm;
- // TODO-post-0.11.4-release: temporary hack until 0.11.4-release
- String key = ("model.improvement.plow".equals(ti.getId())
- || "model.improvement.clearForest".equals(ti.getId()))
- ? "report.colony.plowing"
- : ("model.improvement.road".equals(ti.getId()))
- ? "report.colony.roadBuilding"
- : null;
- t = (key == null) ? null : stpld(key)
- .addName("%colony%", s.colony.getName())
- .addAmount("%amount%", n);
- // end temporary hack
+ if (n == 1) {
+ TileImprovementSuggestion tis = s.tileSuggestions.get(0);
+ for (Unit u : tis.tile.getUnitList()) {
+ if (u.getState() == Unit.UnitState.IMPROVING
+ && u.getWorkImprovement() != null
+ && u.getWorkImprovement().getType()
+ == tis.tileImprovementType) {
+ c = cWarn; // Work is underway
+ break;
+ }
+ }
+ t = stpld("report.colony.tile." + ti.getSuffix()
+ + ".specific")
+ .addName("%colony%", s.colony.getName())
+ .addStringTemplate("%location%",
+ tis.tile.getColonyTileLocationLabel(s.colony));
+ } else {
+ t = stpld("report.colony.tile." + ti.getSuffix())
+ .addName("%colony%", s.colony.getName())
+ .addAmount("%amount%", n);
+ }
b = newButton(cac, Integer.toString(n), null, c, t);
if (center) b.setFont(b.getFont().deriveFont(Font.BOLD));
} else {
@@ -667,17 +670,19 @@ public final class ReportCompactColonyPanel extends ReportPanel
break;
case PRODUCTION:
c = cWarn;
- t = stpld("report.colony.production")
+ t = stpld("report.colony.production.maxProduction")
.addName("%colony%", s.colony.getName())
.addNamed("%goods%", gt)
- .addAmount("%amount%", gp.amount);
+ .addAmount("%amount%", gp.amount)
+ .addAmount("%more%", gp.extra);
break;
case CONSUMPTION:
c = cWarn;
- t = stpld("report.colony.production")
+ t = stpld("report.colony.production.maxConsumption")
.addName("%colony%", s.colony.getName())
.addNamed("%goods%", gt)
- .addAmount("%amount%", gp.amount);
+ .addAmount("%amount%", gp.amount)
+ .addAmount("%more%", gp.extra);
break;
default:
throw new IllegalStateException("Bogus status: " + gp.status);
@@ -692,8 +697,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
if (s.newColonist > 0) {
t = stpld("report.colony.arriving")
.addName("%colony%", s.colony.getName())
- .addNamed("%unit%",
- spec.getDefaultUnitType(s.colony.getOwner()))
+ .addNamed("%unit%", defaultUnitType)
.addAmount("%turns%", s.newColonist);
b = newButton(cac, Integer.toString(s.newColonist), null,
cGood, t);
@@ -747,8 +751,13 @@ public final class ReportCompactColonyPanel extends ReportPanel
buttons.add(b);
}
- // Field: What is being trained.
+ // Field: What is being trained, including shadow units for vacant
+ // places.
// Colour: cAlarm if completion is blocked, otherwise cPlain.
+ int empty = 0;
+ Building school = s.colony.getWorkLocationWithAbility(Ability.TEACH,
+ Building.class);
+ if (school != null) empty = school.getType().getWorkPlaces();
for (Entry e
: mapEntriesByValue(s.teachers, descendingIntegerComparator)) {
Unit u = e.getKey();
@@ -770,6 +779,18 @@ public final class ReportCompactColonyPanel extends ReportPanel
cPlain, t);
}
buttons.add(b);
+ empty--;
+ }
+
+ if (empty > 0) {
+ final ImageIcon emptyIcon
+ = new ImageIcon(this.lib.getTinyUnitImage(defaultUnitType, true));
+ t = stpld("report.colony.making.educationVacancy")
+ .addName("%colony%", s.colony.getName())
+ .addAmount("%number%", empty);
+ for (; empty > 0; empty--) {
+ buttons.add(newButton(cac, "", emptyIcon, cPlain, t));
+ }
}
addTogether(buttons);
@@ -814,12 +835,16 @@ public final class ReportCompactColonyPanel extends ReportPanel
? stpld("report.colony.wanting")
.addName("%colony%", colony.getName())
.addNamed("%unit%", type)
+ .addStringTemplate("%location%",
+ suggestion.workLocation.getLabel())
.addNamed("%goods%", suggestion.goodsType)
.addAmount("%amount%", suggestion.amount)
: stpld("report.colony.improving")
.addName("%colony%", colony.getName())
.addNamed("%oldUnit%", suggestion.oldType)
.addNamed("%unit%", type)
+ .addStringTemplate("%location%",
+ suggestion.workLocation.getLabel())
.addNamed("%goods%", suggestion.goodsType)
.addAmount("%amount%", suggestion.amount);
JButton b = newButton(cac, label, icon,
@@ -891,13 +916,15 @@ public final class ReportCompactColonyPanel extends ReportPanel
// Colour: Plain
t = mapEntriesByValue(rRegionMap, descendingIntegerComparator)
.get(0).getKey().getLabel();
- reportPanel.add(newLabel(Messages.message(t), null, cPlain, null),
+ reportPanel.add(newLabel(Messages.message(t), null, cPlain,
+ stpld("report.colony.name.summary")),
"newline");
// Field: The total of the size change field.
// Colour: cGood if efficient/cAlarm if inefficient.
reportPanel.add(newLabel(Integer.toString(rSizeChange), null,
- (rSizeChange < 0) ? cAlarm : cGood, null));
+ (rSizeChange < 0) ? cAlarm : cGood,
+ stpld("report.colony.growing.summary")));
// Field: The number of potential colony tiles that need
// exploring.
@@ -909,7 +936,8 @@ public final class ReportCompactColonyPanel extends ReportPanel
}
}
reportPanel.add((tiles.isEmpty()) ? new JLabel()
- : newLabel(Integer.toString(tiles.size()), null, cAlarm, null));
+ : newLabel(Integer.toString(tiles.size()), null, cAlarm,
+ stpld("report.colony.exploring.summary")));
// Fields: The number of existing colony tiles that would
// benefit from improvements.
@@ -924,7 +952,9 @@ public final class ReportCompactColonyPanel extends ReportPanel
}
}
reportPanel.add((tiles.isEmpty()) ? new JLabel()
- : newLabel(Integer.toString(tiles.size()), null, cAlarm, null));
+ : newLabel(Integer.toString(tiles.size()), null, cAlarm,
+ stpld("report.colony.tile." + ti.getSuffix()
+ + ".summary")));
}
// Fields: The net production of each storable+non-trade-goods
@@ -950,13 +980,16 @@ public final class ReportCompactColonyPanel extends ReportPanel
throw new IllegalStateException("Bogus status: " + gp.status);
}
reportPanel.add((c == null) ? new JLabel()
- : newLabel(Integer.toString(gp.amount), null, c, null));
+ : newLabel(Integer.toString(gp.amount), null, c,
+ stpld("report.colony.production.summary")
+ .addNamed("%goods%", gt)));
}
// Field: New colonist arrival or famine warning.
// Colour: cWarn if negative, else cGood
reportPanel.add(newLabel(Integer.toString((int)rNewColonist), null,
- (rNewColonist < 0) ? cWarn : cGood, null));
+ (rNewColonist < 0) ? cWarn : cGood,
+ stpld("report.colony.arriving.summary")));
// Field: The required goods rates.
// Colour: cPlain
@@ -965,18 +998,22 @@ public final class ReportCompactColonyPanel extends ReportPanel
: mapEntriesByValue(rNeeded, descendingDoubleComparator)) {
labels.add(newLabel(String.format("%4.1f %s", e.getValue(),
Messages.getName(e.getKey())),
- null, cPlain, null));
+ null, cPlain,
+ stpld("report.colony.making.summary")
+ .addNamed("%goods%", e.getKey())));
}
// Field: What is being trained (attached to previous)
// Colour: cPlain.
teacherLen = Math.max(3, teacherLen); // Always some room here
- labels.addAll(unitTypeLabels(rTeachers, teacherLen, null));
+ labels.addAll(unitTypeLabels(rTeachers, teacherLen,
+ stpld("report.colony.making.educating.summary")));
addTogether(labels);
// Field: The units that could be upgraded, followed by the units
// that could be added.
- addTogether(unitTypeLabels(rImprove, improveLen, null));
+ addTogether(unitTypeLabels(rImprove, improveLen,
+ stpld("report.colony.improving.summary")));
}
private List unitTypeLabels(Map unitTypeMap,
@@ -988,7 +1025,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
ImageIcon icon
= new ImageIcon(this.lib.getTinyUnitImage(e.getKey(), false));
result.add(newLabel(Integer.toString(e.getValue()), icon,
- cPlain, t));
+ cPlain, t));
if (++n >= maxSize) break;
}
@@ -1014,13 +1051,7 @@ public final class ReportCompactColonyPanel extends ReportPanel
stpld("report.colony.explore")));
for (TileImprovementType ti : this.spec.getTileImprovementTypeList()) {
if (ti.isNatural()) continue;
- // TODO-post-0.11.4-release: temporary hack until 0.11.4-release
- String key = (("model.improvement.plow".equals(ti.getId()))
- ? "report.colony.plow"
- : ("model.improvement.road".equals(ti.getId()))
- ? "report.colony.road"
- : null) + ".header";
- // end temporary hack
+ String key = "report.colony.tile." + ti.getSuffix() + ".header";
reportPanel.add(newLabel(key, null, null, stpld(key)));
}
for (GoodsType gt : this.goodsTypes) {
@@ -1082,34 +1113,24 @@ public final class ReportCompactColonyPanel extends ReportPanel
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
+ public void actionPerformed(ActionEvent ae) {
final Game game = getGame();
- String command = event.getActionCommand();
+ String command = ae.getActionCommand();
if (command.startsWith(BUILDQUEUE)) {
command = command.substring(BUILDQUEUE.length());
Colony colony = game.getFreeColGameObject(command, Colony.class);
if (colony != null) {
- getGUI().showBuildQueuePanel(colony, new Runnable() {
- @Override
- public void run() {
- update();
- }
- });
+ getGUI().showBuildQueuePanel(colony, () -> { update(); });
return;
}
} else {
Colony colony = game.getFreeColGameObject(command, Colony.class);
if (colony != null) {
- getGUI().showColonyPanel(colony, null)
- .addClosingCallback(new Runnable() {
- @Override
- public void run() {
- update();
- }
- });
+ getGUI().showColonyPanel2(colony, null)
+ .addClosingCallback(() -> { update(); });
return;
}
}
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/ReportContinentalCongressPanel.java b/src/net/sf/freecol/client/gui/panel/ReportContinentalCongressPanel.java
index d9fe12fde..06b7aad17 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportContinentalCongressPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportContinentalCongressPanel.java
@@ -36,7 +36,6 @@ import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
-import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.FoundingFather.FoundingFatherType;
import net.sf.freecol.common.model.GoodsType;
@@ -84,10 +83,8 @@ public final class ReportContinentalCongressPanel extends ReportPanel {
Messages.getDescription(currentFather));
recruitingPanel.add(currentFatherLabel);
for (GoodsType gt : getSpecification().getLibertyGoodsTypeList()) {
- int total = 0;
- for (Colony colony : player.getColonies()) {
- total += colony.getNetProductionOf(gt);
- }
+ int total = player.getColonies().stream()
+ .mapToInt(c -> c.getNetProductionOf(gt)).sum();
FreeColProgressBar progressBar = new FreeColProgressBar(gt, 0,
player.getTotalFoundingFatherCost(), player.getLiberty(),
total);
diff --git a/src/net/sf/freecol/client/gui/panel/ReportExplorationPanel.java b/src/net/sf/freecol/client/gui/panel/ReportExplorationPanel.java
index fefe8501a..af38a1059 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportExplorationPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportExplorationPanel.java
@@ -78,7 +78,7 @@ public final class ReportExplorationPanel extends ReportPanel {
* Header Row
*/
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, Font.BOLD, getImageLibrary().getScalingFactor());
+ FontLibrary.FontSize.TINY, Font.BOLD, getImageLibrary().getScaleFactor());
JLabel nameOfRegion = Utility.localizedLabel("report.exploration.nameOfRegion");
nameOfRegion.setFont(font);
reportPanel.add(nameOfRegion);
@@ -106,7 +106,7 @@ public final class ReportExplorationPanel extends ReportPanel {
reportPanel.add(Utility.localizedLabel(region.getDiscoveredIn()
.getLabel()));
reportPanel.add(Utility.localizedLabel(region.getDiscoveredBy()
- .getNationName()));
+ .getCountryLabel()));
reportPanel.add(new JLabel(String.valueOf(region.getScoreValue())));
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java b/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java
index 723f585df..0ab8b3245 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportForeignAffairPanel.java
@@ -52,7 +52,7 @@ public final class ReportForeignAffairPanel extends ReportPanel {
final ImageLibrary lib = freeColClient.getGUI().getImageLibrary();
final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.SMALL, Font.BOLD, lib.getScalingFactor());
+ FontLibrary.FontSize.SMALL, Font.BOLD, lib.getScaleFactor());
final String stance = Messages.message(
StringTemplate.key("report.foreignAffair.stance"));
final String numberOfColonies = Messages.message(
@@ -83,13 +83,13 @@ public final class ReportForeignAffairPanel extends ReportPanel {
if (ns == null) continue;
JPanel enemyPanel = new MigPanel(new MigLayout("gapy 0",
- "[][]20[align right]0[]", ""));
+ "[][]20[align right]0[]", ""));
enemyPanel.setOpaque(false);
final Image coatOfArms = lib.getMiscIconImage(enemy.getNation());
JLabel coatLabel = new JLabel(new ImageIcon(coatOfArms));
enemyPanel.add(coatLabel, "spany, aligny top");
- JLabel label = Utility.localizedLabel(enemy.getNationName());
+ JLabel label = Utility.localizedLabel(enemy.getCountryLabel());
label.setFont(font);
enemyPanel.add(label, "wrap 12");
diff --git a/src/net/sf/freecol/client/gui/panel/ReportHighScoresPanel.java b/src/net/sf/freecol/client/gui/panel/ReportHighScoresPanel.java
index dd1e2d4e6..268462af0 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportHighScoresPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportHighScoresPanel.java
@@ -24,6 +24,8 @@ import java.text.DateFormat;
import java.util.List;
import javax.swing.JLabel;
+import javax.swing.SwingConstants;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
@@ -72,8 +74,8 @@ public final class ReportHighScoresPanel extends ReportPanel {
StringTemplate template = StringTemplate.template(messageId)
.addName("%name%", highScore.getPlayerName())
.addName("%nation%", highScore.getNewLandName());
- JLabel headline = Utility.localizedLabel(template);
- headline.setFont(font);
+ JLabel headline = Utility.localizedHeaderLabel(template,
+ SwingConstants.LEADING, FontLibrary.FontSize.SMALL);
reportPanel.add(headline,
"span, wrap 10");
@@ -102,7 +104,7 @@ public final class ReportHighScoresPanel extends ReportPanel {
reportPanel.add(Utility.localizedLabel("report.highScores.nation"),
"skip");
reportPanel.add(Utility.localizedLabel((highScore.getIndependenceTurn() > 0)
- ? StringTemplate.name(highScore.getNationName())
+ ? StringTemplate.name(highScore.getNationLabel())
: StringTemplate.key(highScore.getOldNationNameKey())));
reportPanel.add(Utility.localizedLabel("report.highScores.nationType"),
diff --git a/src/net/sf/freecol/client/gui/panel/ReportIndianPanel.java b/src/net/sf/freecol/client/gui/panel/ReportIndianPanel.java
index 1cb2d9960..ebeab91ea 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportIndianPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportIndianPanel.java
@@ -101,15 +101,15 @@ public final class ReportIndianPanel extends ReportPanel {
JLabel villageLabel = new JLabel();
villageLabel.setIcon(new ImageIcon(ImageLibrary.getSettlementImage(
opponent.getNationType().getCapitalType(),
- lib.getScalingFactor())));
+ lib.getScaleFactor())));
reportPanel.add(villageLabel, "span, split 2");
- JLabel headline = Utility.localizedLabel(opponent.getNationName());
+ JLabel headline = Utility.localizedLabel(opponent.getNationLabel());
headline.setFont(FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.SMALL, Font.BOLD, lib.getScalingFactor()));
+ FontLibrary.FontSize.SMALL, Font.BOLD, lib.getScaleFactor()));
reportPanel.add(headline, "wrap 20, aligny center");
JLabel label = Utility.localizedLabel("report.indian.chieftain");
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, Font.BOLD, lib.getScalingFactor());
+ FontLibrary.FontSize.TINY, Font.BOLD, lib.getScaleFactor());
label.setFont(font);
reportPanel.add(label);
reportPanel.add(Utility.localizedLabel(opponent.getName()), "left, wrap");
diff --git a/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java b/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java
index 89cbdf5a8..363cd3f9e 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java
@@ -173,13 +173,13 @@ public final class ReportLabourPanel extends ReportPanel {
}
Action selectAction = new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
showDetails();
}
};
Action quitAction = new AbstractAction() {
@Override
- public void actionPerformed(ActionEvent e) {
+ public void actionPerformed(ActionEvent ae) {
getGUI().removeFromCanvas(ReportLabourPanel.this);
}
};
@@ -223,10 +223,10 @@ public final class ReportLabourPanel extends ReportPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (OK.equals(command)) {
- super.actionPerformed(event);
+ super.actionPerformed(ae);
} else {
UnitType unitType = getSpecification().getUnitType(command);
getGUI().showReportLabourDetailPanel(unitType, this.data,
diff --git a/src/net/sf/freecol/client/gui/panel/ReportPanel.java b/src/net/sf/freecol/client/gui/panel/ReportPanel.java
index 6e758eabe..74a5af9ff 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportPanel.java
@@ -31,17 +31,15 @@ import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.AbstractUnit;
-import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.FreeColGameObject;
-import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Map;
-import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
@@ -53,20 +51,6 @@ public class ReportPanel extends FreeColPanel {
protected static final Logger logger = Logger.getLogger(ReportPanel.class.getName());
- private static final Comparator unitTypeComparator
- = new Comparator() {
- @Override
- public int compare(Unit unit1, Unit unit2) {
- int deltaType = unit2.getType().compareTo(unit1.getType());
- if (deltaType == 0) {
- return (unit2.getRole() == null) ? -1
- : unit2.getRole().getId().compareTo(unit1.getRole().getId());
- } else {
- return deltaType;
- }
- }
- };
-
protected final JPanel reportPanel;
protected final JLabel header;
@@ -98,7 +82,7 @@ public class ReportPanel extends FreeColPanel {
add(scrollPane, "cell 0 1, height 100%, width 100%");
add(okButton, "cell 0 2, tag ok");
- float scale = getImageLibrary().getScalingFactor();
+ float scale = getImageLibrary().getScaleFactor();
getGUI().restoreSavedSize(this, 200 + (int)(scale*850), 200 + (int)(scale*525));
}
@@ -111,15 +95,6 @@ public class ReportPanel extends FreeColPanel {
reportPanel.doLayout();
}
- /**
- * Returns a unit type comparator.
- *
- * @return A unit type comparator.
- */
- public static Comparator getUnitTypeComparator() {
- return unitTypeComparator;
- }
-
private Border createBorder() {
return new EmptyBorder(20, 20, 20, 20);
}
@@ -162,8 +137,8 @@ public class ReportPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (OK.equals(command)) {
getGUI().removeFromCanvas(this);
} else {
diff --git a/src/net/sf/freecol/client/gui/panel/ReportProductionPanel.java b/src/net/sf/freecol/client/gui/panel/ReportProductionPanel.java
index 2455af1ea..ee94c0dfc 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportProductionPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportProductionPanel.java
@@ -20,7 +20,6 @@
package net.sf.freecol.client.gui.panel;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
@@ -93,11 +92,8 @@ public final class ReportProductionPanel extends ReportPanel {
reportPanel.add(selectLabel);
JButton selectButton = Utility.localizedButton("report.production.update");
- selectButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- update();
- }
+ selectButton.addActionListener((ActionEvent ae) -> {
+ update();
});
reportPanel.add(selectButton, "wrap");
diff --git a/src/net/sf/freecol/client/gui/panel/ReportReligiousPanel.java b/src/net/sf/freecol/client/gui/panel/ReportReligiousPanel.java
index 4edb797ab..c12ec5611 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportReligiousPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportReligiousPanel.java
@@ -49,7 +49,7 @@ public final class ReportReligiousPanel extends ReportPanel {
final Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
FontLibrary.FontSize.SMALLER, Font.BOLD,
- freeColClient.getGUI().getImageLibrary().getScalingFactor());
+ freeColClient.getGUI().getImageLibrary().getScaleFactor());
final Player player = getMyPlayer();
final Specification spec = getSpecification();
diff --git a/src/net/sf/freecol/client/gui/panel/ReportRequirementsPanel.java b/src/net/sf/freecol/client/gui/panel/ReportRequirementsPanel.java
index d365becfb..8f516feec 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportRequirementsPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportRequirementsPanel.java
@@ -32,6 +32,7 @@ import javax.swing.JButton;
import javax.swing.JTextPane;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
@@ -43,7 +44,6 @@ import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Colony.TileImprovementSuggestion;
import net.sf.freecol.common.model.ColonyTile;
import net.sf.freecol.common.model.GoodsType;
-import net.sf.freecol.common.model.Direction;
import net.sf.freecol.common.model.ProductionInfo;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
@@ -190,20 +190,16 @@ public final class ReportRequirementsPanel extends ReportPanel {
List tileSuggestions
= colony.getTileImprovementSuggestions();
for (TileImprovementSuggestion tis : tileSuggestions) {
- // TODO-post-0.11.4-release: temporary hack until 0.11.4-release
- String key = (tis.isExploration())
- ? "report.requirements.exploreTile"
- : ("model.improvement.plow".equals(tis.tileImprovementType.getId()))
- ? ((tis.tile == colony.getTile())
- ? "report.requirements.plowCenter"
- : "report.requirements.plowTile")
- : ("model.improvement.clearForest".equals(tis.tileImprovementType.getId()))
- ? "report.requirements.clearTile"
- : ("model.improvement.road".equals(tis.tileImprovementType.getId()))
- ? "report.requirements.roadTile"
- : null;
- // end temporary hack
- addTileWarning(doc, colony, key, tis.tile);
+ if (tis.tileImprovementType == null) {
+ addTileWarning(doc, colony, "report.requirements.exploreTile",
+ tis.tile);
+ } else {
+ String key = "report.requirements.tile."
+ + tis.tileImprovementType.getSuffix();
+ if (Messages.containsKey(key)) {
+ addTileWarning(doc, colony, key, tis.tile);
+ }
+ }
}
if (tileSuggestions.isEmpty()
@@ -223,12 +219,9 @@ public final class ReportRequirementsPanel extends ReportPanel {
private void addTileWarning(StyledDocument doc, Colony colony,
String messageId, Tile tile) {
if (messageId == null || !Messages.containsKey(messageId)) return;
- // TODO-post-0.11.4-release: migrate to using Tile.getColonyTileLocationLabel()
- Direction direction = colony.getTile().getDirection(tile);
StringTemplate t = StringTemplate.template(messageId)
- .addNamed("%type%", tile.getType())
- .addName("%colony%", colony.getName());
- if (direction != null) t.addNamed("%direction%", direction);
+ .addStringTemplate("%location%",
+ tile.getColonyTileLocationLabel(colony));
try {
doc.insertString(doc.getLength(), "\n\n" + Messages.message(t),
doc.getStyle("regular"));
@@ -237,7 +230,8 @@ public final class ReportRequirementsPanel extends ReportPanel {
}
}
- private void addBadAssignmentWarning(StyledDocument doc, Colony colony, Unit expert, Unit nonExpert) {
+ private void addBadAssignmentWarning(StyledDocument doc, Colony colony,
+ Unit expert, Unit nonExpert) {
GoodsType expertGoods = expert.getWorkType();
GoodsType nonExpertGoods = nonExpert.getWorkType();
String colonyName = colony.getName();
@@ -260,7 +254,8 @@ public final class ReportRequirementsPanel extends ReportPanel {
}
}
- private void addExpertWarning(StyledDocument doc, Colony c, GoodsType goodsType, UnitType workType) {
+ private void addExpertWarning(StyledDocument doc, Colony c,
+ GoodsType goodsType, UnitType workType) {
String newMessage = Messages.message(StringTemplate
.template("report.requirements.noExpert")
.addName("%colony%", c.getName())
@@ -391,11 +386,11 @@ public final class ReportRequirementsPanel extends ReportPanel {
}
private JButton createColonyButton(Colony colony, String info, boolean headline) {
- JButton button = Utility.getLinkButton(colony.getName() + info, null,
- colony.getId());
+ String text = colony.getName() + info;
+ JButton button = Utility.getLinkButton(text, null, colony.getId());
if (headline) {
- button.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ button.setFont(FontLibrary.createCompatibleFont(text,
+ FontLibrary.FontType.HEADER, FontLibrary.FontSize.SMALL));
}
button.addActionListener(this);
return button;
diff --git a/src/net/sf/freecol/client/gui/panel/ReportTradePanel.java b/src/net/sf/freecol/client/gui/panel/ReportTradePanel.java
index 5df300d83..1e730b555 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportTradePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportTradePanel.java
@@ -27,7 +27,6 @@ import java.util.List;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
-import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
@@ -87,7 +86,7 @@ public final class ReportTradePanel extends ReportPanel {
String layoutConstraints = "insets 0, gap 0 0";
String columnConstraints = "[25%!, fill]["
- + Math.round(lib.getScalingFactor()
+ + Math.round(lib.getScaleFactor()
* (ImageLibrary.ICON_SIZE.width * 1.25f))
+ "!, fill]";
String rowConstraints = "[fill]";
@@ -176,6 +175,13 @@ public final class ReportTradePanel extends ReportPanel {
: Utility.CELLBORDER);
goodsLabel.setForeground(GoodsLabel.getColor(goodsType, amount,
colony));
+ ExportData ed = colony.getExportData(goodsType);
+ if (ed.getExported()) {
+ goodsLabel.setToolTipText(Messages.message(StringTemplate
+ .template("report.trade.export")
+ .addNamed("%goods%", goodsType)
+ .addAmount("%amount%", ed.getExportLevel())));
+ }
reportPanel.add(goodsLabel, "cell " + column + " " + row);
int production = colony.getNetProductionOf(goodsType);
@@ -216,7 +222,7 @@ public final class ReportTradePanel extends ReportPanel {
}
private JLabel createLeftLabel(String key) {
- JLabel result = Utility.localizedLabel(key, JLabel.LEADING);
+ JLabel result = Utility.localizedLabel(key);
result.setBorder(Utility.LEFTCELLBORDER);
return result;
}
diff --git a/src/net/sf/freecol/client/gui/panel/ReportTurnPanel.java b/src/net/sf/freecol/client/gui/panel/ReportTurnPanel.java
index 7a0c24782..45868da3f 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportTurnPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportTurnPanel.java
@@ -19,9 +19,9 @@
package net.sf.freecol.client.gui.panel;
+import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
@@ -38,6 +38,7 @@ import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.ClientOptions;
@@ -50,12 +51,10 @@ import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Game;
-import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Nameable;
import net.sf.freecol.common.model.Player;
-import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
@@ -124,15 +123,14 @@ public final class ReportTurnPanel extends ReportPanel {
FreeColGameObject messageSource = game.getMessageSource(message);
if (messageSource != source) {
source = messageSource;
- reportPanel.add(getHeadline(source), "newline 20, skip");
+ reportPanel.add(getHeadline(messageSource), "newline 20, skip");
}
break;
case ClientOptions.MESSAGES_GROUP_BY_TYPE:
if (message.getMessageType() != type) {
type = message.getMessageType();
- JLabel headline = Utility.localizedLabel(message.getMessageType());
- headline.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel headline = Utility.localizedHeaderLabel(
+ message.getMessageType(), FontLibrary.FontSize.SMALL);
reportPanel.add(headline, "newline 20, skip, span");
}
break;
@@ -142,19 +140,19 @@ public final class ReportTurnPanel extends ReportPanel {
JComponent component = new JLabel();
FreeColObject messageDisplay = game.getMessageDisplay(message);
+ final ImageLibrary lib = getImageLibrary();
if (messageDisplay != null) {
- Image image = getImageLibrary().getObjectImage(messageDisplay, 1f);
+ Image image = lib.getObjectImage(messageDisplay, 1f);
ImageIcon icon = (image == null) ? null : new ImageIcon(image);
-
if (messageDisplay instanceof Colony
|| messageDisplay instanceof Europe) {
JButton button = Utility.getLinkButton(null, icon,
- messageDisplay.getId());
+ messageDisplay.getId());
button.addActionListener(this);
component = button;
} else if (messageDisplay instanceof Unit) {
JButton button = Utility.getLinkButton(null, icon,
- upLoc(((Unit)messageDisplay).getLocation()).getId());
+ ((Unit)messageDisplay).up().getId());
button.addActionListener(this);
component = button;
} else { // includes Player
@@ -165,8 +163,12 @@ public final class ReportTurnPanel extends ReportPanel {
reportPanel.add(component, "newline");
final JTextPane textPane = Utility.getDefaultTextPane();
- insertMessage(textPane.getStyledDocument(), message,
- getMyPlayer());
+ try {
+ insertMessage(textPane.getStyledDocument(), message,
+ getMyPlayer());
+ } catch (BadLocationException ble) {
+ logger.log(Level.WARNING, "message insert fail", ble);
+ }
reportPanel.add(textPane);
boolean ignore = false;
@@ -177,14 +179,11 @@ public final class ReportTurnPanel extends ReportPanel {
Utility.localizeToolTip(ignoreButton,
StringTemplate.copy("report.turn.ignore", message));
final ModelMessage m = message;
- ignoreButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- boolean flag = label.isEnabled();
- igc().ignoreMessage(m, flag);
- textPane.setEnabled(!flag);
- label.setEnabled(!flag);
- }
+ ignoreButton.addActionListener((ActionEvent ae) -> {
+ boolean flag = label.isEnabled();
+ igc().ignoreMessage(m, flag);
+ textPane.setEnabled(!flag);
+ label.setEnabled(!flag);
});
reportPanel.add(ignoreButton);
ignore = true;
@@ -214,18 +213,12 @@ public final class ReportTurnPanel extends ReportPanel {
.template("report.turn.filter")
.addNamed("%type%", message.getMessageType()));
final ModelMessage m = message;
- filterButton.addActionListener(new ActionListener() {
-
- @Override
- public void actionPerformed(ActionEvent event) {
- boolean flag = filterOption.getValue();
- filterOption.setValue(!flag);
- //textPane.setEnabled(!flag);
- //label.setEnabled(!flag);
-
- setEnabledByType(m.getMessageType(), !flag);
- }
-
+ filterButton.addActionListener((ActionEvent ae) -> {
+ boolean flag = filterOption.getValue();
+ filterOption.setValue(!flag);
+ //textPane.setEnabled(!flag);
+ //label.setEnabled(!flag);
+ setEnabledByType(m.getMessageType(), !flag);
});
if (ignore) {
reportPanel.add(filterButton);
@@ -250,184 +243,77 @@ public final class ReportTurnPanel extends ReportPanel {
}
}
- private JComponent getHeadline(Object source) {
- JComponent headline;
+ private JComponent getHeadline(FreeColGameObject source) {
+ String text;
+ String commandId = null;
if (source == null) {
- return new JLabel();
+ text = "";
} else if (source instanceof Player) {
Player player = (Player) source;
- headline = Utility.localizedLabel(StringTemplate
+ StringTemplate template = StringTemplate
.template("report.turn.playerNation")
.addName("%player%", player.getName())
- .addStringTemplate("%nation%", player.getNationName()));
+ .addStringTemplate("%nation%", player.getNationLabel());
+ text = Messages.message(template);
} else if (source instanceof Europe) {
Europe europe = (Europe) source;
- JButton button = new JButton(Messages.getName(europe));
- button.addActionListener(this);
- button.setActionCommand(europe.getId());
- headline = button;
+ text = Messages.getName(europe);
+ commandId = europe.getId();
} else if (source instanceof Market) {
Market market = (Market) source;
- JButton button = Utility.localizedButton(market.getOwner().getMarketName());
- button.addActionListener(this);
- button.setActionCommand(getMyPlayer().getEurope().getId());
- headline = button;
+ StringTemplate template = market.getOwner().getMarketName();
+ text = Messages.message(template);
+ commandId = getMyPlayer().getEurope().getId();
} else if (source instanceof Colony) {
final Colony colony = (Colony) source;
- JButton button = new JButton(colony.getName());
- button.addActionListener(this);
- button.setActionCommand(colony.getId());
- headline = button;
+ text = colony.getName();
+ commandId = colony.getId();
} else if (source instanceof Unit) {
final Unit unit = (Unit) source;
- JButton button
- = new JButton(unit.getDescription(Unit.UnitLabelType.NATIONAL));
- button.addActionListener(this);
- button.setActionCommand(unit.getLocation().getId());
- headline = button;
+ text = unit.getDescription(Unit.UnitLabelType.NATIONAL);
+ commandId = unit.getLocation().getId();
} else if (source instanceof Tile) {
final Tile tile = (Tile) source;
- JButton button = Utility.localizedButton(tile.getLocationLabelFor(getMyPlayer()));
- button.addActionListener(this);
- button.setActionCommand(tile.getId());
- headline = button;
+ StringTemplate template = tile.getLocationLabelFor(getMyPlayer());
+ text = Messages.message(template);
+ commandId = tile.getId();
} else if (source instanceof Nameable) {
- headline = new JLabel(((Nameable) source).getName());
+ text = ((Nameable) source).getName();
} else {
- headline = new JLabel(source.toString());
+ text = source.toString();
}
- headline.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ Font font = FontLibrary.createCompatibleFont(text,
+ FontLibrary.FontType.HEADER, FontLibrary.FontSize.SMALL);
+ JComponent headline;
+ if(commandId != null) {
+ JButton button = new JButton(text);
+ button.addActionListener(this);
+ button.setActionCommand(commandId);
+ headline = button;
+ headline.setForeground(Utility.LINK_COLOR);
+ } else {
+ headline = new JLabel(text);
+ }
+ headline.setFont(font);
headline.setOpaque(false);
- headline.setForeground(Utility.LINK_COLOR);
headline.setBorder(Utility.blankBorder(5, 0, 0, 0));
return headline;
}
private void insertMessage(StyledDocument document, ModelMessage message,
- Player player) {
- try {
- String input = null;
- String id = message.getId();
- if (id == null || id.equals(input = Messages.message(id))) {
- // id not present, fallback to default
- input = Messages.message(message.getDefaultId());
+ Player player) throws BadLocationException {
+ for (Object o : message.splitLinks(player)) {
+ if (o instanceof String) {
+ document.insertString(document.getLength(), (String)o,
+ document.getStyle("regular"));
+ } else if (o instanceof JButton) {
+ JButton b = (JButton)o;
+ b.addActionListener(this);
+ StyleConstants.setComponent(document.getStyle("button"), b);
+ document.insertString(document.getLength(), " ",
+ document.getStyle("button"));
}
- int start = input.indexOf('%');
- if (start == -1) {
- // no variables present
- insertText(document, input);
- return;
- } else if (start > 0) {
- // output any string before the first occurrence of '%'
- insertText(document, input.substring(0, start));
- }
-
- int end;
- while ((end = input.indexOf('%', start + 1)) >= 0) {
- String var = input.substring(start, end + 1);
- String item = Messages.message(message.getReplacement(var));
- FreeColGameObject messageSource = getFreeColClient().getGame()
- .getMessageSource(message);
- if (item != null) {
- // found variable to replace
- if ("%colony%".equals(var) || var.endsWith("Colony%")) {
- Colony colony = player.getColonyByName(item);
- if (colony != null) {
- insertLinkButton(document, colony, item);
- } else if (messageSource instanceof Tile) {
- insertLinkButton(document, messageSource, item);
- } else {
- insertText(document, item);
- }
- } else if ("%europe%".equals(var)
- || ("%market%".equals(var) && player.isColonial())) {
- insertLinkButton(document, player.getEurope(),
- Messages.getName(player.getEurope()));
- } else if ("%unit%".equals(var)
- || var.endsWith("Unit%")
- || "%newName%".equals(var)) {
- Tile tile = null;
- if (messageSource instanceof Unit) {
- tile = ((Unit)messageSource).getTile();
- } else if (messageSource instanceof Tile) {
- tile = (Tile)messageSource;
- }
- if (tile != null) {
- Settlement settlement = tile.getSettlement();
- if (settlement != null) {
- insertLinkButton(document, settlement, item);
- } else {
- insertLinkButton(document, tile, item);
- }
- } else {
- insertText(document, item);
- }
- } else if ("%location%".equals(var)
- || var.endsWith("Location%")) {
- if (messageSource instanceof Europe) {
- insertLinkButton(document, player.getEurope(),
- Messages.getName(player.getEurope()));
- } else if (messageSource instanceof Location) {
- Location loc = upLoc((Location)messageSource);
- insertLinkButton(document, (FreeColGameObject)loc,
- item);
- } else {
- insertText(document, item);
- }
- } else {
- insertText(document, item);
- }
- start = end + 1;
- } else {
- // found no variable to replace: either a single '%', or
- // some unnecessary variable
- insertText(document, input.substring(start, end));
- start = end;
- }
- }
-
- // output any string after the last occurrence of '%'
- if (start < input.length()) {
- insertText(document, input.substring(start));
- }
-
- } catch (Exception e) {
- logger.log(Level.WARNING, "Insert fail: " + message, e);
}
}
-
- private void insertText(StyledDocument document, String text)
- throws BadLocationException {
- document.insertString(document.getLength(), text,
- document.getStyle("regular"));
- }
-
- private void insertLinkButton(StyledDocument document,
- FreeColGameObject object, String name)
- throws BadLocationException {
- JButton button = Utility.getLinkButton(name, null, object.getId());
- button.addActionListener(this);
- StyleConstants.setComponent(document.getStyle("button"), button);
- document.insertString(document.getLength(), " ",
- document.getStyle("button"));
- }
-
- public static Location upLoc(Location loc) {
- if (loc instanceof Unit) loc = ((Unit)loc).getLocation();
- return (loc == null) ? null
- : (loc.getSettlement() != null) ? loc.getSettlement()
- : loc;
- }
-
- // Interface ActionListener
-
- /**
- * {@inheritDoc}
- */
- @Override
- public void actionPerformed(ActionEvent event) {
- super.actionPerformed(event);
- }
}
diff --git a/src/net/sf/freecol/client/gui/panel/ReportUnitPanel.java b/src/net/sf/freecol/client/gui/panel/ReportUnitPanel.java
index 541ed74c1..277ab1dc7 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportUnitPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportUnitPanel.java
@@ -25,6 +25,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.stream.Collectors;
import javax.swing.ImageIcon;
import javax.swing.JButton;
@@ -184,17 +185,18 @@ public abstract class ReportUnitPanel extends ReportPanel {
if (unitList == null || unitList.isEmpty()) {
reportPanel.add(Utility.localizedLabel("none"), "sg");
} else {
- Collections.sort(unitList, ReportPanel.getUnitTypeComparator());
- for (Unit unit : unitList) {
- JButton unitButton = getUnitButton(unit);
- if (unit.isCarrier()) {
+ for (Unit u : unitList.stream()
+ .sorted(Unit.typeRoleComparator).collect(Collectors.toList())) {
+ JButton unitButton = getUnitButton(u);
+ if (u.isCarrier()) {
reportPanel.add(unitButton, "newline, sg");
- for (Goods goods : unit.getGoodsList()) {
+ for (Goods goods : u.getGoodsList()) {
GoodsLabel goodsLabel = new GoodsLabel(getGUI(), goods);
reportPanel.add(goodsLabel);
}
- for (Unit unitLoaded : unit.getUnitList()) {
- UnitLabel unitLoadedLabel = new UnitLabel(getFreeColClient(), unitLoaded, true);
+ for (Unit unitLoaded : u.getUnitList()) {
+ UnitLabel unitLoadedLabel
+ = new UnitLabel(getFreeColClient(), unitLoaded, true);
reportPanel.add(unitLoadedLabel);
}
} else {
diff --git a/src/net/sf/freecol/client/gui/panel/ResourcesDetailPanel.java b/src/net/sf/freecol/client/gui/panel/ResourcesDetailPanel.java
index 4a7b302fb..e7a8b7dc9 100644
--- a/src/net/sf/freecol/client/gui/panel/ResourcesDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ResourcesDetailPanel.java
@@ -20,6 +20,7 @@
package net.sf.freecol.client.gui.panel;
import java.util.ArrayList;
+import java.util.stream.Collectors;
import javax.swing.JButton;
import javax.swing.JLabel;
@@ -37,7 +38,7 @@ import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Modifier;
import net.sf.freecol.common.model.ResourceType;
import net.sf.freecol.common.model.Scope;
-
+import net.sf.freecol.common.model.Specification;
import static net.sf.freecol.common.util.StringUtils.*;
@@ -60,12 +61,10 @@ public class ResourcesDetailPanel
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
@@ -73,24 +72,16 @@ public class ResourcesDetailPanel
}
/**
- * Builds the details panel for the ResourceType with the given
- * identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (getId().equals(id)) {
- return;
- }
+ if (getId().equals(id)) return;
ResourceType type = getSpecification().getResourceType(id);
panel.setLayout(new MigLayout("wrap 2", "[]20[]"));
- JLabel name = Utility.localizedLabel(type);
- name.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel name = Utility.localizedHeaderLabel(type, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
panel.add(Utility.localizedLabel("colopedia.resource.bonusProduction"));
@@ -99,17 +90,12 @@ public class ResourcesDetailPanel
for (Modifier modifier : type.getModifiers()) {
String text = ModifierFormat.getModifierAsString(modifier);
if (modifier.hasScope()) {
- ArrayList scopeStrings = new ArrayList<>();
- for (Scope scope : modifier.getScopes()) {
- if (scope.getType() != null) {
- FreeColGameObjectType fcgot = getSpecification()
- .findType(scope.getType());
- scopeStrings.add(Messages.getName(fcgot));
- }
- }
- if (!scopeStrings.isEmpty()) {
- text += " (" + join(", ", scopeStrings) + ")";
- }
+ final Specification spec = getSpecification();
+ String scopeStrings = modifier.getScopes().stream()
+ .filter(s -> s.getType() != null)
+ .map(s -> Messages.getName(spec.findType(s.getType())))
+ .collect(Collectors.joining(", "));
+ if (!scopeStrings.isEmpty()) text += " (" + scopeStrings + ")";
}
GoodsType goodsType = getSpecification().getGoodsType(modifier.getId());
@@ -123,5 +109,4 @@ public class ResourcesDetailPanel
panel.add(Utility.localizedTextArea(Messages.descriptionKey(type), 30),
"growx");
}
-
}
diff --git a/src/net/sf/freecol/client/gui/panel/RiverStyleDialog.java b/src/net/sf/freecol/client/gui/panel/RiverStyleDialog.java
index ccdcad0cb..389e5476e 100644
--- a/src/net/sf/freecol/client/gui/panel/RiverStyleDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/RiverStyleDialog.java
@@ -19,15 +19,15 @@
package net.sf.freecol.client.gui.panel;
-import javax.swing.ImageIcon;
-import javax.swing.JPanel;
-
import java.util.List;
import java.util.logging.Logger;
+import javax.swing.ImageIcon;
import javax.swing.JFrame;
+import javax.swing.JPanel;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.common.resources.ResourceManager;
diff --git a/src/net/sf/freecol/client/gui/panel/SaveDialog.java b/src/net/sf/freecol/client/gui/panel/SaveDialog.java
index 2b2713de2..50402569e 100644
--- a/src/net/sf/freecol/client/gui/panel/SaveDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/SaveDialog.java
@@ -20,18 +20,15 @@
package net.sf.freecol.client.gui.panel;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
-
-import javax.swing.JFileChooser;
-import javax.swing.filechooser.FileFilter;
-
import java.io.File;
-
import java.util.List;
+import javax.swing.JFileChooser;
import javax.swing.JFrame;
+import javax.swing.filechooser.FileFilter;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
/**
@@ -54,11 +51,9 @@ public final class SaveDialog extends FreeColDialog {
* @param directory The directory to display when choosing the file.
* @param fileFilters The available file filters in the dialog.
* @param defaultName Name of the default save game file.
- * @param ext The default extension to add to user specified file names.
*/
public SaveDialog(FreeColClient freeColClient, JFrame frame,
- File directory, FileFilter[] fileFilters,
- String defaultName, final String ext) {
+ File directory, FileFilter[] fileFilters, String defaultName) {
super(freeColClient, frame);
final JFileChooser fileChooser = new JFileChooser(directory);
@@ -73,22 +68,11 @@ public final class SaveDialog extends FreeColDialog {
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileHidingEnabled(false);
fileChooser.setSelectedFile(new File(defaultName));
- fileChooser.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- final String cmd = event.getActionCommand();
- if (JFileChooser.APPROVE_SELECTION.equals(cmd)) {
- File file = fileChooser.getSelectedFile();
- if (!file.getName().endsWith(ext)) {
- file = new File(file.getAbsolutePath() + ext);
- }
- setValue(file);
- } else {
- setValue(cancelFile);
- }
- }
- });
-
+ fileChooser.addActionListener((ActionEvent ae) ->
+ setValue((JFileChooser.APPROVE_SELECTION
+ .equals(ae.getActionCommand()))
+ ? fileChooser.getSelectedFile() : cancelFile));
+
List> c = choices();
initializeDialog(frame, DialogType.QUESTION, true, fileChooser, null, c);
}
diff --git a/src/net/sf/freecol/client/gui/panel/ScaleMapSizeDialog.java b/src/net/sf/freecol/client/gui/panel/ScaleMapSizeDialog.java
index 84982f337..8587814dc 100644
--- a/src/net/sf/freecol/client/gui/panel/ScaleMapSizeDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/ScaleMapSizeDialog.java
@@ -33,6 +33,7 @@ import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Map;
@@ -95,12 +96,9 @@ public class ScaleMapSizeDialog extends FreeColDialog {
panel.add(heightPanel);
panel.setSize(panel.getPreferredSize());
- final ActionListener al = new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent event) {
- ScaleMapSizeDialog.this.checkFields();
- }
- };
+ final ActionListener al = (ActionEvent ae) -> {
+ ScaleMapSizeDialog.this.checkFields();
+ };
inputWidth.addActionListener(al);
inputHeight.addActionListener(al);
diff --git a/src/net/sf/freecol/client/gui/panel/SelectAmountDialog.java b/src/net/sf/freecol/client/gui/panel/SelectAmountDialog.java
index 2a367812f..0afb832be 100644
--- a/src/net/sf/freecol/client/gui/panel/SelectAmountDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/SelectAmountDialog.java
@@ -30,7 +30,6 @@ import javax.swing.JTextArea;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Player;
diff --git a/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java b/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java
index fe743c338..a08dc0357 100644
--- a/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/SelectDestinationDialog.java
@@ -21,7 +21,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
-import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
@@ -41,14 +40,13 @@ import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.client.gui.plaf.FreeColComboBoxRenderer;
import net.sf.freecol.common.i18n.Messages;
@@ -73,8 +71,9 @@ import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.UnitTypeChange.ChangeType;
import net.sf.freecol.common.model.pathfinding.GoalDeciders.MultipleAdjacentDecider;
-import net.sf.freecol.common.util.LogBuilder;
import net.sf.freecol.common.resources.ResourceManager;
+import static net.sf.freecol.common.util.CollectionUtils.*;
+import net.sf.freecol.common.util.LogBuilder;
/**
@@ -196,13 +195,8 @@ public final class SelectDestinationDialog extends FreeColDialog
Unit up = (unit.getType().canBeUpgraded(sk,
ChangeType.NATIVES)) ? unit : null;
if (unit.isCarrier()) {
- for (Unit u : unit.getUnitList()) {
- if (u.getType().canBeUpgraded(sk,
- ChangeType.NATIVES)) {
- up = u;
- break;
- }
- }
+ up = find(unit.getUnitList(),
+ u -> u.getType().canBeUpgraded(sk, ChangeType.NATIVES));
}
if (up != null) {
lb.add("[", Messages.getName(sk), "]");
@@ -387,12 +381,9 @@ public final class SelectDestinationDialog extends FreeColDialog
String omcb = Messages.message("selectDestinationDialog.onlyMyColonies");
this.onlyMyColoniesBox = new JCheckBox(omcb, showOnlyMyColonies);
- this.onlyMyColoniesBox.addChangeListener(new ChangeListener() {
- @Override
- public void stateChanged(ChangeEvent event) {
- showOnlyMyColonies = onlyMyColoniesBox.isSelected();
- updateDestinationList();
- }
+ this.onlyMyColoniesBox.addChangeListener((ChangeEvent event) -> {
+ showOnlyMyColonies = onlyMyColoniesBox.isSelected();
+ updateDestinationList();
});
this.comparatorBox = new JComboBox<>(new String[] {
@@ -400,14 +391,11 @@ public final class SelectDestinationDialog extends FreeColDialog
Messages.message("selectDestinationDialog.sortByName"),
Messages.message("selectDestinationDialog.sortByDistance")
});
- this.comparatorBox.addItemListener(new ItemListener() {
- @Override
- public void itemStateChanged(ItemEvent event) {
- updateDestinationComparator();
- Collections.sort(SelectDestinationDialog.this.destinations,
- SelectDestinationDialog.this.destinationComparator);
- updateDestinationList();
- }
+ this.comparatorBox.addItemListener((ItemEvent event) -> {
+ updateDestinationComparator();
+ Collections.sort(SelectDestinationDialog.this.destinations,
+ SelectDestinationDialog.this.destinationComparator);
+ updateDestinationList();
});
this.comparatorBox.setSelectedIndex(
(this.destinationComparator instanceof NameComparator) ? 1
diff --git a/src/net/sf/freecol/client/gui/panel/ServerListPanel.java b/src/net/sf/freecol/client/gui/panel/ServerListPanel.java
index 06ea61828..8ba0f38f4 100644
--- a/src/net/sf/freecol/client/gui/panel/ServerListPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ServerListPanel.java
@@ -184,9 +184,8 @@ public final class ServerListPanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
-
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
try {
switch (Integer.parseInt(command)) {
case CONNECT:
@@ -198,9 +197,9 @@ public final class ServerListPanel extends FreeColPanel {
getGUI().showNewPanel();
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
- } catch (NumberFormatException e) {
+ } catch (NumberFormatException nfe) {
logger.warning("Invalid ActionEvent, not a number: " + command);
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/StartGamePanel.java b/src/net/sf/freecol/client/gui/panel/StartGamePanel.java
index 6afa4a0f7..1450703eb 100644
--- a/src/net/sf/freecol/client/gui/panel/StartGamePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/StartGamePanel.java
@@ -31,10 +31,11 @@ import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.Nation;
@@ -292,10 +293,10 @@ public final class StartGamePanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
final FreeColClient fcc = getFreeColClient();
- final GUI gui = getGUI();
+ final SwingGUI gui = getGUI();
try {
switch (Integer.parseInt(command)) {
case START:
@@ -347,9 +348,9 @@ public final class StartGamePanel extends FreeColPanel {
}
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
}
- } catch (NumberFormatException e) {
+ } catch (NumberFormatException nfe) {
logger.warning("Invalid ActionEvent, not a number: " + command);
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/StatisticsPanel.java b/src/net/sf/freecol/client/gui/panel/StatisticsPanel.java
index 8a823361d..ac8fd6f3b 100644
--- a/src/net/sf/freecol/client/gui/panel/StatisticsPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/StatisticsPanel.java
@@ -23,9 +23,7 @@ import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
@@ -40,6 +38,7 @@ import javax.swing.table.AbstractTableModel;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.i18n.Messages;
+
import static net.sf.freecol.common.util.CollectionUtils.*;
@@ -158,7 +157,8 @@ public final class StatisticsPanel extends FreeColPanel {
// Retrieve the client and server data
Map serverStatistics = igc().getServerStatistics();
- Map clientStatistics = igc().getClientStatistics();
+ Map clientStatistics = freeColClient.getGame()
+ .getStatistics();
// Title
JPanel header = new JPanel();
diff --git a/src/net/sf/freecol/client/gui/panel/TerrainDetailPanel.java b/src/net/sf/freecol/client/gui/panel/TerrainDetailPanel.java
index 394b830f9..0b3b12463 100644
--- a/src/net/sf/freecol/client/gui/panel/TerrainDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/TerrainDetailPanel.java
@@ -19,6 +19,7 @@
package net.sf.freecol.client.gui.panel;
+import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
@@ -36,7 +37,7 @@ import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.FontLibrary;
import net.sf.freecol.client.gui.ImageLibrary;
-import net.sf.freecol.client.gui.MapViewer;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.client.gui.action.ColopediaAction.PanelType;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.AbstractGoods;
@@ -63,25 +64,21 @@ public class TerrainDetailPanel
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
- DefaultMutableTreeNode node =
- new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(), getName(), null));
+ DefaultMutableTreeNode node
+ = new DefaultMutableTreeNode(new ColopediaTreeItem(this, getId(),
+ getName(), null));
for (TileType t : getSpecification().getTileTypeList()) {
- // FIXME: Use different method supporting a direct request of an
- // image of fixed ICON_SIZE.
- final float maxTileImageHeight = ImageLibrary.TILE_OVERLAY_SIZE.height;
- Image tile = MapViewer.createTileImageWithOverlayAndForest(t,
- ImageLibrary.ICON_SIZE.height / maxTileImageHeight);
- BufferedImage image = new BufferedImage(tile.getWidth(null), ImageLibrary.ICON_SIZE.height,
- BufferedImage.TYPE_INT_ARGB);
+ Image tile = SwingGUI.createTileImageWithOverlayAndForest(t,
+ new Dimension(-1, ImageLibrary.ICON_SIZE.height));
+ BufferedImage image = new BufferedImage(tile.getWidth(null),
+ ImageLibrary.ICON_SIZE.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.drawImage(tile, 0, (ImageLibrary.ICON_SIZE.height - tile.getHeight(null)) / 2, null);
g.dispose();
@@ -92,16 +89,11 @@ public class TerrainDetailPanel
}
/**
- * Builds the details panel for the TileType with the given identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (getId().equals(id)) {
- return;
- }
+ if (getId().equals(id)) return;
TileType tileType = getSpecification().getTileType(id);
panel.setLayout(new MigLayout("wrap 4, gap 20"));
@@ -113,13 +105,12 @@ public class TerrainDetailPanel
defenseBonus = ModifierFormat.getModifierAsString(defenceModifiers.iterator().next());
}
- JLabel nameLabel = Utility.localizedLabel(tileType);
- nameLabel.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel nameLabel = Utility.localizedHeaderLabel(tileType, FontLibrary.FontSize.SMALL);
panel.add(nameLabel, "span, align center");
panel.add(Utility.localizedLabel("colopedia.terrain.terrainImage"), "spany 3");
- Image terrainImage = MapViewer.createTileImageWithOverlayAndForest(tileType, 1);
+ Image terrainImage = SwingGUI.createTileImageWithOverlayAndForest(
+ tileType, ImageLibrary.TILE_OVERLAY_SIZE);
panel.add(new JLabel(new ImageIcon(terrainImage)), "spany 3");
List resourceList = tileType.getResourceTypes();
diff --git a/src/net/sf/freecol/client/gui/panel/TilePanel.java b/src/net/sf/freecol/client/gui/panel/TilePanel.java
index 9b1f968f5..c7653316d 100644
--- a/src/net/sf/freecol/client/gui/panel/TilePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/TilePanel.java
@@ -33,11 +33,11 @@ import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.ImageLibrary;
-import net.sf.freecol.client.gui.MapViewer;
import net.sf.freecol.common.debug.DebugUtils;
import net.sf.freecol.common.debug.FreeColDebugger;
import net.sf.freecol.common.i18n.Messages;
@@ -90,9 +90,8 @@ public final class TilePanel extends FreeColPanel {
.addAmount("%y%", tile.getY());
add(Utility.localizedLabel(template), "span, center");
- final MapViewer mapViewer = getGUI().getColonyTileMapViewer();
final ImageLibrary lib = getImageLibrary();
- BufferedImage image = mapViewer.createColonyTileImage(tile, null);
+ BufferedImage image = getGUI().createTileImage(tile);
add(new JLabel(new ImageIcon(image)), "span, center");
if (tile.getRegion() != null) {
@@ -101,7 +100,7 @@ public final class TilePanel extends FreeColPanel {
}
if (tile.getOwner() != null) {
- StringTemplate ownerName = tile.getOwner().getNationName();
+ StringTemplate ownerName = tile.getOwner().getNationLabel();
if (ownerName != null) {
add(Utility.localizedLabel("tilePanel.owner"));
add(Utility.localizedLabel(ownerName));
@@ -220,8 +219,8 @@ public final class TilePanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (OK.equals(command)) {
getGUI().removeFromCanvas(this);
} else {
diff --git a/src/net/sf/freecol/client/gui/panel/TradeRouteInputPanel.java b/src/net/sf/freecol/client/gui/panel/TradeRouteInputPanel.java
index 07a6f96e1..056e1fdae 100644
--- a/src/net/sf/freecol/client/gui/panel/TradeRouteInputPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/TradeRouteInputPanel.java
@@ -26,12 +26,12 @@ import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -52,6 +52,7 @@ import javax.swing.TransferHandler;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.plaf.PanelUI;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
@@ -68,6 +69,7 @@ import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.TradeRoute;
import net.sf.freecol.common.model.TradeRouteStop;
+import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -223,12 +225,7 @@ public final class TradeRouteInputPanel extends FreeColPanel
@Override
public boolean canImport(JComponent c, DataFlavor[] flavors) {
- for (DataFlavor flavor : flavors) {
- if (flavor.equals(DefaultTransferHandler.flavor)) {
- return true;
- }
- }
- return false;
+ return any(flavors, f -> f.equals(DefaultTransferHandler.flavor));
}
}
@@ -345,12 +342,7 @@ public final class TradeRouteInputPanel extends FreeColPanel
*/
@Override
public boolean canImport(JComponent c, DataFlavor[] flavors) {
- for (DataFlavor flavor : flavors) {
- if (flavor.equals(STOP_FLAVOR)) {
- return true;
- }
- }
- return false;
+ return any(flavors, f -> f.equals(STOP_FLAVOR));
}
/**
@@ -465,7 +457,7 @@ public final class TradeRouteInputPanel extends FreeColPanel
} else if (location instanceof Colony) {
Colony colony = (Colony) location;
icon = new JLabel(new ImageIcon(ImageLibrary.getSettlementImage(
- colony, lib.getScalingFactor()* 0.5f)));
+ colony, lib.getScaleFactor()* 0.5f)));
name = new JLabel(colony.getName());
} else {
throw new IllegalStateException("Bogus location: " + location);
@@ -587,27 +579,18 @@ public final class TradeRouteInputPanel extends FreeColPanel
this.messagesBox
= new JCheckBox(Messages.message("tradeRouteInputPanel.silence"));
this.messagesBox.setSelected(tradeRoute.isSilent());
- this.messagesBox.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- tradeRoute.setSilent(messagesBox.isSelected());
- }
+ this.messagesBox.addActionListener((ActionEvent ae) -> {
+ tradeRoute.setSilent(messagesBox.isSelected());
});
this.addStopButton = Utility.localizedButton("tradeRouteInputPanel.addStop");
- this.addStopButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- addSelectedStops();
- }
+ this.addStopButton.addActionListener((ActionEvent ae) -> {
+ addSelectedStops();
});
this.removeStopButton = Utility.localizedButton("tradeRouteInputPanel.removeStop");
- this.removeStopButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- deleteCurrentlySelectedStops();
- }
+ this.removeStopButton.addActionListener((ActionEvent ae) -> {
+ deleteCurrentlySelectedStops();
});
this.goodsPanel = new GoodsPanel();
@@ -764,21 +747,21 @@ public final class TradeRouteInputPanel extends FreeColPanel
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (command == null) return;
switch (command) {
case OK:
if (!verifyNewTradeRoute()) return;
// Return to TradeRoutePanel, which will add the route
// if needed, and it is valid.
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
case CANCEL:
cancelTradeRoute();
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/TradeRoutePanel.java b/src/net/sf/freecol/client/gui/panel/TradeRoutePanel.java
index 0d00dc853..ace6c5c0b 100644
--- a/src/net/sf/freecol/client/gui/panel/TradeRoutePanel.java
+++ b/src/net/sf/freecol/client/gui/panel/TradeRoutePanel.java
@@ -21,7 +21,6 @@ package net.sf.freecol.client.gui.panel;
import java.awt.Component;
import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
@@ -38,7 +37,7 @@ import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
-import javax.swing.event.ListSelectionListener;
+
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
@@ -63,12 +62,7 @@ public final class TradeRoutePanel extends FreeColPanel {
/** Compare trade routes by name. */
private static final Comparator tradeRouteComparator
- = new Comparator() {
- @Override
- public int compare(TradeRoute r1, TradeRoute r2) {
- return r1.getName().compareTo(r2.getName());
- }
- };
+ = Comparator.comparing(TradeRoute::getName);
/** The unit to assign/deassign trade routes for. */
private final Unit unit;
@@ -106,11 +100,8 @@ public final class TradeRoutePanel extends FreeColPanel {
this.unit = unit;
this.tradeRoutes = new JList<>(listModel);
- this.tradeRoutes.addListSelectionListener(new ListSelectionListener() {
- @Override
- public void valueChanged(ListSelectionEvent e) {
- updateButtons();
- }
+ this.tradeRoutes.addListSelectionListener((ListSelectionEvent e) -> {
+ updateButtons();
});
this.tradeRoutes.setCellRenderer(new DefaultListCellRenderer() {
@Override
@@ -139,52 +130,38 @@ public final class TradeRoutePanel extends FreeColPanel {
// listener below.
this.newRouteButton = Utility.localizedButton("tradeRoutePanel.newRoute");
Utility.localizeToolTip(this.newRouteButton, "tradeRoutePanel.new.tooltip");
- this.newRouteButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- newRoute();
- }
+ this.newRouteButton.addActionListener((ActionEvent ae) -> {
+ newRoute();
});
this.editRouteButton = Utility.localizedButton("tradeRoutePanel.editRoute");
Utility.localizeToolTip(this.editRouteButton, "tradeRoutePanel.edit.tooltip");
- this.editRouteButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- final TradeRoute selected
- = tradeRoutes.getSelectedValue();
- final String name = selected.getName();
- getGUI().showTradeRouteInputPanel(selected,
- new Runnable() {
- @Override
- public void run() {
- StringTemplate template = null;
- if (selected.getName() == null) { // Cancelled
- selected.setName(name);
- } else if ((template = selected.verify()) == null) {
- igc().updateTradeRoute(selected);
- updateList(selected);
- } else {
- getGUI().showInformationMessage(template);
- }
- }
- });
- }
+ this.editRouteButton.addActionListener((ActionEvent ae) -> {
+ final TradeRoute selected = tradeRoutes.getSelectedValue();
+ final String name = selected.getName();
+ getGUI().showTradeRouteInputPanel(selected, () -> {
+ StringTemplate template = null;
+ if (selected.getName() == null) { // Cancelled
+ selected.setName(name);
+ } else if ((template = selected.verify()) == null) {
+ igc().updateTradeRoute(selected);
+ updateList(selected);
+ } else {
+ getGUI().showInformationMessage(template);
+ }
+ });
});
this.deleteRouteButton = Utility.localizedButton("tradeRoutePanel.deleteRoute");
Utility.localizeToolTip(this.deleteRouteButton, "tradeRoutePanel.delete.tooltip");
- this.deleteRouteButton.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent e) {
- TradeRoute route = getRoute();
- if (route != null) {
- for (Unit u : route.getAssignedUnits()) {
- igc().assignTradeRoute(u, null);
- }
- deleteTradeRoute(route);
- updateList(null);
+ this.deleteRouteButton.addActionListener((ActionEvent ae) -> {
+ TradeRoute route = getRoute();
+ if (route != null) {
+ for (Unit u : route.getAssignedUnits()) {
+ igc().assignTradeRoute(u, null);
}
+ deleteTradeRoute(route);
+ updateList(null);
}
});
@@ -240,24 +217,18 @@ public final class TradeRoutePanel extends FreeColPanel {
final Player player = getMyPlayer();
final Unit u = this.unit;
final TradeRoute newRoute = igc().getNewTradeRoute(player);
- getGUI().showTradeRouteInputPanel(newRoute,
- new Runnable() {
- @Override
- public void run() {
- StringTemplate template = null;
- if (newRoute.getName() == null) { // Cancelled
- deleteTradeRoute(newRoute);
- updateList(null);
- } else {
- if ((template = newRoute.verify()) == null) {
- igc().updateTradeRoute(newRoute);
- if (u != null) igc().assignTradeRoute(u, newRoute);
- updateList(newRoute);
- } else {
- updateList(null);
- getGUI().showInformationMessage(template);
- }
- }
+ getGUI().showTradeRouteInputPanel(newRoute, () -> {
+ StringTemplate template = null;
+ if (newRoute.getName() == null) { // Cancelled
+ deleteTradeRoute(newRoute);
+ updateList(null);
+ } else if ((template = newRoute.verify()) == null) {
+ igc().updateTradeRoute(newRoute);
+ if (u != null) igc().assignTradeRoute(u, newRoute);
+ updateList(newRoute);
+ } else {
+ updateList(null);
+ getGUI().showInformationMessage(template);
}
});
}
@@ -332,8 +303,8 @@ public final class TradeRoutePanel extends FreeColPanel {
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
- final String command = event.getActionCommand();
+ public void actionPerformed(ActionEvent ae) {
+ final String command = ae.getActionCommand();
if (null == command) return;
final TradeRoute route = getRoute();
switch (command) {
@@ -352,13 +323,13 @@ public final class TradeRoutePanel extends FreeColPanel {
if (unit != null && route != null) {
igc().assignTradeRoute(unit, route);
}
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
case CANCEL:
getGUI().removeTradeRoutePanel(this);
break;
default:
- super.actionPerformed(event);
+ super.actionPerformed(ae);
break;
}
}
diff --git a/src/net/sf/freecol/client/gui/panel/UnitButton.java b/src/net/sf/freecol/client/gui/panel/UnitButton.java
index 53eadb27e..ebc3381dd 100644
--- a/src/net/sf/freecol/client/gui/panel/UnitButton.java
+++ b/src/net/sf/freecol/client/gui/panel/UnitButton.java
@@ -25,10 +25,12 @@ import java.beans.PropertyChangeListener;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Icon;
+import javax.swing.ImageIcon;
import javax.swing.JButton;
import net.sf.freecol.client.gui.action.ActionManager;
import net.sf.freecol.client.gui.action.FreeColAction;
+import net.sf.freecol.common.resources.ResourceManager;
/**
@@ -72,20 +74,21 @@ public final class UnitButton extends JButton {
if (a != null) {
setRolloverEnabled(true);
- Icon bi = (Icon) a.getValue(FreeColAction.BUTTON_IMAGE);
+ String key = (String) a.getValue(FreeColAction.BUTTON_IMAGE);
+ ImageIcon bi = new ImageIcon(ResourceManager.getImage(key));
setIcon(bi);
- setRolloverIcon((Icon) a.getValue(FreeColAction.BUTTON_ROLLOVER_IMAGE));
- setPressedIcon((Icon) a.getValue(FreeColAction.BUTTON_PRESSED_IMAGE));
- setDisabledIcon((Icon) a.getValue(FreeColAction.BUTTON_DISABLED_IMAGE));
+ key = (String) a.getValue(FreeColAction.BUTTON_ROLLOVER_IMAGE);
+ setRolloverIcon(new ImageIcon(ResourceManager.getImage(key)));
+ key = (String) a.getValue(FreeColAction.BUTTON_PRESSED_IMAGE);
+ setPressedIcon(new ImageIcon(ResourceManager.getImage(key)));
+ key = (String) a.getValue(FreeColAction.BUTTON_DISABLED_IMAGE);
+ setDisabledIcon(new ImageIcon(ResourceManager.getImage(key)));
setToolTipText((String) a.getValue(FreeColAction.NAME));
setText(null);
setFocusPainted(false);
setContentAreaFilled(false);
setBorderPainted(false);
- if (bi == null) {
- throw new IllegalArgumentException("The given action is missing \"BUTTON_IMAGE\".");
- }
setSize(bi.getIconWidth(), bi.getIconHeight());
}
}
@@ -118,20 +121,20 @@ public final class UnitButton extends JButton {
button.setIcon(icon);
button.repaint();
} else if (FreeColAction.BUTTON_IMAGE.equals(e.getPropertyName())) {
- Icon icon = (Icon) e.getNewValue();
- button.setIcon(icon);
+ String key = (String) e.getNewValue();
+ button.setIcon(new ImageIcon(ResourceManager.getImage(key)));
button.repaint();
} else if (FreeColAction.BUTTON_ROLLOVER_IMAGE.equals(e.getPropertyName())) {
- Icon icon = (Icon) e.getNewValue();
- button.setRolloverIcon(icon);
+ String key = (String) e.getNewValue();
+ button.setRolloverIcon(new ImageIcon(ResourceManager.getImage(key)));
button.repaint();
} else if (FreeColAction.BUTTON_PRESSED_IMAGE.equals(e.getPropertyName())) {
- Icon icon = (Icon) e.getNewValue();
- button.setPressedIcon(icon);
+ String key = (String) e.getNewValue();
+ button.setPressedIcon(new ImageIcon(ResourceManager.getImage(key)));
button.repaint();
} else if (FreeColAction.BUTTON_DISABLED_IMAGE.equals(e.getPropertyName())) {
- Icon icon = (Icon) e.getNewValue();
- button.setDisabledIcon(icon);
+ String key = (String) e.getNewValue();
+ button.setDisabledIcon(new ImageIcon(ResourceManager.getImage(key)));
button.repaint();
} else if (Action.MNEMONIC_KEY.equals(e.getPropertyName())) {
Integer mn = (Integer) e.getNewValue();
diff --git a/src/net/sf/freecol/client/gui/panel/UnitDetailPanel.java b/src/net/sf/freecol/client/gui/panel/UnitDetailPanel.java
index 219104224..1390a4472 100644
--- a/src/net/sf/freecol/client/gui/panel/UnitDetailPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/UnitDetailPanel.java
@@ -23,6 +23,7 @@ import java.awt.GridLayout;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import java.util.stream.Collectors;
import javax.swing.JButton;
import javax.swing.JLabel;
@@ -46,8 +47,10 @@ import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.IndianNationType;
import net.sf.freecol.common.model.Modifier;
import net.sf.freecol.common.model.Player;
+import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.UnitType;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.RandomChoice;
@@ -56,12 +59,12 @@ import net.sf.freecol.common.util.RandomChoice;
*/
public class UnitDetailPanel extends ColopediaGameObjectTypePanel {
- // layout of production modifier panel
+ /** Layout of production modifier panel. */
private static final int MODIFIERS_PER_ROW = 5;
/**
- * Creates a new instance of this ColopediaDetailPanel.
+ * Creates a new instance of this colopedia subpanel.
*
* @param freeColClient The FreeColClient
for the game.
* @param colopediaPanel The parent ColopediaPanel.
@@ -72,49 +75,29 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel {
}
+ // Implement ColopediaDetailPanel
+
/**
- * Adds one or several subtrees for all the objects for which this
- * ColopediaDetailPanel could build a detail panel to the given
- * root node.
- *
- * @param root a DefaultMutableTreeNode
+ * {@inheritDoc}
*/
@Override
public void addSubTrees(DefaultMutableTreeNode root) {
- List units = new ArrayList<>();
- List skills = new ArrayList<>();
- for (UnitType u : getSpecification().getUnitTypeList()) {
- if (u.getSkill() <= 0 || u.hasAbility(Ability.EXPERT_SOLDIER)) {
- units.add(u);
- } else {
- skills.add(u);
- }
- }
- super.addSubTrees(root, "colopediaAction." + PanelType.UNITS.getKey(),
- units);
- super.addSubTrees(root, "colopediaAction." + PanelType.SKILLS.getKey(),
- skills);
+ super.addSubTrees(root, getId(),
+ new ArrayList<>(getSpecification().getUnitTypeList()));
}
/**
- * Builds the details panel for the UnitType with the given identifier.
- *
- * @param id The object identifier.
- * @param panel the detail panel to build
+ * {@inheritDoc}
*/
@Override
public void buildDetail(String id, JPanel panel) {
- if (getId().equals(id)
- || ("colopediaAction." + PanelType.SKILLS.getKey()).equals(id)) {
- return;
- }
+ if (getId().equals(id)) return;
- UnitType type = getSpecification().getUnitType(id);
+ final Specification spec = getSpecification();
+ UnitType type = spec.getUnitType(id);
panel.setLayout(new MigLayout("wrap 4", "[]20[]40[]20[]"));
- JLabel name = Utility.localizedLabel(type);
- name.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- FontLibrary.FontSize.SMALL));
+ JLabel name = Utility.localizedHeaderLabel(type, FontLibrary.FontSize.SMALL);
panel.add(name, "span, align center, wrap 40");
panel.add(Utility.localizedLabel("colopedia.unit.offensivePower"));
@@ -152,8 +135,9 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel {
panel.add(new JLabel(Integer.toString(type.getSkill())), "right");
List schools = new ArrayList<>();
- for (final BuildingType buildingType : getSpecification().getBuildingTypeList()) {
- if (buildingType.hasAbility(Ability.TEACH) && buildingType.canAdd(type)) {
+ for (BuildingType buildingType : spec.getBuildingTypeList()) {
+ if (buildingType.hasAbility(Ability.TEACH)
+ && buildingType.canAdd(type)) {
schools.add(buildingType);
}
}
@@ -172,14 +156,9 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel {
}
}
- List nations = new ArrayList<>();
- for (IndianNationType nation : getSpecification().getIndianNationTypes()) {
- for (RandomChoice choice : nation.getSkills()) {
- if (choice.getObject() == type) {
- nations.add(nation);
- }
- }
- }
+ List nations = spec.getIndianNationTypes().stream()
+ .filter(nt -> any(nt.getSkills(), ut -> ut.getObject() == type))
+ .collect(Collectors.toList());
if (!nations.isEmpty()) {
panel.add(Utility.localizedLabel("colopedia.unit.natives"), "newline");
int count = 0;
@@ -211,7 +190,7 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel {
}
List bonusList = new ArrayList<>();
- for (GoodsType goodsType : getSpecification().getGoodsTypeList()) {
+ for (GoodsType goodsType : spec.getGoodsTypeList()) {
bonusList.addAll(type.getModifiers(goodsType.getId()));
}
int bonusNumber = bonusList.size();
@@ -223,7 +202,7 @@ public class UnitDetailPanel extends ColopediaGameObjectTypePanel {
JPanel productionPanel = new JPanel(new GridLayout(0, MODIFIERS_PER_ROW));
productionPanel.setOpaque(false);
for (Modifier productionBonus : bonusList) {
- GoodsType goodsType = getSpecification().getGoodsType(productionBonus.getId());
+ GoodsType goodsType = spec.getGoodsType(productionBonus.getId());
String bonus = ModifierFormat.getModifierAsString(productionBonus);
productionPanel.add(getGoodsButton(goodsType, bonus));
}
diff --git a/src/net/sf/freecol/client/gui/panel/UnitLabel.java b/src/net/sf/freecol/client/gui/panel/UnitLabel.java
index 0f6a5cb7b..bb867ce85 100644
--- a/src/net/sf/freecol/client/gui/panel/UnitLabel.java
+++ b/src/net/sf/freecol/client/gui/panel/UnitLabel.java
@@ -36,8 +36,8 @@ import javax.swing.JLabel;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.control.InGameController;
import net.sf.freecol.client.gui.FontLibrary;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.client.gui.ImageLibrary;
+import net.sf.freecol.client.gui.SwingGUI;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.AbstractGoods;
@@ -47,12 +47,10 @@ import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Specification;
-import net.sf.freecol.common.model.Tile;
-import net.sf.freecol.common.model.TileType;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.WorkLocation;
-import static net.sf.freecol.common.util.StringUtils.*;
+import static net.sf.freecol.common.util.StringUtils.lastPart;
/**
@@ -83,7 +81,7 @@ public final class UnitLabel extends JLabel
private final FreeColClient freeColClient;
- private final GUI gui;
+ private final SwingGUI gui;
private final Unit unit;
@@ -93,7 +91,7 @@ public final class UnitLabel extends JLabel
private boolean ignoreLocation;
- private boolean useMapImageLibrary;
+ private boolean useTileImageLibrary;
/**
@@ -140,20 +138,20 @@ public final class UnitLabel extends JLabel
* @param isSmall The image will be smaller if set to true
.
* @param ignoreLocation The image will not include production or state
* information if set to true
.
- * @param useMapImageLibrary If false use ImageLibrary in gui.
- * If true use ImageLibrary in gui.getColonyTileMapViewer().
+ * @param useTileImageLibrary If false use ImageLibrary in GUI.
+ * If true use tileImageLibrary in SwingGUI.
*/
public UnitLabel(FreeColClient freeColClient, Unit unit,
boolean isSmall, boolean ignoreLocation,
- boolean useMapImageLibrary) {
+ boolean useTileImageLibrary) {
this.freeColClient = freeColClient;
- this.gui = freeColClient.getGUI();
+ this.gui = (SwingGUI)freeColClient.getGUI();
this.unit = unit;
selected = false;
this.isSmall = isSmall;
this.ignoreLocation = ignoreLocation;
- this.useMapImageLibrary = useMapImageLibrary;
+ this.useTileImageLibrary = useTileImageLibrary;
updateIcon();
}
@@ -194,8 +192,8 @@ public final class UnitLabel extends JLabel
* @param isSmall The image will be smaller if set to true
.
*/
public void setSmall(boolean isSmall) {
- final ImageLibrary lib = useMapImageLibrary
- ? gui.getColonyTileMapViewer().getImageLibrary()
+ final ImageLibrary lib = useTileImageLibrary
+ ? gui.getTileImageLibrary()
: gui.getImageLibrary();
if (isSmall) {
ImageIcon imageIcon = new ImageIcon(lib.getSmallUnitImage(unit));
@@ -210,12 +208,10 @@ public final class UnitLabel extends JLabel
ImageIcon imageIcon = new ImageIcon(lib.getUnitImage(unit));
ImageIcon disabledImageIcon = new ImageIcon(lib.getUnitImage(unit, true));
if (unit.getLocation() instanceof ColonyTile) {
- final Tile tile = unit.getLocation().getTile();
- final TileType tileType = tile.getType();
- final Image image = lib.getTerrainImage(tileType, tile.getX(),
- tile.getY());
- setSize(new Dimension(image.getWidth(null) / 2,
- imageIcon.getIconHeight()));
+ Dimension tileSize = lib.scaleDimension(ImageLibrary.TILE_SIZE);
+ tileSize.width /= 2;
+ tileSize.height = imageIcon.getIconHeight();
+ setSize(tileSize);
} else {
setPreferredSize(null);
}
@@ -261,8 +257,8 @@ public final class UnitLabel extends JLabel
@Override
public void paintComponent(Graphics g) {
final Player player = freeColClient.getMyPlayer();
- final ImageLibrary lib = useMapImageLibrary
- ? gui.getColonyTileMapViewer().getImageLibrary()
+ final ImageLibrary lib = useTileImageLibrary
+ ? gui.getTileImageLibrary()
: gui.getImageLibrary();
if (ignoreLocation || selected
|| (!unit.isCarrier() && unit.getState() != Unit.UnitState.SENTRY)) {
@@ -301,7 +297,7 @@ public final class UnitLabel extends JLabel
String underRepair1 = underRepair.substring(0, underRepair.indexOf('(')).trim();
String underRepair2 = underRepair.substring(underRepair.indexOf('(')).trim();
Font font = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.TINY, lib.getScalingFactor());
+ FontLibrary.FontSize.TINY, lib.getScaleFactor());
Image repairImage1 = lib.getStringImage(g, underRepair1, Color.RED, font);
Image repairImage2 = lib.getStringImage(g, underRepair2, Color.RED, font);
int textHeight = repairImage1.getHeight(null) + repairImage2.getHeight(null);
@@ -370,11 +366,11 @@ public final class UnitLabel extends JLabel
* {@inheritDoc}
*/
@Override
- public void actionPerformed(ActionEvent event) {
+ public void actionPerformed(ActionEvent ae) {
final Game game = freeColClient.getGame();
final Specification spec = game.getSpecification();
final InGameController igc = freeColClient.getInGameController();
- String[] args = event.getActionCommand().split("/");
+ String[] args = ae.getActionCommand().split("/");
GoodsType gt;
switch (Enum.valueOf(UnitAction.class,
args[0].toUpperCase(Locale.US))) {
diff --git a/src/net/sf/freecol/client/gui/panel/UnitPanel.java b/src/net/sf/freecol/client/gui/panel/UnitPanel.java
index 50c4c18d8..caa5f3299 100644
--- a/src/net/sf/freecol/client/gui/panel/UnitPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/UnitPanel.java
@@ -66,6 +66,8 @@ public abstract class UnitPanel extends MigPanel
cleanup();
addPropertyChangeListeners();
update();
+ Unit active = portPanel.getGUI().getActiveUnit();
+ if (active != null && active.isCarrier()) setSelectedUnit(active);
}
/**
diff --git a/src/net/sf/freecol/client/gui/panel/Utility.java b/src/net/sf/freecol/client/gui/panel/Utility.java
index 5fddf4f9c..0e9796a4b 100644
--- a/src/net/sf/freecol/client/gui/panel/Utility.java
+++ b/src/net/sf/freecol/client/gui/panel/Utility.java
@@ -48,8 +48,13 @@ import javax.swing.text.StyleContext;
import net.sf.freecol.client.gui.FontLibrary;
import net.sf.freecol.common.i18n.Messages;
+import net.sf.freecol.common.model.FreeColGameObject;
+import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Named;
+import net.sf.freecol.common.model.Player;
+import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.StringTemplate;
+import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.resources.ResourceManager;
@@ -171,6 +176,43 @@ public final class Utility {
return button;
}
+ /**
+ * Make a suitable link button for a given key.
+ *
+ * Colonies and Europe-like objects are obvious, locations and units
+ * are dependent on the message source.
+ * TODO: Are there more useful possibilities?
+ *
+ * @param key The message key to make a link for.
+ * @param val The text for the link.
+ * @param player The Player
to make a link for.
+ * @param source The message source FreeColGameObject
.
+ * @return A JButton
for the link, or null if no good
+ * choice found.
+ */
+ public static JButton getMessageButton(String key, String val,
+ Player player, FreeColGameObject source) {
+ FreeColGameObject link = null;
+ if ("%colony%".equals(key) || key.endsWith("Colony%")) {
+ Settlement settlement = player.getGame().getSettlementByName(val);
+ link = (settlement == null) ? null
+ : (player.owns(settlement)) ? settlement
+ : settlement.getTile();
+ } else if ("%europe%".equals(key) || "%market%".equals(key)) {
+ link = player.getEurope();
+ } else if ("%location%".equals(key) || key.endsWith("Location%")) {
+ if (source instanceof Location) {
+ link = source.getLinkTarget(player);
+ }
+ } else if ("%unit%".equals(key) || key.endsWith("Unit%")) {
+ if (source instanceof Unit) {
+ link = source.getLinkTarget(player);
+ }
+ }
+ return (link == null) ? null
+ : getLinkButton(val, null, link.getId());
+ }
+
/**
* Creates a text area with standard settings suitable for use in FreeCol
* panels, without setting its size.
@@ -233,7 +275,14 @@ public final class Utility {
* @return The default JTextPane
to use.
*/
public static JTextPane getDefaultTextPane() {
- return getDefaultTextPane(null);
+ DefaultStyledDocument document
+ = new DefaultStyledDocument(STYLE_CONTEXT);
+
+ JTextPane textPane = new JTextPane(document);
+ textPane.setOpaque(false);
+ textPane.setEditable(false);
+ textPane.setLogicalStyle(STYLE_CONTEXT.getStyle("regular"));
+ return textPane;
}
/**
@@ -243,14 +292,7 @@ public final class Utility {
* @return A suitable JTextPane
.
*/
public static JTextPane getDefaultTextPane(String text) {
- DefaultStyledDocument document
- = new DefaultStyledDocument(STYLE_CONTEXT);
-
- JTextPane textPane = new JTextPane(document);
- textPane.setOpaque(false);
- textPane.setEditable(false);
- textPane.setLogicalStyle(STYLE_CONTEXT.getStyle("regular"));
-
+ JTextPane textPane = getDefaultTextPane();
textPane.setText(text);
return textPane;
}
@@ -353,6 +395,55 @@ public final class Utility {
return new JCheckBoxMenuItem(Messages.message(key), value);
}
+ /**
+ * Gets a default header for panels containing a localized message.
+ *
+ * @param key The message key to use.
+ * @param small If true, use a smaller font.
+ * @return A suitable JLabel
.
+ */
+ public static JLabel localizedHeader(String key, boolean small) {
+ JLabel header = localizedHeaderLabel(key, SwingConstants.CENTER,
+ (small ? FontLibrary.FontSize.SMALL : FontLibrary.FontSize.BIG));
+ header.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
+ return header;
+ }
+
+ /**
+ * Gets a label containing a localized message using the header font.
+ *
+ * @param key The message key to use.
+ * @param alignment The alignment.
+ * @param size The font size.
+ * @return A suitable JLabel
.
+ */
+ public static JLabel localizedHeaderLabel(String key, int alignment,
+ FontLibrary.FontSize size) {
+ String text = Messages.message(key);
+ JLabel header = new JLabel(text, alignment);
+ header.setFont(FontLibrary.createCompatibleFont(
+ text, FontLibrary.FontType.HEADER, size));
+ header.setOpaque(false);
+ return header;
+ }
+
+ public static JLabel localizedHeaderLabel(StringTemplate template,
+ int alignment,
+ FontLibrary.FontSize size) {
+ String text = Messages.message(template);
+ JLabel header = new JLabel(text, alignment);
+ header.setFont(FontLibrary.createCompatibleFont(
+ text, FontLibrary.FontType.HEADER, size));
+ header.setOpaque(false);
+ return header;
+ }
+
+ public static JLabel localizedHeaderLabel(Named named,
+ FontLibrary.FontSize size) {
+ return localizedHeaderLabel(named.getNameKey(),
+ SwingConstants.LEADING, size);
+ }
+
/**
* Get a JLabel with a named object.
*
@@ -363,21 +454,6 @@ public final class Utility {
return localizedLabel(named.getNameKey());
}
- /**
- * Gets a default header for panels containing a localized message.
- *
- * @param key The message key to use.
- * @param small If true, use a smaller font.
- * @return A suitable JLabel
.
- */
- public static JLabel localizedHeader(String key, boolean small) {
- JLabel header = new JLabel(Messages.message(key), JLabel.CENTER);
- header.setFont(FontLibrary.createFont(FontLibrary.FontType.HEADER,
- (small) ? FontLibrary.FontSize.SMALL : FontLibrary.FontSize.BIG));
- header.setBorder(BorderFactory.createEmptyBorder(20, 0, 20, 0));
- return header;
- }
-
/**
* Get a JLabel with Messages.message(key) as text.
*
@@ -385,30 +461,7 @@ public final class Utility {
* @return The JLabel
.
*/
public static JLabel localizedLabel(String key) {
- return localizedLabel(key, SwingConstants.LEADING);
- }
-
- /**
- * Get a JLabel with Messages.message(key) as text.
- *
- * @param key The key to use.
- * @param alignment The alignment.
- * @return The JLabel
.
- */
- public static JLabel localizedLabel(String key, int alignment) {
- return localizedLabel(key, null, alignment);
- }
-
- /**
- * Get a JLabel with Messages.message(key) as text.
- *
- * @param key The key to use.
- * @param icon The icon to use.
- * @param alignment The alignment.
- * @return The JLabel
.
- */
- public static JLabel localizedLabel(String key, Icon icon, int alignment) {
- return localizedLabel(StringTemplate.key(key), icon, alignment);
+ return localizedLabel(StringTemplate.key(key));
}
/**
@@ -418,7 +471,9 @@ public final class Utility {
* @return The JLabel
.
*/
public static JLabel localizedLabel(StringTemplate template) {
- return localizedLabel(template, null, SwingConstants.LEADING);
+ JLabel label = new JLabel(Messages.message(template));
+ label.setOpaque(false);
+ return label;
}
/**
@@ -431,7 +486,9 @@ public final class Utility {
*/
public static JLabel localizedLabel(StringTemplate template, Icon icon,
int alignment) {
- return new JLabel(Messages.message(template), icon, alignment);
+ JLabel label = new JLabel(Messages.message(template), icon, alignment);
+ label.setOpaque(false);
+ return label;
}
/**
diff --git a/src/net/sf/freecol/client/gui/panel/VictoryDialog.java b/src/net/sf/freecol/client/gui/panel/VictoryDialog.java
index d41e015cf..34d098b24 100644
--- a/src/net/sf/freecol/client/gui/panel/VictoryDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/VictoryDialog.java
@@ -47,7 +47,7 @@ public final class VictoryDialog extends FreeColConfirmDialog {
super(freeColClient, frame);
MigPanel panel = new MigPanel(new MigLayout("wrap 1", "", ""));
- panel.add(Utility.localizedHeader(Messages.nameKey("victoryDialog"),
+ panel.add(Utility.localizedHeader(Messages.message("victory.text"),
false),
"align center, wrap 20");
Image image = ResourceManager.getImage("image.flavor.Victory");
diff --git a/src/net/sf/freecol/client/gui/panel/WarehouseDialog.java b/src/net/sf/freecol/client/gui/panel/WarehouseDialog.java
index c63da19fb..e228e3a15 100644
--- a/src/net/sf/freecol/client/gui/panel/WarehouseDialog.java
+++ b/src/net/sf/freecol/client/gui/panel/WarehouseDialog.java
@@ -34,7 +34,6 @@ import javax.swing.SpinnerNumberModel;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.FreeColClient;
-import net.sf.freecol.client.gui.GUI;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.Colony;
diff --git a/src/net/sf/freecol/client/gui/panel/WorkProductionPanel.java b/src/net/sf/freecol/client/gui/panel/WorkProductionPanel.java
index 69973ff16..555d7f449 100644
--- a/src/net/sf/freecol/client/gui/panel/WorkProductionPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/WorkProductionPanel.java
@@ -89,8 +89,7 @@ public class WorkProductionPanel extends FreeColPanel {
final TileType tileType = tile.getType();
shortName = Messages.getName(tileType);
longName = Messages.message(colonyTile.getLabel());
- image = getGUI().getColonyTileMapViewer()
- .createColonyTileImage(tile, colony);
+ image = getGUI().createColonyTileImage(tile, colony);
} else if (wl instanceof Building) {
final Building building = (Building)wl;
@@ -119,7 +118,7 @@ public class WorkProductionPanel extends FreeColPanel {
}
Font bigFont = FontLibrary.createFont(FontLibrary.FontType.NORMAL,
- FontLibrary.FontSize.SMALLER, Font.BOLD, lib.getScalingFactor());
+ FontLibrary.FontSize.SMALLER, Font.BOLD, lib.getScaleFactor());
JLabel finalLabel = Utility.localizedLabel("finalResult");
finalLabel.setFont(bigFont);
add(finalLabel, "newline");
diff --git a/src/net/sf/freecol/client/gui/plaf/FreeColOptionPaneUI.java b/src/net/sf/freecol/client/gui/plaf/FreeColOptionPaneUI.java
index 4df0492fa..26575afd9 100644
--- a/src/net/sf/freecol/client/gui/plaf/FreeColOptionPaneUI.java
+++ b/src/net/sf/freecol/client/gui/plaf/FreeColOptionPaneUI.java
@@ -25,7 +25,6 @@ import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionListener;
import java.awt.event.HierarchyEvent;
-import java.awt.event.HierarchyListener;
import javax.swing.Icon;
import javax.swing.JButton;
@@ -40,7 +39,7 @@ import javax.swing.plaf.basic.BasicOptionPaneUI;
import net.miginfocom.swing.MigLayout;
import net.sf.freecol.client.gui.ImageLibrary;
-import net.sf.freecol.client.gui.panel.ChoiceItem;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.client.gui.panel.MigPanel;
import net.sf.freecol.common.i18n.Messages;
@@ -170,15 +169,11 @@ public class FreeColOptionPaneUI extends BasicOptionPaneUI {
if (0 <= initialIndex && initialIndex < buttons.length) {
JButton b = newButtons[initialIndex];
this.initialFocusComponent = b;
- b.addHierarchyListener(new HierarchyListener() {
- @Override
- public void hierarchyChanged(HierarchyEvent e) {
- if ((e.getChangeFlags()
- & HierarchyEvent.PARENT_CHANGED) != 0) {
- JButton b = (JButton)e.getComponent();
- JRootPane root = SwingUtilities.getRootPane(b);
- if (root != null) root.setDefaultButton(b);
- }
+ b.addHierarchyListener((HierarchyEvent e) -> {
+ if ((e.getChangeFlags() & HierarchyEvent.PARENT_CHANGED) != 0) {
+ JButton button = (JButton)e.getComponent();
+ JRootPane root = SwingUtilities.getRootPane(button);
+ if (root != null) root.setDefaultButton(button);
}
});
}
diff --git a/src/net/sf/freecol/client/gui/video/VideoComponent.java b/src/net/sf/freecol/client/gui/video/VideoComponent.java
index 9eb3669f0..dc73e11d6 100644
--- a/src/net/sf/freecol/client/gui/video/VideoComponent.java
+++ b/src/net/sf/freecol/client/gui/video/VideoComponent.java
@@ -27,11 +27,11 @@ import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.border.Border;
+import com.fluendo.player.Cortado;
+
import net.sf.freecol.client.gui.panel.FreeColImageBorder;
import net.sf.freecol.common.resources.Video;
-import com.fluendo.player.Cortado;
-
/**
* A component for playing video.
@@ -55,6 +55,7 @@ public class VideoComponent extends JPanel {
public VideoComponent(Video video, boolean mute) {
final String url = video.getURL().toExternalForm();
+ setOpaque(false);
setBorder(createBorder());
final Insets insets = getInsets();
@@ -77,11 +78,9 @@ public class VideoComponent extends JPanel {
// Disable the feature that seems to be missing from the stock Cortado
//applet.setStopListener(new StopListener() {
// public void stopped() {
- // SwingUtilities.invokeLater(new Runnable() {
- // public void run() {
- // for (VideoListener sl : videoListeners) {
- // sl.stopped();
- // }
+ // SwingUtilities.invokeLater(() -> {
+ // for (VideoListener sl : videoListeners) {
+ // sl.stopped();
// }
// });
// }
diff --git a/src/net/sf/freecol/common/debug/DebugUtils.java b/src/net/sf/freecol/common/debug/DebugUtils.java
index 7671d8abd..ab8d1b203 100644
--- a/src/net/sf/freecol/common/debug/DebugUtils.java
+++ b/src/net/sf/freecol/common/debug/DebugUtils.java
@@ -20,20 +20,21 @@
package net.sf.freecol.common.debug;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.event.ChangeEvent;
-import javax.swing.event.ChangeListener;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.client.gui.GUI;
-import net.sf.freecol.client.gui.panel.ChoiceItem;
+import net.sf.freecol.client.gui.ChoiceItem;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.io.FreeColXMLWriter.WriteScope;
import net.sf.freecol.common.model.Building;
@@ -63,8 +64,10 @@ import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.option.BooleanOption;
import net.sf.freecol.common.util.LogBuilder;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.RandomChoice;
import static net.sf.freecol.common.util.StringUtils.*;
+
import net.sf.freecol.server.FreeColServer;
import net.sf.freecol.server.ai.AIColony;
import net.sf.freecol.server.ai.AIMain;
@@ -113,16 +116,14 @@ public class DebugUtils {
final GUI gui = freeColClient.getGUI();
final Player player = freeColClient.getMyPlayer();
- List> buildings = new ArrayList<>();
- for (BuildingType b : game.getSpecification().getBuildingTypeList()) {
- String msg = Messages.getName(b);
- buildings.add(new ChoiceItem<>(msg, b));
- }
- Collections.sort(buildings);
-
- BuildingType buildingType
- = gui.getChoice(true, null, buildingTitle, null, "cancel",
- buildings);
+ BuildingType buildingType = gui.getChoice(null, buildingTitle,
+ "cancel",
+ game.getSpecification().getBuildingTypeList().stream()
+ .map(bt -> {
+ String msg = Messages.getName(bt);
+ return new ChoiceItem(msg, bt);
+ })
+ .sorted().collect(Collectors.toList()));
if (buildingType == null) return;
final Game sGame = server.getGame();
@@ -172,17 +173,15 @@ public class DebugUtils {
final Player sPlayer = sGame.getFreeColGameObject(player.getId(),
Player.class);
- List> fathers = new ArrayList<>();
- for (FoundingFather father : sSpec.getFoundingFathers()) {
- if (!sPlayer.hasFather(father)) {
- String msg = Messages.getName(father);
- fathers.add(new ChoiceItem<>(msg, father));
- }
- }
- Collections.sort(fathers);
-
- FoundingFather father = gui.getChoice(true, null, fatherTitle, null,
- "cancel", fathers);
+ FoundingFather father = gui.getChoice(null, fatherTitle,
+ "cancel",
+ sSpec.getFoundingFathers().stream()
+ .filter(f -> !sPlayer.hasFather(f))
+ .map(f -> {
+ String msg = Messages.getName(f);
+ return new ChoiceItem(msg, f);
+ })
+ .sorted().collect(Collectors.toList()));
if (father != null) {
server.getInGameController()
.addFoundingFather((ServerPlayer)sPlayer, father);
@@ -204,7 +203,7 @@ public class DebugUtils {
final Player sPlayer = sGame.getFreeColGameObject(player.getId(),
Player.class);
- String response = gui.getInput(true, null,
+ String response = gui.getInput(null,
StringTemplate.template("prompt.selectGold"),
Integer.toString(1000), "ok", "cancel");
if (response == null || response.isEmpty()) return;
@@ -233,7 +232,7 @@ public class DebugUtils {
final Player sPlayer = sGame.getFreeColGameObject(player.getId(),
Player.class);
- String response = gui.getInput(true, null,
+ String response = gui.getInput(null,
StringTemplate.template("prompt.selectImmigration"),
Integer.toString(100), "ok", "cancel");
if (response == null || response.isEmpty()) return;
@@ -260,7 +259,7 @@ public class DebugUtils {
final Player player = freeColClient.getMyPlayer();
final Game sGame = server.getGame();
- String response = gui.getInput(true, null,
+ String response = gui.getInput(null,
StringTemplate.template("prompt.selectLiberty"),
Integer.toString(100), "ok", "cancel");
if (response == null || response.isEmpty()) return;
@@ -290,15 +289,12 @@ public class DebugUtils {
final FreeColServer server = freeColClient.getFreeColServer();
if (server == null) return;
- menu.addChangeListener(new ChangeListener() {
- @Override
- public void stateChanged(ChangeEvent e) {
- boolean skipping = server.getInGameController()
- .getSkippedTurns() > 0;
- item.setText(Messages.message((skipping)
- ? "menuBar.debug.stopSkippingTurns"
- : "menuBar.debug.skipTurns"));
- }
+ menu.addChangeListener((ChangeEvent e) -> {
+ boolean skipping = server.getInGameController()
+ .getSkippedTurns() > 0;
+ item.setText(Messages.message((skipping)
+ ? "menuBar.debug.stopSkippingTurns"
+ : "menuBar.debug.skipTurns"));
});
}
@@ -321,26 +317,20 @@ public class DebugUtils {
final Tile sTile = sGame.getFreeColGameObject(tile.getId(), Tile.class);
final GUI gui = freeColClient.getGUI();
- List> uts = new ArrayList<>();
- for (UnitType t : sSpec.getUnitTypeList()) {
- String msg = Messages.getName(t);
- uts.add(new ChoiceItem<>(msg, t));
- }
- Collections.sort(uts);
- UnitType unitChoice = gui.getChoice(true, null,
- StringTemplate.template("prompt.selectUnitType"),
- null, "cancel", uts);
+ UnitType unitChoice = gui.getChoice(null,
+ StringTemplate.template("prompt.selectUnitType"), "cancel",
+ sSpec.getUnitTypeList().stream()
+ .map(ut -> {
+ String msg = Messages.getName(ut);
+ return new ChoiceItem(msg, ut);
+ })
+ .sorted().collect(Collectors.toList()));
if (unitChoice == null) return;
Unit carrier = null, sCarrier = null;
if (!sTile.isLand() && !unitChoice.isNaval()) {
- for (Unit u : sTile.getUnitList()) {
- if (u.isNaval()
- && u.getSpaceLeft() >= unitChoice.getSpaceTaken()) {
- sCarrier = u;
- break;
- }
- }
+ sCarrier = find(sTile.getUnitList(), u -> u.isNaval()
+ && u.getSpaceLeft() >= unitChoice.getSpaceTaken());
}
Location loc = (sCarrier != null) ? sCarrier : sTile;
ServerUnit sUnit = new ServerUnit(sGame, loc, sPlayer,
@@ -382,12 +372,19 @@ public class DebugUtils {
gtl.add(new ChoiceItem<>(msg, t));
}
Collections.sort(gtl);
- GoodsType goodsType = gui.getChoice(true, null,
+ GoodsType goodsType = gui.getChoice(null,
StringTemplate.template("prompt.selectGoodsType"),
- null, "cancel", gtl);
+ "cancel",
+ sSpec.getGoodsTypeList().stream()
+ .filter(gt -> !gt.isFoodType() || gt == sSpec.getPrimaryFoodType())
+ .map(gt -> {
+ String msg = Messages.getName(gt);
+ return new ChoiceItem(msg, gt);
+ })
+ .sorted().collect(Collectors.toList()));
if (goodsType == null) return;
- String amount = gui.getInput(true, null,
+ String amount = gui.getInput(null,
StringTemplate.template("prompt.selectGoodsAmount"),
"20", "ok", "cancel");
if (amount == null) return;
@@ -424,16 +421,15 @@ public class DebugUtils {
.addName("%colony%", colony.getName()));
return;
}
- List> choices = new ArrayList<>();
- for (RandomChoice rc : disasters) {
- String label = Messages.getName(rc.getObject())
- + " " + Integer.toString(rc.getProbability());
- choices.add(new ChoiceItem<>(label, rc.getObject()));
- }
- Collections.sort(choices);
- Disaster disaster = gui.getChoice(true, null,
- StringTemplate.template("prompt.selectDisaster"),
- null, "cancel", choices);
+ Disaster disaster = gui.getChoice(null,
+ StringTemplate.template("prompt.selectDisaster"), "cancel",
+ disasters.stream()
+ .map(rc -> {
+ String label = Messages.getName(rc.getObject())
+ + " " + Integer.toString(rc.getProbability());
+ return new ChoiceItem(label, rc.getObject());
+ })
+ .sorted().collect(Collectors.toList()));
if (disaster == null) return;
final FreeColServer server = freeColClient.getFreeColServer();
@@ -469,15 +465,14 @@ public class DebugUtils {
final GUI gui = freeColClient.getGUI();
final Game game = freeColClient.getGame();
- List> pcs = new ArrayList<>();
- for (Player p : game.getLiveEuropeanPlayers(colony.getOwner())) {
- String msg = Messages.message(p.getNationName());
- pcs.add(new ChoiceItem<>(msg, p));
- }
- Collections.sort(pcs);
- Player player = gui.getChoice(true, null,
- StringTemplate.template("prompt.selectOwner"),
- null, "cancel", pcs);
+ Player player = gui.getChoice(null,
+ StringTemplate.template("prompt.selectOwner"), "cancel",
+ game.getLiveEuropeanPlayers(colony.getOwner()).stream()
+ .map(p -> {
+ String msg = Messages.message(p.getCountryLabel());
+ return new ChoiceItem(msg, p);
+ })
+ .sorted().collect(Collectors.toList()));
if (player == null) return;
ServerPlayer sPlayer = sGame.getFreeColGameObject(player.getId(),
@@ -507,17 +502,15 @@ public class DebugUtils {
final GUI gui = freeColClient.getGUI();
final Game game = unit.getGame();
- List> pcs = new ArrayList<>();
- for (Player p : game.getLivePlayers(null)) {
- if (unit.getType().isAvailableTo(p)) {
- String msg = Messages.message(p.getNationName());
- pcs.add(new ChoiceItem<>(msg, p));
- }
- }
- Collections.sort(pcs);
- Player player = gui.getChoice(true, null,
- StringTemplate.template("prompt.selectOwner"),
- null, "cancel", pcs);
+ Player player = gui.getChoice(null,
+ StringTemplate.template("prompt.selectOwner"), "cancel",
+ game.getLivePlayers(null).stream()
+ .filter(p -> unit.getType().isAvailableTo(p))
+ .map(p -> {
+ String msg = Messages.message(p.getCountryLabel());
+ return new ChoiceItem(msg, p);
+ })
+ .sorted().collect(Collectors.toList()));
if (player == null || unit.getOwner() == player) return;
final Game sGame = server.getGame();
@@ -552,14 +545,11 @@ public class DebugUtils {
final Unit sUnit = sGame.getFreeColGameObject(unit.getId(), Unit.class);
final GUI gui = freeColClient.getGUI();
- List> rcs = new ArrayList<>();
- for (Role role : sGame.getSpecification().getRoles()) {
- rcs.add(new ChoiceItem<>(role.getId(), role));
- }
- Collections.sort(rcs);
- Role roleChoice = gui.getChoice(true, null,
- StringTemplate.template("prompt.selectRole"),
- null, "cancel", rcs);
+ Role roleChoice = gui.getChoice(null,
+ StringTemplate.template("prompt.selectRole"), "cancel",
+ sGame.getSpecification().getRoles().stream()
+ .map(r -> new ChoiceItem(r.getId(), r))
+ .sorted().collect(Collectors.toList()));
if (roleChoice == null) return;
sUnit.changeRole(roleChoice, roleChoice.getMaximumCount());
@@ -739,7 +729,7 @@ public class DebugUtils {
units.put(Messages.message("sailingToEurope"), toEurope);
units.put(Messages.getName(p.getEurope()), inEurope);
units.put(Messages.message("sailingToAmerica"), toAmerica);
- lb.add("\n==", Messages.message(p.getNationName()), "==\n");
+ lb.add("\n==", Messages.message(p.getCountryLabel()), "==\n");
for (Unit u : p.getEurope().getUnitList()) {
if (u.getDestination() instanceof Map) {
@@ -945,19 +935,18 @@ public class DebugUtils {
public static void setColonyGoods(final FreeColClient freeColClient,
final Colony colony) {
final Specification spec = colony.getSpecification();
- List> gtl = new ArrayList<>();
- for (GoodsType t : spec.getGoodsTypeList()) {
- if (t.isFoodType() && t != spec.getPrimaryFoodType()) continue;
- String msg = Messages.getName(t);
- gtl.add(new ChoiceItem<>(msg, t));
- }
- Collections.sort(gtl);
- GoodsType goodsType = freeColClient.getGUI().getChoice(true, null,
- StringTemplate.template("prompt.selectGoodsType"),
- null, "cancel", gtl);
+ GoodsType goodsType = freeColClient.getGUI().getChoice(null,
+ StringTemplate.template("prompt.selectGoodsType"), "cancel",
+ spec.getGoodsTypeList().stream()
+ .filter(gt -> !gt.isFoodType() || gt == spec.getPrimaryFoodType())
+ .map(gt -> {
+ String msg = Messages.getName(gt);
+ return new ChoiceItem(msg, gt);
+ })
+ .sorted().collect(Collectors.toList()));
if (goodsType == null) return;
- String response = freeColClient.getGUI().getInput(true, null,
+ String response = freeColClient.getGUI().getInput(null,
StringTemplate.template("prompt.selectGoodsAmount"),
Integer.toString(colony.getGoodsCount(goodsType)),
"ok", "cancel");
@@ -997,13 +986,13 @@ public class DebugUtils {
ServerPlayer.class);
final GUI gui = freeColClient.getGUI();
- List> actions = new ArrayList<>();
- for (MonarchAction action : MonarchAction.values()) {
- actions.add(new ChoiceItem<>(action));
- }
- Collections.sort(actions);
- MonarchAction action = gui.getChoice(true, null, monarchTitle, null,
- "cancel", actions);
+ MonarchAction action = gui.getChoice(null, monarchTitle,
+ "cancel",
+ Arrays.stream(MonarchAction.values())
+ .map(a -> new ChoiceItem(a))
+ .sorted().collect(Collectors.toList()));
+ if (action == null) return;
+
server.getInGameController().setMonarchAction(sPlayer, action);
}
@@ -1022,15 +1011,15 @@ public class DebugUtils {
final Tile sTile = sGame.getFreeColGameObject(tile.getId(),
Tile.class);
- List> rumours = new ArrayList<>();
- for (RumourType rumour : RumourType.values()) {
- if (rumour == RumourType.NO_SUCH_RUMOUR) continue;
- rumours.add(new ChoiceItem<>(rumour.toString(), rumour));
- }
- Collections.sort(rumours);
- RumourType rumourChoice = freeColClient.getGUI().getChoice(true, null,
+ RumourType rumourChoice = freeColClient.getGUI().getChoice(null,
StringTemplate.template("prompt.selectLostCityRumour"),
- null, "cancel", rumours);
+ "cancel",
+ Arrays.stream(RumourType.values())
+ .filter(r -> r != RumourType.NO_SUCH_RUMOUR)
+ .map(r -> new ChoiceItem(r.toString(), r))
+ .sorted().collect(Collectors.toList()));
+ if (rumourChoice == null) return;
+
tile.getTileItemContainer().getLostCityRumour().setType(rumourChoice);
sTile.getTileItemContainer().getLostCityRumour()
.setType(rumourChoice);
@@ -1046,7 +1035,7 @@ public class DebugUtils {
public static void skipTurns(FreeColClient freeColClient) {
freeColClient.skipTurns(0); // Clear existing skipping
- String response = freeColClient.getGUI().getInput(true, null,
+ String response = freeColClient.getGUI().getInput(null,
StringTemplate.key("prompt.selectTurnsToSkip"),
Integer.toString(10), "ok", "cancel");
if (response == null || response.isEmpty()) return;
@@ -1073,7 +1062,7 @@ public class DebugUtils {
boolean more = true;
while (more) {
int val = server.getInGameController().stepRandom();
- more = gui.confirm(true, null, StringTemplate
+ more = gui.confirm(null, StringTemplate
.template("prompt.stepRNG")
.addAmount("%value%", val),
"more", "cancel");
@@ -1104,7 +1093,7 @@ public class DebugUtils {
Player mostHated = sis.getMostHated();
for (Player p : sGame.getLiveEuropeanPlayers(null)) {
Tension tension = sis.getAlarm(p);
- lb.add(Messages.message(p.getNationName()),
+ lb.add(Messages.message(p.getNationLabel()),
" ", ((tension == null) ? "(none)"
: Integer.toString(tension.getValue())),
((mostHated == p) ? " (most hated)" : ""),
diff --git a/src/net/sf/freecol/common/debug/FreeColDebugger.java b/src/net/sf/freecol/common/debug/FreeColDebugger.java
index 513729de5..f01cab982 100644
--- a/src/net/sf/freecol/common/debug/FreeColDebugger.java
+++ b/src/net/sf/freecol/common/debug/FreeColDebugger.java
@@ -24,8 +24,10 @@ import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
+import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import net.sf.freecol.client.FreeColClient;
import net.sf.freecol.common.model.Player;
@@ -129,11 +131,10 @@ public class FreeColDebugger {
* @return A string containing the modes as csv.
*/
public static String getDebugModes() {
- String ret = "";
- for (DebugMode mode : DebugMode.values()) {
- if (isInDebugMode(mode)) ret += "," + mode;
- }
- return (ret.isEmpty()) ? ret : ret.substring(1, ret.length());
+ return Arrays.stream(DebugMode.values())
+ .filter(m -> isInDebugMode(m))
+ .map(m -> m.toString())
+ .collect(Collectors.joining(","));
}
/**
diff --git a/src/net/sf/freecol/common/i18n/DefaultNumberRule.java b/src/net/sf/freecol/common/i18n/DefaultNumberRule.java
index 6831cc457..839f13cb0 100644
--- a/src/net/sf/freecol/common/i18n/DefaultNumberRule.java
+++ b/src/net/sf/freecol/common/i18n/DefaultNumberRule.java
@@ -22,6 +22,8 @@ package net.sf.freecol.common.i18n;
import java.util.EnumMap;
import java.util.Map;
+import static net.sf.freecol.common.util.CollectionUtils.*;
+
/**
* This class handles zero or one rule for each number category.
@@ -75,12 +77,8 @@ public class DefaultNumberRule extends Number {
*/
@Override
public Category getCategory(double input) {
- for (Category number : Category.values()) {
- Rule r = rules.get(number);
- if (r != null && r.matches(input)) {
- return number;
- }
- }
- return Category.other;
+ return find(Category.values(),
+ category -> rules.containsKey(category)
+ && rules.get(category).matches(input), Category.other);
}
}
diff --git a/src/net/sf/freecol/common/i18n/Messages.java b/src/net/sf/freecol/common/i18n/Messages.java
index a54fb3f57..685555d31 100644
--- a/src/net/sf/freecol/common/i18n/Messages.java
+++ b/src/net/sf/freecol/common/i18n/Messages.java
@@ -41,11 +41,11 @@ import net.sf.freecol.common.io.FreeColDirectories;
import net.sf.freecol.common.io.FreeColDataFile;
import net.sf.freecol.common.io.FreeColModFile;
import net.sf.freecol.common.io.Mods;
-import net.sf.freecol.common.model.FreeColObject;
import net.sf.freecol.common.model.Named;
import net.sf.freecol.common.model.Role;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.StringTemplate.TemplateType;
+import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -60,7 +60,7 @@ import net.sf.freecol.common.model.StringTemplate.TemplateType;
* Properties class is unable to handle UTF-8 directly, this class
* uses its own implementation.
*
- * Te individual messages may include variables, which must be
+ * The individual messages may include variables, which must be
* delimited by percent characters (e.g. "%nation%"), and will be
* replaced when the message is formatted. Furthermore, the messages
* may include choice formats consisting of a tag followed by a colon
@@ -416,13 +416,9 @@ public class Messages {
}
public static String getBestDescription(String id) {
- for (String suffix : DESCRIPTION_KEYS) {
- String key = id + suffix;
- if (containsKey(key)) {
- return message(key);
- }
- }
- return id;
+ String key = find(map(DESCRIPTION_KEYS, s -> id + s),
+ k -> containsKey(k), null);
+ return (key == null) ? id : message(key);
}
/**
@@ -874,10 +870,12 @@ public class Messages {
int replacementIndex = input.indexOf('|', start);
int nextOpenIndex = input.indexOf("{{", start);
if (nextOpenIndex >= 0 && nextOpenIndex < replacementIndex) {
- replacementIndex = input.indexOf('|', findMatchingBracket(input, nextOpenIndex + 2) + 2);
+ replacementIndex = input.indexOf('|',
+ findMatchingBracket(input, nextOpenIndex + 2) + 2);
}
- int end = (replacementIndex < 0 || replacementIndex > closeChoice)
- ? closeChoice : replacementIndex;
+ int end = (replacementIndex < 0
+ || replacementIndex > closeChoice) ? closeChoice
+ : replacementIndex;
String replacement = input.substring(start, end);
if (!replacement.contains("{{")) {
result.append(replacement);
diff --git a/src/net/sf/freecol/common/i18n/NameCache.java b/src/net/sf/freecol/common/i18n/NameCache.java
index 321846676..f49eb1bb9 100644
--- a/src/net/sf/freecol/common/i18n/NameCache.java
+++ b/src/net/sf/freecol/common/i18n/NameCache.java
@@ -32,8 +32,8 @@ import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Region;
import net.sf.freecol.common.model.Region.RegionType;
import net.sf.freecol.common.model.StringTemplate;
-import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.UnitType;
+
import static net.sf.freecol.common.util.RandomUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
@@ -423,7 +423,7 @@ public class NameCache {
synchronized (regionNameLock) {
index = regionIndex.get(prefix);
}
- StringTemplate nn = player.getNationName();
+ StringTemplate nn = player.getNationLabel();
do {
name = Messages.message(StringTemplate.label(" ")
.addStringTemplate(nn)
@@ -478,7 +478,7 @@ public class NameCache {
List names = settlementNames.get(player);
while (!names.isEmpty()) {
String name = names.remove(0);
- if (game.getSettlement(name) == null) return name;
+ if (game.getSettlementByName(name) == null) return name;
}
}
@@ -486,7 +486,7 @@ public class NameCache {
final String base = getFallbackSettlementName(player);
int i = player.getSettlements().size() + 1;
String name = null;
- while (game.getSettlement(name = base + i++) != null);
+ while (game.getSettlementByName(name = base + i++) != null);
return name;
}
@@ -514,10 +514,10 @@ public class NameCache {
*/
public static String getTradeRouteName(Player player) {
String base = Messages.message("nameCache.base.tradeRoute");
- if (player.getTradeRoute(base) == null) return base;
+ if (player.getTradeRouteByName(base) == null) return base;
String name;
int i = 1;
- while (player.getTradeRoute(name = base + i++) != null);
+ while (player.getTradeRouteByName(name = base + i++) != null);
return name;
}
@@ -543,14 +543,14 @@ public class NameCache {
List names = shipNames.get(player);
while (!names.isEmpty()) {
name = names.remove(0);
- if (player.getUnit(name) == null) return name;
+ if (player.getUnitByName(name) == null) return name;
}
}
// Get a fallback ship name
final String base = Messages.message("nameCache.base.ship") + "-";
int i = 1;
- while (player.getUnit(name = base + i++) != null);
+ while (player.getUnitByName(name = base + i++) != null);
return name;
}
}
diff --git a/src/net/sf/freecol/common/i18n/Rule.java b/src/net/sf/freecol/common/i18n/Rule.java
index c9ffb030d..3b47383ac 100644
--- a/src/net/sf/freecol/common/i18n/Rule.java
+++ b/src/net/sf/freecol/common/i18n/Rule.java
@@ -24,6 +24,8 @@ import java.util.List;
import java.util.Locale;
import java.util.StringTokenizer;
+import static net.sf.freecol.common.util.CollectionUtils.*;
+
/**
* A rule consists of any number of relations combined with "and" and
@@ -52,19 +54,15 @@ public class Rule {
/**
* Returns true if this rule matches the given number.
*
- * @param number a double
value
- * @return a boolean
value
+ * The outer conditions are or-combined (using anyMatch), the
+ * inner conditions are and-combined (using allMatch).
+ *
+ * @param number The number to test.
+ * @return True if the number matches this rule.
*/
public boolean matches(double number) {
- outer: for (List andCondition : conditions) {
- for (Relation relation : andCondition) {
- if (!relation.matches(number)) {
- continue outer;
- }
- }
- return true;
- }
- return false;
+ return any(conditions,
+ andConditions -> all(andConditions, r -> r.matches(number)));
}
/**
diff --git a/src/net/sf/freecol/common/io/FreeColDataFile.java b/src/net/sf/freecol/common/io/FreeColDataFile.java
index b682c9948..7e361a362 100644
--- a/src/net/sf/freecol/common/io/FreeColDataFile.java
+++ b/src/net/sf/freecol/common/io/FreeColDataFile.java
@@ -28,27 +28,22 @@ import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
-
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
-import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
-import net.sf.freecol.common.resources.Resource;
import net.sf.freecol.common.resources.ResourceFactory;
import net.sf.freecol.common.resources.ResourceMapper;
import net.sf.freecol.common.resources.ResourceMapping;
-
-import static net.sf.freecol.common.util.CollectionUtils.*;
-
import net.sf.freecol.common.util.LogBuilder;
-
+import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
@@ -60,8 +55,7 @@ public class FreeColDataFile {
private static final Logger logger = Logger.getLogger(FreeColDataFile.class.getName());
- private static final Set FILE_ENDINGS
- = makeUnmodifiableSet(".zip");
+ protected static final String ZIP_FILE_EXTENSION = "zip";
private static final String RESOURCE_FILE_PREFIX = "resources";
private static final String RESOURCE_FILE_SUFFIX = ".properties";
@@ -85,38 +79,23 @@ public class FreeColDataFile {
* @exception IOException if the file does not exist.
*/
public FreeColDataFile(File file) throws IOException {
- if (!file.exists()) {
- for (String ending : getFileEndings()) {
- final File tempFile = new File(file.getAbsolutePath() + ending);
- if (tempFile.exists()) {
- file = tempFile;
- break;
- }
- }
- }
if (!file.exists()) {
throw new IOException("File " + file.getName() + " does not exist");
}
this.file = file;
-
- if (file.isDirectory()) {
- this.jarDirectory = null;
- } else {
- String jarName = file.getName().substring(0,
- file.getName().lastIndexOf('.'));
- this.jarDirectory = findJarDirectory(jarName, file);
- }
+ this.jarDirectory = (file.isDirectory()) ? null
+ : findJarDirectory(file);
}
/**
* Finds the directory within the zip-file in case the data file
* has been renamed.
*
- * @param expectedName The name the directory should have.
* @param file The zip-file.
* @return The name of the base directory in the zip-file.
*/
- private static String findJarDirectory(final String expectedName, File file) {
+ private static String findJarDirectory(File file) {
+ String expected = file.getName().substring(0, file.getName().lastIndexOf('.'));
try (
JarFile jf = new JarFile(file);
) {
@@ -130,7 +109,7 @@ public class FreeColDataFile {
return name;
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while reading data file.", e);
- return expectedName;
+ return expected;
}
}
@@ -291,32 +270,23 @@ public class FreeColDataFile {
}
/**
- * Gets a FileFilter
for the accepted file endings.
+ * Make a FileFilter
for a set of file endings.
*
- * @return The FileFilter
.
+ * @param requiredFile If non-null, the filter will accept a directory
+ * containing this file.
+ * @param endings Acceptable file suffixes.
+ * @return A suitable FileFilter
.
*/
- public FileFilter getFileFilter() {
- return new FileFilter() {
- @Override
- public boolean accept(File f) {
- final String name = f.getName();
- for (String ending : getFileEndings()) {
- if (name.endsWith(ending)) {
- return true;
- }
- }
- return false;
- }
+ public static FileFilter makeFileFilter(final String requiredFile,
+ final String... endings) {
+ return f -> {
+ final String name = f.getName();
+ return (name.startsWith("."))
+ ? false
+ : (requiredFile != null && f.isDirectory())
+ ? new File(f, requiredFile).exists()
+ : any(endings, e -> name.endsWith("." + e)
+ && name.length() > e.length());
};
}
-
- /**
- * File endings that are supported for this type of data file.
- * Override in classes that accept other endings.
- *
- * @return An array with a single element: ".zip".
- */
- protected static Set getFileEndings() {
- return FILE_ENDINGS;
- }
}
diff --git a/src/net/sf/freecol/common/io/FreeColDirectories.java b/src/net/sf/freecol/common/io/FreeColDirectories.java
index 50bc4081b..ceed04ca6 100644
--- a/src/net/sf/freecol/common/io/FreeColDirectories.java
+++ b/src/net/sf/freecol/common/io/FreeColDirectories.java
@@ -22,6 +22,8 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.StandardCopyOption;
import javax.swing.filechooser.FileSystemView;
@@ -431,52 +433,6 @@ public class FreeColDirectories {
return null;
}
- /**
- * Copy files/directories from one path to another.
- *
- * FIXME: Use Java7 copyFile and copyDirectory routines
- *
- * @param src The source directory.
- * @param dst The destination directory.
- * @return True if the copy succeeded.
- */
- private static boolean copyDir(File src, File dst) {
- if (!dst.mkdir()) return false;
- for (String f : src.list()) {
- File srcFile = new File(src, f);
- File dstFile = new File(dst, f);
- if (srcFile.isDirectory()) {
- if (!copyDir(srcFile, dstFile)) return false;
- } else if (srcFile.isFile()) {
- if (!copyFile(srcFile, dstFile)) return false;
- } else {
- // do not copy other objects
- }
- }
- return true;
- }
-
- /**
- * Copy a file.
- *
- * @param src The source File
.
- * @param dst The destination File
.
- * @return True if the copy succeeded.
- */
- private static boolean copyFile(File src, File dst) {
- byte[] buf = new byte[16384];
- int len;
- try (
- FileInputStream in = new FileInputStream(src);
- FileOutputStream out = new FileOutputStream(dst);
- ) {
- while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
- } catch (IOException ioe) {
- return false;
- }
- return true;
- }
-
/**
* Copy directory with given name under an old directory to a new
* directory.
@@ -489,7 +445,13 @@ public class FreeColDirectories {
File src = new File(oldDir, name);
File dst = new File(newDir, name);
if (src.exists() && src.isDirectory() && !dst.exists()) {
- copyDir(src, dst);
+ try {
+ Files.copy(src.toPath(), dst.toPath(),
+ StandardCopyOption.COPY_ATTRIBUTES);
+ } catch (IOException ioe) {
+ System.err.println("Could not copy " + src.toString() + " to "
+ + dst.toString() + ": " + ioe.getMessage());
+ }
}
}
@@ -515,6 +477,16 @@ public class FreeColDirectories {
}
}
+ /**
+ * Derive the directory for the autosave files from the save directory.
+ */
+ private static void deriveAutosaveDirectory() {
+ if (autosaveDirectory == null && saveDirectory != null) {
+ autosaveDirectory = new File(saveDirectory, AUTOSAVE_DIRECTORY);
+ if (!insistDirectory(autosaveDirectory)) autosaveDirectory = null;
+ }
+ }
+
// Main initialization/bootstrap routines.
// These need to be called early before the subsidiary directory
@@ -630,9 +602,7 @@ public class FreeColDirectories {
saveDirectory = new File(getUserDataDirectory(), SAVE_DIRECTORY);
if (!insistDirectory(saveDirectory)) return "main.userDir.fail";
}
-
- autosaveDirectory = new File(getSaveDirectory(), AUTOSAVE_DIRECTORY);
- if (!insistDirectory(autosaveDirectory)) autosaveDirectory = null;
+ deriveAutosaveDirectory();
userModsDirectory = new File(getUserDataDirectory(), MODS_DIRECTORY);
if (!insistDirectory(userModsDirectory)) userModsDirectory = null;
@@ -644,7 +614,6 @@ public class FreeColDirectories {
: null;
}
-
// Directory accessors.
// Where there are supported command line arguments there will also
// be a mutator.
@@ -803,15 +772,6 @@ public class FreeColDirectories {
return saveDirectory;
}
- /**
- * Set the directory where the saved games should be put.
- *
- * @param dir The new saved games directory.
- */
- public static void setSaveDirectory(File dir) {
- saveDirectory = dir;
- }
-
/**
* Gets the save game file.
*
@@ -821,15 +781,6 @@ public class FreeColDirectories {
return savegameFile;
}
- /**
- * Sets the save game file.
- *
- * @param file The new save game file.
- */
- public static void setSavegameFile(File file) {
- savegameFile = file;
- }
-
/**
* Sets the save game file.
*
@@ -842,10 +793,11 @@ public class FreeColDirectories {
file = new File(getSaveDirectory(), path);
if (!file.exists() || !file.isFile() || !file.canRead()) return false;
}
- setSavegameFile(file);
- setSaveDirectory(file.getParentFile());
- File autoDirectory = new File(getSaveDirectory(), AUTOSAVE_DIRECTORY);
- if (insistDirectory(autoDirectory)) autosaveDirectory = autoDirectory;
+ savegameFile = file;
+ File parent = file.getParentFile();
+ if (parent == null) parent = new File(".");
+ saveDirectory = parent;
+ deriveAutosaveDirectory();
return true;
}
@@ -861,7 +813,7 @@ public class FreeColDirectories {
for (File directory : new File[] {
FreeColDirectories.getSaveDirectory(),
FreeColDirectories.getAutosaveDirectory() }) {
- for (File savegame : directory.listFiles(FreeCol.freeColSaveFileFilter)) {
+ for (File savegame : directory.listFiles(FreeColSavegameFile.getFileFilter())) {
if (lastSave == null
|| savegame.lastModified() > lastSave.lastModified()) {
lastSave = savegame;
diff --git a/src/net/sf/freecol/common/io/FreeColFileFilter.java b/src/net/sf/freecol/common/io/FreeColFileFilter.java
deleted file mode 100644
index bb84fbd87..000000000
--- a/src/net/sf/freecol/common/io/FreeColFileFilter.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/**
- * Copyright (C) 2002-2015 The FreeCol Team
- *
- * This file is part of FreeCol.
- *
- * FreeCol is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 2 of the License, or
- * (at your option) any later version.
- *
- * FreeCol is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with FreeCol. If not, see .
- */
-
-package net.sf.freecol.common.io;
-
-import java.io.File;
-
-import javax.swing.filechooser.FileFilter;
-
-import net.sf.freecol.FreeCol;
-import net.sf.freecol.common.i18n.Messages;
-
-
-/**
- * A simple file filter with a description.
- */
-public class FreeColFileFilter extends FileFilter {
-
- private final String[] extensions;
- private final boolean allowSubdirs;
- private final String description;
-
- /**
- * Visible predefined constant filter for selected saved games or
- * subdirectories.
- */
- public static final FileFilter freeColSaveDirectoryFilter
- = new FreeColFileFilter(FreeCol.FREECOL_SAVE_EXTENSION, true,
- "filter.savedGames");
-
- public static final FileFilter freeColXMLFilter
- = new FreeColFileFilter(".xml", true, "filter.xml");
-
-
- /**
- * Create a new FreeColFileFilter.
- *
- * @param extension An acceptable extension.
- * @param allowSubdirs If true accept subdirectories.
- * @param description A description for the filter.
- */
- public FreeColFileFilter(String extension, boolean allowSubdirs,
- String description) {
- this.extensions = new String[] { extension };
- this.allowSubdirs = allowSubdirs;
- this.description = Messages.message(description);
- }
-
-
- // Implement FileFilter
-
- /**
- * {@inheritDoc}
- */
- @Override
- public boolean accept(File f) {
- if (allowSubdirs && f.isDirectory()) return true;
- if (!f.isFile()) return false;
- for (String x : extensions) {
- if (f.getName().endsWith(x) && f.getName().length() > x.length())
- return true;
- }
- return false;
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public String getDescription() {
- return description;
- }
-}
diff --git a/src/net/sf/freecol/common/io/FreeColModFile.java b/src/net/sf/freecol/common/io/FreeColModFile.java
index fd4eb5c0e..bcab2e9bd 100644
--- a/src/net/sf/freecol/common/io/FreeColModFile.java
+++ b/src/net/sf/freecol/common/io/FreeColModFile.java
@@ -20,17 +20,15 @@
package net.sf.freecol.common.io;
import java.io.File;
+import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import javax.xml.stream.XMLStreamException;
-import java.util.Set;
-
import net.sf.freecol.common.ObjectWithId;
-
-import static net.sf.freecol.common.util.CollectionUtils.*;
+import net.sf.freecol.common.model.Specification;
/**
@@ -38,12 +36,17 @@ import static net.sf.freecol.common.util.CollectionUtils.*;
*/
public class FreeColModFile extends FreeColDataFile implements ObjectWithId {
- private static final Set FILE_ENDINGS
- = makeUnmodifiableSet(".fmd", ".zip");
- public static final String SPECIFICATION_FILE = "specification.xml";
- public static final String MOD_DESCRIPTOR_FILE = "mod.xml";
+ protected static final String SPECIFICATION_FILE = "specification.xml";
+ protected static final String MOD_DESCRIPTOR_FILE = "mod.xml";
+ /** A file filter to select mods. */
+ private static final FileFilter fileFilter
+ = makeFileFilter(MOD_DESCRIPTOR_FILE, "fmd", ZIP_FILE_EXTENSION);
+
+ /** The identifier for this mod. */
private String id;
+
+ /** The identifier for the parent of this mod, if any. */
private String parent;
@@ -55,9 +58,11 @@ public class FreeColModFile extends FreeColDataFile implements ObjectWithId {
*/
public FreeColModFile(final File file) throws IOException {
super(file);
+
readModDescriptor();
}
+
/**
* Gets the input stream to the specification.
*
@@ -74,6 +79,29 @@ public class FreeColModFile extends FreeColDataFile implements ObjectWithId {
return null;
}
+ /**
+ * Gets the Specification.
+ *
+ * @return The Specification
, or null if none present.
+ * @exception IOException if an error occurs reading the specification.
+ */
+ public Specification getSpecification() throws IOException {
+ try (InputStream si = getSpecificationInputStream()) {
+ return (si == null) ? null : new Specification(si);
+ }
+ }
+
+ /**
+ * Gets the input stream to the mod meta file.
+ *
+ * @return An InputStream
to the file "mod.xml"
+ * within this data file.
+ * @exception IOException if thrown while opening the input stream.
+ */
+ private InputStream getModDescriptorInputStream() throws IOException {
+ return getInputStream(MOD_DESCRIPTOR_FILE);
+ }
+
/**
* Reads a file object representing this mod.
*
@@ -92,26 +120,6 @@ public class FreeColModFile extends FreeColDataFile implements ObjectWithId {
}
}
- /**
- * Gets the input stream to the mod meta file.
- *
- * @return An InputStream
to the file "mod.xml"
- * within this data file.
- * @exception IOException if thrown while opening the input stream.
- */
- private InputStream getModDescriptorInputStream() throws IOException {
- return getInputStream(MOD_DESCRIPTOR_FILE);
- }
-
- /**
- * File endings that are supported for this type of data file.
- *
- * @return A set of: ".fmd" and ".zip".
- */
- protected static Set getFileEndings() {
- return FILE_ENDINGS;
- }
-
/**
* Gets the object identifier of this mod.
*
@@ -130,4 +138,13 @@ public class FreeColModFile extends FreeColDataFile implements ObjectWithId {
public String getParent() {
return parent;
}
+
+ /**
+ * Get the file filter to select mod files.
+ *
+ * @return The mod file filter.
+ */
+ public static FileFilter getFileFilter() {
+ return fileFilter;
+ }
}
diff --git a/src/net/sf/freecol/common/io/FreeColSavegameFile.java b/src/net/sf/freecol/common/io/FreeColSavegameFile.java
index 6331be645..69a2e54c4 100644
--- a/src/net/sf/freecol/common/io/FreeColSavegameFile.java
+++ b/src/net/sf/freecol/common/io/FreeColSavegameFile.java
@@ -20,28 +20,18 @@
package net.sf.freecol.common.io;
import java.io.File;
+import java.io.FileFilter;
import java.io.IOException;
import java.io.BufferedInputStream;
-import java.util.Set;
-import java.util.logging.Logger;
-
import net.sf.freecol.FreeCol;
-import static net.sf.freecol.common.util.CollectionUtils.*;
-
/**
* Represents a FreeCol savegame.
*/
public class FreeColSavegameFile extends FreeColDataFile {
- @SuppressWarnings("unused")
- private static final Logger logger = Logger.getLogger(FreeColSavegameFile.class.getName());
-
- private static final Set FILE_ENDINGS
- = makeUnmodifiableSet(FreeCol.FREECOL_SAVE_EXTENSION, ".zip");
-
/** The tag for the version string in the saved game. */
public static final String VERSION_TAG = "version";
@@ -72,8 +62,16 @@ public class FreeColSavegameFile extends FreeColDataFile {
*/
public static final String THUMBNAIL_FILE = "thumbnail.png";
+ /** A file filter to select the saved game files. */
+ private static final FileFilter fileFilter = makeFileFilter(SAVEGAME_FILE,
+ FreeCol.FREECOL_SAVE_EXTENSION, ZIP_FILE_EXTENSION);
+ /**
+ * Create a new save game file from a given file.
+ *
+ * @param file The base File
.
+ */
public FreeColSavegameFile(File file) throws IOException {
super(file);
}
@@ -119,10 +117,11 @@ public class FreeColSavegameFile extends FreeColDataFile {
}
/**
- * File endings that are supported for this type of data file.
- * @return An array of: ".fsg" and ".zip".
+ * Get the file filter to select saved game files.
+ *
+ * @return The saved game file filter.
*/
- protected static Set getFileEndings() {
- return FILE_ENDINGS;
+ public static FileFilter getFileFilter() {
+ return fileFilter;
}
}
diff --git a/src/net/sf/freecol/common/io/FreeColTcFile.java b/src/net/sf/freecol/common/io/FreeColTcFile.java
index ce3c5075c..d5ae91a06 100644
--- a/src/net/sf/freecol/common/io/FreeColTcFile.java
+++ b/src/net/sf/freecol/common/io/FreeColTcFile.java
@@ -20,14 +20,10 @@
package net.sf.freecol.common.io;
import java.io.File;
-import java.io.InputStream;
+import java.io.FileFilter;
import java.io.IOException;
-import java.util.Set;
-
-import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.resources.ResourceMapping;
-import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -35,8 +31,9 @@ import static net.sf.freecol.common.util.CollectionUtils.*;
*/
public class FreeColTcFile extends FreeColModFile {
- private static final Set FILE_ENDINGS
- = makeUnmodifiableSet(".ftc", ".zip");
+ /** A file filter to select TCs. */
+ private static final FileFilter fileFilter
+ = makeFileFilter(MOD_DESCRIPTOR_FILE, "ftc", ZIP_FILE_EXTENSION);
/**
@@ -60,22 +57,6 @@ public class FreeColTcFile extends FreeColModFile {
}
- /**
- * Gets the Specification of this TC.
- *
- * @return The Specification
in this TC, or null if
- * none present.
- * @exception IOException if an error occurs reading the specification.
- */
- public Specification getSpecification() throws IOException {
- Specification specification;
- try (InputStream si = getSpecificationInputStream()) {
- if (si == null) return null;
- specification = new Specification(si);
- }
- return specification;
- }
-
/**
* {@inheritDoc}
*/
@@ -100,11 +81,11 @@ public class FreeColTcFile extends FreeColModFile {
}
/**
- * File endings that are supported for this type of data file.
+ * Get the file filter to select TC files.
*
- * @return A set: ".ftc" and ".zip".
+ * @return The TC file filter.
*/
- protected static Set getFileEndings() {
- return FILE_ENDINGS;
+ public static FileFilter getFileFilter() {
+ return fileFilter;
}
}
diff --git a/src/net/sf/freecol/common/io/FreeColXMLReader.java b/src/net/sf/freecol/common/io/FreeColXMLReader.java
index a9df9ee94..dd78a40e2 100644
--- a/src/net/sf/freecol/common/io/FreeColXMLReader.java
+++ b/src/net/sf/freecol/common/io/FreeColXMLReader.java
@@ -593,7 +593,6 @@ public class FreeColXMLReader extends StreamReaderDelegate
* @param required If true a null result should throw an exception.
* @return The FreeColGameObject
found or made, or null
* if the attribute was not present.
- * @exception XMLStreamError if there was a problem reading the stream.
*/
public T makeFreeColGameObject(Game game,
String attributeName, Class returnClass,
diff --git a/src/net/sf/freecol/common/io/Mods.java b/src/net/sf/freecol/common/io/Mods.java
index 82e3b0337..650c446d9 100644
--- a/src/net/sf/freecol/common/io/Mods.java
+++ b/src/net/sf/freecol/common/io/Mods.java
@@ -20,7 +20,6 @@
package net.sf.freecol.common.io;
import java.io.File;
-import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
@@ -30,6 +29,7 @@ import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
+import net.sf.freecol.common.io.FreeColModFile;
import net.sf.freecol.common.util.LogBuilder;
@@ -40,26 +40,6 @@ public class Mods {
private static final Logger logger = Logger.getLogger(Mods.class.getName());
- private static final FileFilter MOD_FILTER = new FileFilter() {
- @Override
- public boolean accept(File f) {
- final String name = f.getName();
- if (name.startsWith(".")) {
- // Ignore `hidden' files.
- return false;
- } else if (f.isDirectory()) {
- return true;
- } else {
- for (String ending : FreeColModFile.getFileEndings()) {
- if (name.endsWith(ending)) {
- return true;
- }
- }
- return false;
- }
- }
- };
-
/** A cache of all the mods. */
private static final Map allMods = new HashMap<>();
@@ -74,7 +54,7 @@ public class Mods {
LogBuilder lb = new LogBuilder(64);
lb.add("In ", directory.getPath(), " found mod:");
lb.mark();
- for (File f : directory.listFiles(MOD_FILTER)) {
+ for (File f : directory.listFiles(FreeColModFile.getFileFilter())) {
try {
FreeColModFile fcmf = new FreeColModFile(f);
allMods.put(fcmf.getId(), fcmf);
@@ -137,18 +117,11 @@ public class Mods {
public static List getRuleSets() {
List result = new ArrayList<>();
File directory = FreeColDirectories.getRulesDirectory();
- for (File dir : directory.listFiles()) {
- if (dir.isDirectory()) {
- File modDescription
- = new File(dir, FreeColModFile.MOD_DESCRIPTOR_FILE);
- if (modDescription.exists()) {
- try {
- result.add(new FreeColTcFile(dir));
- } catch (IOException e) {
- logger.log(Level.WARNING, "Failed to create rule set "
- + dir, e);
- }
- }
+ for (File f : directory.listFiles(FreeColTcFile.getFileFilter())) {
+ try {
+ result.add(new FreeColTcFile(f));
+ } catch (IOException ioe) {
+ logger.log(Level.WARNING, "Failed to load rule set " + f, ioe);
}
}
return result;
diff --git a/src/net/sf/freecol/common/model/AbstractGoods.java b/src/net/sf/freecol/common/model/AbstractGoods.java
index 01cc99dae..59e6152d6 100644
--- a/src/net/sf/freecol/common/model/AbstractGoods.java
+++ b/src/net/sf/freecol/common/model/AbstractGoods.java
@@ -27,6 +27,7 @@ import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import net.sf.freecol.common.model.GoodsType;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.Utils;
@@ -182,10 +183,8 @@ public class AbstractGoods extends FreeColObject implements Named {
* @return The AbstractGoods
found, or null if not.
*/
public static AbstractGoods findByType(GoodsType type,
- Collection goods) {
- for (AbstractGoods ag : goods) {
- if (ag.getType() == type) return ag;
- }
+ Collection extends AbstractGoods> goods) {
+ for (AbstractGoods ag : goods) if (ag.getType() == type) return ag;
return null;
}
@@ -198,11 +197,23 @@ public class AbstractGoods extends FreeColObject implements Named {
* @return The goods count found, or zero if not found.
*/
public static int getCount(GoodsType type,
- Collection goods) {
+ Collection extends AbstractGoods> goods) {
AbstractGoods ag = findByType(type, goods);
return (ag == null) ? 0 : ag.getAmount();
}
+ /**
+ * Does a goods collection contain an element with a given type?
+ *
+ * @param goods The Goods collection to search.
+ * @param type The GoodsType
to search for.
+ * @return True if the goods type was found.
+ */
+ public static boolean containsType(GoodsType type,
+ Collection extends AbstractGoods> goods) {
+ return contains(goods, ag -> ag.getType() == type);
+ }
+
/**
* Evaluate goods for trade purposes.
*
diff --git a/src/net/sf/freecol/common/model/AbstractUnit.java b/src/net/sf/freecol/common/model/AbstractUnit.java
index d0a489a71..41c86f9b9 100644
--- a/src/net/sf/freecol/common/model/AbstractUnit.java
+++ b/src/net/sf/freecol/common/model/AbstractUnit.java
@@ -166,7 +166,7 @@ public class AbstractUnit extends FreeColObject {
* @param spec A Specification
to look up.
* @return The approximate offence power.
*/
- public float getOffence(Specification spec) {
+ public double getOffence(Specification spec) {
int n = getNumber();
Role role = getRole(spec);
UnitType type = spec.getUnitType(getId());
@@ -182,9 +182,7 @@ public class AbstractUnit extends FreeColObject {
*/
public static double calculateStrength(Specification spec,
List units) {
- float result = 0;
- for (AbstractUnit au : units) result += au.getOffence(spec);
- return result;
+ return units.stream().mapToDouble(au -> au.getOffence(spec)).sum();
}
/**
diff --git a/src/net/sf/freecol/common/model/BuildQueue.java b/src/net/sf/freecol/common/model/BuildQueue.java
index b9e5e14d6..5d489d8c3 100644
--- a/src/net/sf/freecol/common/model/BuildQueue.java
+++ b/src/net/sf/freecol/common/model/BuildQueue.java
@@ -143,6 +143,7 @@ public class BuildQueue implements Consumer {
this.completionAction = newCompletionAction;
}
+
// Interface Consumer
/**
diff --git a/src/net/sf/freecol/common/model/BuildableType.java b/src/net/sf/freecol/common/model/BuildableType.java
index 48ca6f746..5e6c3e22c 100644
--- a/src/net/sf/freecol/common/model/BuildableType.java
+++ b/src/net/sf/freecol/common/model/BuildableType.java
@@ -20,17 +20,20 @@
package net.sf.freecol.common.model;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.stream.Collectors;
import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import net.sf.freecol.common.model.StringTemplate;
+import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -132,18 +135,9 @@ public abstract class BuildableType extends FreeColGameObjectType {
* @return True if the buildable is available.
*/
public boolean isAvailableTo(FreeColObject... fco) {
- if (requiredAbilities != null) {
- FreeColObject[] objects = fco;
- for (Entry entry : requiredAbilities.entrySet()) {
- boolean found = false;
- for (FreeColObject object : objects) {
- found = object.hasAbility(entry.getKey());
- if (found) break;
- }
- if (found != entry.getValue()) return false;
- }
- }
- return true;
+ return (requiredAbilities == null) ? true
+ : all(requiredAbilities.entrySet(),
+ e -> e.getValue() == any(fco, o -> o.hasAbility(e.getKey())));
}
/**
@@ -180,9 +174,7 @@ public abstract class BuildableType extends FreeColGameObjectType {
* @param ag The required AbstractGoods
to add.
*/
private void addRequiredGoods(AbstractGoods ag) {
- if (requiredGoods == null) {
- requiredGoods = new ArrayList<>();
- }
+ if (requiredGoods == null) requiredGoods = new ArrayList<>();
requiredGoods.add(ag);
}
diff --git a/src/net/sf/freecol/common/model/Building.java b/src/net/sf/freecol/common/model/Building.java
index c2849e963..ccb30f87e 100644
--- a/src/net/sf/freecol/common/model/Building.java
+++ b/src/net/sf/freecol/common/model/Building.java
@@ -263,10 +263,8 @@ public class Building extends WorkLocation
} else {
for (AbstractGoods output : getOutputs()) {
final GoodsType goodsType = output.getType();
- float production = 0f;
- for (Unit u : getUnitList()) {
- production += getUnitProduction(u, goodsType);
- }
+ float production = getUnitList().stream()
+ .mapToInt(u -> getUnitProduction(u, goodsType)).sum();
// Unattended production always applies for buildings!
production += getBaseProduction(null, goodsType, null);
production = applyModifiers(production, turn,
@@ -282,8 +280,8 @@ public class Building extends WorkLocation
// Then reduce the minimum ratio if some input is in short supply.
for (AbstractGoods input : getInputs()) {
- int required = (int)Math.floor(input.getAmount() * minimumRatio);
- int available = getAvailable(input.getType(), inputs);
+ long required = (long)Math.floor(input.getAmount() * minimumRatio);
+ long available = getAvailable(input.getType(), inputs);
// Do not allow auto-production to go negative.
if (canAutoProduce()) available = Math.max(0, available);
// Experts in factory level buildings may produce a
@@ -292,13 +290,10 @@ public class Building extends WorkLocation
if (available < required
&& hasAbility(Ability.EXPERTS_USE_CONNECTIONS)
&& spec.getBoolean(GameOptions.EXPERTS_HAVE_CONNECTIONS)) {
- int minimumGoodsInput = 0;
- for (Unit unit: getUnitList()) {
- if (unit.getType() == getExpertUnitType()) {
- // FIXME: put magic number in specification
- minimumGoodsInput += 4;
- }
- }
+ long minimumGoodsInput = 4 // FIXME: magic number
+ * (int)getUnitList().stream()
+ .filter(u -> u.getType() == getExpertUnitType())
+ .count();
if (minimumGoodsInput > available) {
available = minimumGoodsInput;
}
@@ -368,11 +363,9 @@ public class Building extends WorkLocation
*/
@Override
public int evaluateFor(Player player) {
- int result = 0;
- for (AbstractGoods ag : getType().getRequiredGoods()) {
- result += ag.evaluateFor(player);
- }
- return result + super.evaluateFor(player);
+ return super.evaluateFor(player)
+ + getType().getRequiredGoods().stream()
+ .mapToInt(ag -> ag.evaluateFor(player)).sum();
}
@@ -388,8 +381,9 @@ public class Building extends WorkLocation
// final UnitLocation.getUnitIterator
// UnitLocation.getUnitList
// UnitLocation.getGoodsContainer
- // final WorkLocation getSettlement
- // final WorkLocation getColony
+ // final WorkLocation.getSettlement
+ // final WorkLocation.getColony
+ // final WorkLocation.getRank
/**
* {@inheritDoc}
@@ -459,6 +453,22 @@ public class Building extends WorkLocation
: StringTemplate.key(buildingType);
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isAvailable() {
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isCurrent() {
+ return true;
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/src/net/sf/freecol/common/model/BuildingType.java b/src/net/sf/freecol/common/model/BuildingType.java
index a3eaa5789..6cc40d79f 100644
--- a/src/net/sf/freecol/common/model/BuildingType.java
+++ b/src/net/sf/freecol/common/model/BuildingType.java
@@ -21,6 +21,7 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.List;
+import java.util.stream.Collectors;
import javax.xml.stream.XMLStreamException;
@@ -223,14 +224,10 @@ public final class BuildingType extends BuildableType {
*/
public List getAvailableProductionTypes(boolean unattended,
String level) {
- List result = new ArrayList<>();
- for (ProductionType productionType : productionTypes) {
- if (productionType.getUnattended() == unattended
- && productionType.appliesTo(level)) {
- result.add(productionType);
- }
- }
- return result;
+ return productionTypes.stream()
+ .filter(pt -> pt.getUnattended() == unattended
+ && pt.appliesTo(level))
+ .collect(Collectors.toList());
}
// @compat 0.10.6
diff --git a/src/net/sf/freecol/common/model/Colony.java b/src/net/sf/freecol/common/model/Colony.java
index 735052a6e..a51da52fa 100644
--- a/src/net/sf/freecol/common/model/Colony.java
+++ b/src/net/sf/freecol/common/model/Colony.java
@@ -26,11 +26,12 @@ import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
-import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import javax.xml.stream.XMLStreamException;
@@ -38,7 +39,9 @@ import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import net.sf.freecol.common.model.Occupation;
import net.sf.freecol.common.model.Stance;
+
import static net.sf.freecol.common.util.CollectionUtils.*;
+
import net.sf.freecol.common.util.LogBuilder;
import net.sf.freecol.common.util.RandomChoice;
@@ -215,10 +218,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return The corresponding ColonyTile
, or null if not found.
*/
public ColonyTile getColonyTile(Tile t) {
- for (ColonyTile c : colonyTiles) {
- if (c.getWorkTile() == t) return c;
- }
- return null;
+ return find(colonyTiles, ct -> ct.getWorkTile() == t);
}
/**
@@ -503,15 +503,24 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
// WorkLocations, Buildings, ColonyTiles
+ /**
+ * Get a stream of all the possible work locations for this colony.
+ *
+ * @return A suitable Stream
.
+ */
+ private Stream getAllWorkLocationsStream() {
+ return Stream.concat(colonyTiles.stream(),
+ buildingMap.values().stream());
+ }
+
/**
* Gets a list of every work location in this colony.
*
* @return The list of work locations.
*/
public List getAllWorkLocations() {
- List result = new ArrayList(colonyTiles);
- result.addAll(buildingMap.values());
- return result;
+ return getAllWorkLocationsStream()
+ .collect(Collectors.toList());
}
/**
@@ -521,16 +530,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return The list of available WorkLocation
s.
*/
public List getAvailableWorkLocations() {
- List result
- = new ArrayList(buildingMap.values());
- for (ColonyTile ct : colonyTiles) {
- Tile tile = ct.getWorkTile();
- if (tile.getOwningSettlement() == this
- || getOwner().canClaimForSettlement(tile)) {
- result.add(ct);
- }
- }
- return result;
+ return getAllWorkLocationsStream()
+ .filter(WorkLocation::isAvailable)
+ .collect(Collectors.toList());
}
/**
@@ -539,28 +541,30 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return The list of current WorkLocation
s.
*/
public List getCurrentWorkLocations() {
- List result
- = new ArrayList(buildingMap.values());
- for (ColonyTile ct : colonyTiles) {
- Tile tile = ct.getWorkTile();
- if (tile.getOwningSettlement() == this) result.add(ct);
- }
- return result;
+ return getAllWorkLocationsStream()
+ .filter(WorkLocation::isCurrent)
+ .collect(Collectors.toList());
}
/**
* Add a Building to this Colony.
*
+ * Lower level routine, do not use directly in-game (use buildBuilding).
+ * Used for serialization and public for the test suite.
+ *
* -til: Could change the tile appearance if the building is
* stockade-type
*
- * @param building a Building
value
+ * @param building The Building
to build.
+ * @return True if the building was added.
*/
- public void addBuilding(final Building building) {
- BuildingType buildingType = building.getType().getFirstLevel();
+ public boolean addBuilding(final Building building) {
+ if (building == null || building.getType() == null) return false;
+ final BuildingType buildingType = building.getType().getFirstLevel();
+ if (buildingType == null || buildingType.getId() == null) return false;
buildingMap.put(buildingType.getId(), building);
addFeatures(building.getType());
- invalidateCache();
+ return true;
}
/**
@@ -572,14 +576,11 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @param building The Building
to remove.
* @return True if the building was removed.
*/
- public boolean removeBuilding(final Building building) {
- BuildingType buildingType = building.getType().getFirstLevel();
- boolean result = buildingMap.remove(buildingType.getId()) != null;
- if (result) {
- removeFeatures(building.getType());
- invalidateCache();
- }
- return result;
+ protected boolean removeBuilding(final Building building) {
+ final BuildingType buildingType = building.getType().getFirstLevel();
+ if (buildingMap.remove(buildingType.getId()) == null) return false;
+ removeFeatures(building.getType());
+ return true;
}
/**
@@ -591,10 +592,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public Building getBuildingForProducing(final GoodsType goodsType) {
for (Building b : buildingMap.values()) {
- for (AbstractGoods ag : b.getOutputs()) {
- if (ag.getType() == goodsType)
- return b;
- }
+ if (AbstractGoods.findByType(goodsType, b.getOutputs()) != null)
+ return b;
}
return null;
}
@@ -623,13 +622,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public T getWorkLocationWithAbility(String ability,
Class returnClass) {
- for (WorkLocation wl : getCurrentWorkLocations()) {
- if (wl.hasAbility(ability)) {
- try {
- return returnClass.cast(wl);
- } catch (ClassCastException cce) {}
- }
- }
+ WorkLocation wl = getWorkLocationWithAbility(ability);
+ if (wl != null) try { return returnClass.cast(wl); } catch (ClassCastException cce) {};
return null;
}
@@ -657,13 +651,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public T getWorkLocationWithModifier(String modifier,
Class returnClass) {
- for (WorkLocation wl : getCurrentWorkLocations()) {
- if (wl.hasModifier(modifier)) {
- try {
- return returnClass.cast(wl);
- } catch (ClassCastException cce) {}
- }
- }
+ WorkLocation wl = getWorkLocationWithModifier(modifier);
+ if (wl != null) try { return returnClass.cast(wl); } catch (ClassCastException cce) {}
return null;
}
@@ -675,13 +664,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* the given type of goods.
*/
public List getWorkLocationsForConsuming(GoodsType goodsType) {
- List result = new ArrayList<>();
- for (WorkLocation wl : getCurrentWorkLocations()) {
- for (AbstractGoods input : wl.getInputs()) {
- if (input.getType() == goodsType) result.add(wl);
- }
- }
- return result;
+ return getCurrentWorkLocations().stream()
+ .filter(wl -> any(wl.getInputs(), ag -> ag.getType() == goodsType))
+ .collect(Collectors.toList());
}
/**
@@ -692,13 +677,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* the given type of goods.
*/
public List getWorkLocationsForProducing(GoodsType goodsType) {
- List result = new ArrayList<>();
- for (WorkLocation wl : getCurrentWorkLocations()) {
- for (AbstractGoods ag : wl.getOutputs()) {
- if (ag.getType() == goodsType) result.add(wl);
- }
- }
- return result;
+ return getCurrentWorkLocations().stream()
+ .filter(wl -> any(wl.getOutputs(), ag -> ag.getType() == goodsType))
+ .collect(Collectors.toList());
}
/**
@@ -828,14 +809,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return A list of buildable UnitType
s.
*/
public List getBuildableUnits() {
- ArrayList buildableUnits = new ArrayList<>();
- List unitTypes = getSpecification().getUnitTypeList();
- for (UnitType unitType : unitTypes) {
- if (unitType.needsGoodsToBuild() && canBuild(unitType)) {
- buildableUnits.add(unitType);
- }
- }
- return buildableUnits;
+ return getSpecification().getUnitTypeList().stream()
+ .filter(ut -> ut.needsGoodsToBuild() && canBuild(ut))
+ .collect(Collectors.toList());
}
/**
@@ -977,18 +953,12 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
&& !getTile().isCoastland()) {
return NoBuildReason.COASTAL;
} else {
- for (Entry entry
- : buildableType.getRequiredAbilities().entrySet()) {
- if (hasAbility(entry.getKey()) != entry.getValue()) {
- return NoBuildReason.MISSING_ABILITY;
- }
+ if (!all(buildableType.getRequiredAbilities().entrySet(),
+ e -> e.getValue() == hasAbility(e.getKey()))) {
+ return NoBuildReason.MISSING_ABILITY;
}
- if (buildableType.getLimits() != null) {
- for (Limit limit : buildableType.getLimits()) {
- if (!limit.evaluate(this)) {
- return NoBuildReason.LIMIT_EXCEEDED;
- }
- }
+ if (!all(buildableType.getLimits(), l -> l.evaluate(this))) {
+ return NoBuildReason.LIMIT_EXCEEDED;
}
}
if (assumeBuilt == null) {
@@ -1015,15 +985,12 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
}
}
} else if (buildableType instanceof UnitType) {
- if (!buildableType.hasAbility(Ability.PERSON)) {
- boolean ok = hasAbility(Ability.BUILD, buildableType);
- if (!ok) {
- for (BuildableType bt : assumeBuilt) {
- ok = bt.hasAbility(Ability.BUILD, buildableType);
- if (ok) break;
- }
- }
- if (!ok) return NoBuildReason.MISSING_BUILD_ABILITY;
+ // Non-person units need a BUILD ability, present or assumed.
+ if (!buildableType.hasAbility(Ability.PERSON)
+ && !hasAbility(Ability.BUILD, buildableType)
+ && none(assumeBuilt, bt -> bt.hasAbility(Ability.BUILD,
+ buildableType))) {
+ return NoBuildReason.MISSING_BUILD_ABILITY;
}
}
return NoBuildReason.NONE;
@@ -1060,16 +1027,10 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
public int priceGoodsForBuilding(List required) {
final Market market = getOwner().getMarket();
- int price = 0;
- for (AbstractGoods ag : required) {
- final GoodsType goodsType = ag.getType();
- final int amount = ag.getAmount();
- // FIXME: magic number!
- price += (goodsType.isStorable())
- ? (market.getBidPrice(goodsType, amount) * 110) / 100
- : goodsType.getPrice() * amount;
- }
- return price;
+ // FIXME: magic number!
+ return required.stream().mapToInt(ag -> (ag.getType().isStorable())
+ ? (market.getBidPrice(ag.getType(), ag.getAmount()) * 110) / 100
+ : ag.getType().getPrice() * ag.getAmount()).sum();
}
/**
@@ -1105,8 +1066,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return A list of required abstract goods.
*/
public List getFullRequiredGoods(BuildableType buildable) {
+ if (buildable == null) return Collections.emptyList();
+
List required = new ArrayList<>();
- if (buildable == null) return required;
for (AbstractGoods ag : buildable.getRequiredGoods()) {
int amount = ag.getAmount();
GoodsType type = ag.getType();
@@ -1356,22 +1318,21 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
public StringTemplate getReducePopulationMessage() {
if (canReducePopulation()) return null;
Set modifierSet = getModifiers(Modifier.MINIMUM_COLONY_SIZE);
- for (Modifier modifier : modifierSet) {
- FreeColObject source = modifier.getSource();
- if (source instanceof BuildingType) {
- // If the modifier source is a building type, use the
- // building in the colony, which may be of a different
- // level to the modifier source.
- // This prevents the stockade modifier from matching a
- // colony-fort, and thus the message attributing the
- // failure to reduce population to a non-existing
- // stockade, BR#3522055.
- source = getBuilding((BuildingType)source).getType();
- }
- return StringTemplate.template("model.colony.minimumColonySize")
- .addName("%object%", source);
+ if (modifierSet.isEmpty()) return null;
+ Modifier modifier = modifierSet.iterator().next();
+ FreeColObject source = modifier.getSource();
+ if (source instanceof BuildingType) {
+ // If the modifier source is a building type, use the
+ // building in the colony, which may be of a different
+ // level to the modifier source.
+ // This prevents the stockade modifier from matching a
+ // colony-fort, and thus the message attributing the
+ // failure to reduce population to a non-existing
+ // stockade, BR#3522055.
+ source = getBuilding((BuildingType)source).getType();
}
- return null;
+ return StringTemplate.template("model.colony.minimumColonySize")
+ .addName("%object%", source);
}
/**
@@ -1637,15 +1598,11 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*
* @return The total defence power.
*/
- public float getTotalDefencePower() {
- CombatModel cm = getGame().getCombatModel();
- float defence = 0.0f;
- for (Unit unit : getTile().getUnitList()) {
- if (unit.isDefensiveUnit()) {
- defence += cm.getDefencePower(null, unit);
- }
- }
- return defence;
+ public double getTotalDefencePower() {
+ final CombatModel cm = getGame().getCombatModel();
+ return getTile().getUnitList().stream()
+ .filter(Unit::isDefensiveUnit)
+ .mapToDouble(u -> cm.getDefencePower(null, u)).sum();
}
/**
@@ -1684,11 +1641,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return A list of burnable buildings.
*/
public List getBurnableBuildings() {
- List buildingList = new ArrayList<>();
- for (Building building : getBuildings()) {
- if (building.canBeDamaged()) buildingList.add(building);
- }
- return buildingList;
+ return getBuildings().stream()
+ .filter(Building::canBeDamaged).collect(Collectors.toList());
}
/**
@@ -1698,11 +1652,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return A list of lootable goods in this colony.
*/
public List getLootableGoodsList() {
- List goodsList = new ArrayList<>();
- for (Goods goods : getGoodsContainer().getGoods()) {
- if (goods.getType().isStorable()) goodsList.add(goods);
- }
- return goodsList;
+ return getGoodsContainer().getGoods().stream()
+ .filter(g -> g.getType().isStorable())
+ .collect(Collectors.toList());
}
/**
@@ -1747,23 +1699,19 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
&& player.getNumberOfSettlements() < 5) {// FIXME: magic#
return Integer.MIN_VALUE;
}
- int result = 0;
+ int result;
if (player.owns(this)) {
- for (WorkLocation wl : getAvailableWorkLocations()) {
- result += wl.evaluateFor(player);
- }
- for (Unit u : getTile().getUnitList()) {
- result += u.evaluateFor(player);
- }
- for (Goods g : getCompactGoods()) {
- result += g.evaluateFor(player);
- }
+ result = getAvailableWorkLocations().stream()
+ .mapToInt(wl -> wl.evaluateFor(player)).sum()
+ + getTile().getUnitList().stream()
+ .mapToInt(u -> u.evaluateFor(player)).sum()
+ + getCompactGoods().stream()
+ .mapToInt(g -> g.evaluateFor(player)).sum();
} else { // Much guesswork
- result += getDisplayUnitCount() * 1000;
- result += 500; // Some useful goods?
- for (Tile t : getTile().getSurroundingTiles(1)) {
- if (t.getOwningSettlement() == this) result += 200;
- }
+ result = getDisplayUnitCount() * 1000
+ + 500 // Some useful goods?
+ + 200 * (int)getTile().getSurroundingTiles(0, 1).stream()
+ .filter(t -> t.getOwningSettlement() == this).count();
Building stockade = getStockade();
if (stockade != null) result *= stockade.getLevel();
}
@@ -1796,16 +1744,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return true
if this unit type could be added.
*/
public boolean canTrain(UnitType unitType) {
- if (!hasAbility(Ability.TEACH)) {
- return false;
- }
-
- for (Building building : buildingMap.values()) {
- if (building.canTeach() && building.canAddType(unitType)) {
- return true;
- }
- }
- return false;
+ return hasAbility(Ability.TEACH)
+ && any(buildingMap.values(),
+ b -> b.canTeach() && b.canAddType(unitType));
}
/**
@@ -1949,11 +1890,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return an int
value
*/
public int getFoodProduction() {
- int result = 0;
- for (GoodsType foodType : getSpecification().getFoodGoodsTypeList()) {
- result += getTotalProductionOf(foodType);
- }
- return result;
+ return getSpecification().getFoodGoodsTypeList().stream()
+ .mapToInt(ft -> getTotalProductionOf(ft)).sum();
}
/**
@@ -2043,8 +1981,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
populationQueue }) {
ProductionInfo info = productionCache.getProductionInfo(queue);
if (info != null) {
- AbstractGoods goods = AbstractGoods.findByType(goodsType, info.getConsumption());
- if (goods != null) result += goods.getAmount();
+ result += AbstractGoods.getCount(goodsType,
+ info.getConsumption());
}
}
return result;
@@ -2084,21 +2022,18 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* @return True if the goods can be produced.
*/
public boolean canProduce(GoodsType goodsType) {
- if (getNetProductionOf(goodsType) > 0) return true; // Obviously:-)
+ return (getNetProductionOf(goodsType) > 0)
+ ? true // Obviously:-)
- if (goodsType.isBreedable()) {
- return getGoodsCount(goodsType) >= goodsType.getBreedingNumber();
- }
+ // Breeding requires the breedable number to be present
+ : (goodsType.isBreedable())
+ ? getGoodsCount(goodsType) >= goodsType.getBreedingNumber()
- // Is there a work location that can produce the goods, with
- // satisfied inputs and positive generic production potential?
- outer: for (WorkLocation wl : getWorkLocationsForProducing(goodsType)) {
- for (AbstractGoods ag : wl.getInputs()) {
- if (!canProduce(ag.getType())) continue outer;
- }
- if (wl.getGenericPotential(goodsType) > 0) return true;
- }
- return false;
+ // Is there a work location that can produce the goods, with
+ // positive generic production potential and all inputs satisfied?
+ : any(getWorkLocationsForProducing(goodsType),
+ wl -> wl.getGenericPotential(goodsType) > 0
+ && all(wl.getInputs(),ag -> canProduce(ag.getType())));
}
@@ -2255,19 +2190,25 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
List result = new ArrayList<>();
final int amount = getGoodsCount(goodsType);
final int production = getNetProductionOf(goodsType);
-
- if (goodsType.isFoodType() && goodsType.isStorable()) {
- // Food is never wasted -> new settler is produced
- if (amount + production < 0) {
- result.add(StringTemplate
- .template("model.colony.famineFeared")
- .addName("%colony%", getName())
- .addAmount("%number%", 0));
- }
- } else {
- int waste = (amount + production - getWarehouseCapacity());
- if (waste > 0 && !getExportData(goodsType).getExported()
- && !goodsType.limitIgnored()) {
+ int waste;
+
+ if (goodsType.isStorable()) {
+ if (goodsType.limitIgnored()) {
+ if (goodsType.isFoodType()) {
+ int starve = getStarvationTurns();
+ if (starve == 0) {
+ result.add(StringTemplate
+ .template("model.colony.starving")
+ .addName("%colony%", getName()));
+ } else if (starve <= Colony.FAMINE_TURNS) {
+ result.add(StringTemplate
+ .template("model.colony.famineFeared")
+ .addName("%colony%", getName())
+ .addAmount("%number%", starve));
+ }
+ }
+ } else if (!getExportData(goodsType).getExported()
+ && (waste = amount + production - getWarehouseCapacity()) > 0) {
result.add(StringTemplate
.template("model.building.warehouseSoonFull")
.addNamed("%goods%", goodsType)
@@ -2329,13 +2270,14 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
List input = info.getConsumptionDeficit();
if (input.isEmpty()) return null;
-
+ StringTemplate label = StringTemplate.label(", ");
+ for (AbstractGoods ag : input) label.addStringTemplate(ag.getLabel());
+
return StringTemplate.template("model.colony.insufficientProduction")
.addName("%colony%", getName())
.addNamed("%outputType%", deficit.getType())
.addAmount("%outputAmount%", deficit.getAmount())
- .addNamed("%inputType%", input.get(0).getType())
- .addAmount("%inputAmount%", input.get(0).getAmount());
+ .addStringTemplate("%consumptionDeficit%", label);
}
/**
@@ -2533,10 +2475,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
@Override
public boolean contains(Locatable locatable) {
if (locatable instanceof Unit) {
- for (WorkLocation wl : getAvailableWorkLocations()) {
- if (wl.contains(locatable)) return true;
- }
- return false;
+ return any(getAvailableWorkLocations(),
+ wl -> wl.contains(locatable));
}
return super.contains(locatable);
}
@@ -2546,11 +2486,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
@Override
public int getUnitCount() {
- int n = 0;
- for (WorkLocation wl : getCurrentWorkLocations()) {
- n += wl.getUnitCount();
- }
- return n;
+ return getCurrentWorkLocations().stream()
+ .mapToInt(wl -> wl.getUnitCount()).sum();
}
/**
@@ -2668,9 +2605,9 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
List unitList = getUnitList();
Unit defender = null;
- float defencePower = -1.0f;
+ double defencePower = -1.0;
for (Unit nextUnit : unitList) {
- float unitPower = getGame().getCombatModel()
+ double unitPower = getGame().getCombatModel()
.getDefencePower(attacker, nextUnit);
if (Unit.betterDefender(defender, defencePower,
nextUnit, unitPower)) {
@@ -2689,7 +2626,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
* {@inheritDoc}
*/
@Override
- public float getDefenceRatio() {
+ public double getDefenceRatio() {
return getTotalDefencePower() / (1 + getUnitCount());
}
@@ -2698,7 +2635,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
@Override
public boolean isBadlyDefended() {
- return getTotalDefencePower() < 0.95f * getUnitCount() - 2.5f;
+ return getTotalDefencePower() < 0.95 * getUnitCount() - 2.5;
}
/**
@@ -2727,11 +2664,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
@Override
public int getUpkeep() {
- int upkeep = 0;
- for (Building building : buildingMap.values()) {
- upkeep += building.getType().getUpkeep();
- }
- return upkeep;
+ return buildingMap.values().stream()
+ .mapToInt(b -> b.getType().getUpkeep()).sum();
}
/**
@@ -2739,11 +2673,8 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
*/
@Override
public int getTotalProductionOf(GoodsType goodsType) {
- int amount = 0;
- for (WorkLocation workLocation : getCurrentWorkLocations()) {
- amount += workLocation.getTotalProductionOf(goodsType);
- }
- return amount;
+ return getCurrentWorkLocations().stream()
+ .mapToInt(wl -> wl.getTotalProductionOf(goodsType)).sum();
}
/**
@@ -2788,7 +2719,7 @@ public class Colony extends Settlement implements Nameable, TradeLocation {
public StringTemplate getAlarmLevelLabel(Player player) {
Stance stance = getOwner().getStance(player);
return StringTemplate.template("model.colony." + stance.getKey())
- .addStringTemplate("%nation%", getOwner().getNationName());
+ .addStringTemplate("%nation%", getOwner().getNationLabel());
}
diff --git a/src/net/sf/freecol/common/model/ColonyTile.java b/src/net/sf/freecol/common/model/ColonyTile.java
index 3bdbf32d1..17877ac8f 100644
--- a/src/net/sf/freecol/common/model/ColonyTile.java
+++ b/src/net/sf/freecol/common/model/ColonyTile.java
@@ -173,10 +173,8 @@ public class ColonyTile extends WorkLocation {
} else {
for (AbstractGoods output : getOutputs()) {
final GoodsType goodsType = output.getType();
- int amount = 0;
- for (Unit u : getUnitList()) {
- amount += getUnitProduction(u, goodsType);
- }
+ int amount = getUnitList().stream()
+ .mapToInt(u -> getUnitProduction(u, goodsType)).sum();
if (amount > 0) {
pi.addProduction(new AbstractGoods(goodsType, amount));
}
@@ -210,25 +208,28 @@ public class ColonyTile extends WorkLocation {
// Unattended production is the hard case.
if (productionType.getUnattended()) {
- if (newType != null) { // Tile type change
- final List newProd
- = newType.getPossibleProduction(true);
- int food = 0;
- // Get the current food production. Otherwise for
- // goods that are being passively produced and
- // consumed, check if production remains in surplus
- // following a negative change.
- for (AbstractGoods ag : getProduction()) {
- final GoodsType goodsType = ag.getType();
- if (goodsType.isFoodType()) {
- food -= ag.getAmount();
- continue;
- }
- if (!colony.isConsuming(goodsType)) continue;
- int change = -ag.getAmount();
- AbstractGoods ng
- = AbstractGoods.findByType(goodsType, newProd);
- change += (ng == null) ? 0 : ng.getAmount();
+ if (newType == null) {
+ // Tile type stays the same, return the sum of any food bonues.
+ return getSpecification().getFoodGoodsTypeList().stream()
+ .mapToInt(gt -> ti.getBonus(gt)).sum();
+ }
+
+ // Tile type change.
+ final List newProd
+ = newType.getPossibleProduction(true);
+ int food = newProd.stream()
+ .filter(ag -> ag.getType().isFoodType())
+ .mapToInt(AbstractGoods::getAmount).sum();
+ // Get the current food production. Otherwise for goods
+ // that are being passively produced and consumed, check
+ // if production remains in surplus following a negative change.
+ for (AbstractGoods ag : getProduction()) {
+ final GoodsType goodsType = ag.getType();
+ if (goodsType.isFoodType()) {
+ food -= ag.getAmount();
+ } else if (colony.isConsuming(goodsType)) {
+ int change = -ag.getAmount()
+ + AbstractGoods.getCount(goodsType, newProd);
if (change < 0
&& change + colony.getNetProductionOf(goodsType) < 0) {
// The change drives the net production (more?)
@@ -236,45 +237,24 @@ public class ColonyTile extends WorkLocation {
return change;
}
}
- // No production showstoppers found
- // Would the passive food production be improved?
- for (AbstractGoods ag : newProd) {
- if (ag.getType().isFoodType()) food += ag.getAmount();
- }
- return food;
}
-
- // Tile type stays the same, return the sum of any food bonues.
- int bonus = 0;
- for (GoodsType gt : getSpecification().getFoodGoodsTypeList()) {
- bonus += ti.getBonus(gt);
- }
- return bonus;
+ return food;
}
- // Units are at work here. Find out what work is being done.
- GoodsType work = null;
- UnitType type = null;
- for (Unit u : getUnitList()) {
- if (u != null && (type = u.getType()) != null
- && (work = u.getWorkType()) != null) break;
- }
- if (work == null) return 0; // No work, no reason to improve.
-
- if (newType != null) { // Tile type change
- // Return the production impact on the work being done.
- int diff = newType.getPotentialProduction(work, type);
- if (resource == null) {
- diff -= oldType.getPotentialProduction(work, type);
- } else {
- diff -= resource.applyBonus(work, type,
- oldType.getPotentialProduction(work, type));
- }
- return diff;
- }
-
- // Otherwise return any new bonus that impacts the current work.
- return ti.getBonus(work);
+ // Units are present, see what the change would do to their work.
+ final GoodsType work = getCurrentWorkType();
+ final UnitType unitType = getFirstUnit().getType();
+ return (work == null) // No work, improvement does nothing
+ ? 0
+ : (newType == null) // No tile change, but return the new bonus
+ ? ti.getBonus(work)
+ : (resource == null) // The tile change impact on the work
+ ? newType.getPotentialProduction(work, unitType)
+ - oldType.getPotentialProduction(work, unitType)
+ // The production impact with the new resource in place
+ : newType.getPotentialProduction(work, unitType)
+ - resource.applyBonus(work, unitType,
+ oldType.getPotentialProduction(work, unitType));
}
/**
@@ -285,11 +265,9 @@ public class ColonyTile extends WorkLocation {
*/
@Override
public int evaluateFor(Player player) {
- int result = 0;
- for (AbstractGoods ag :getProductionInfo().getProduction()) {
- result += ag.evaluateFor(player);
- }
- return result + super.evaluateFor(player);
+ return super.evaluateFor(player)
+ + getProductionInfo().getProduction().stream()
+ .mapToInt(ag -> ag.evaluateFor(player)).sum();
}
@@ -307,6 +285,7 @@ public class ColonyTile extends WorkLocation {
// UnitLocation.getGoodsContainer
// final WorkLocation getSettlement
// final WorkLocation getColony
+ // final int getRank
/**
* {@inheritDoc}
@@ -371,6 +350,22 @@ public class ColonyTile extends WorkLocation {
return (workTile == null) ? null : workTile.getLabel();
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isAvailable() {
+ return isCurrent() || getOwner().canClaimForSettlement(getWorkTile());
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isCurrent() {
+ return getWorkTile().getOwningSettlement() == getColony();
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/src/net/sf/freecol/common/model/ColonyWas.java b/src/net/sf/freecol/common/model/ColonyWas.java
index f673afa27..5ba8778fb 100644
--- a/src/net/sf/freecol/common/model/ColonyWas.java
+++ b/src/net/sf/freecol/common/model/ColonyWas.java
@@ -58,26 +58,34 @@ public class ColonyWas {
/**
* Fire any property changes resulting from actions within a
* colony.
+ *
+ * @return True if something changed.
*/
- public void fireChanges() {
+ public boolean fireChanges() {
+ boolean ret = false;
int newPopulation = colony.getUnitCount();
if (newPopulation != population) {
String pc = ColonyChangeEvent.POPULATION_CHANGE.toString();
colony.firePropertyChange(pc, population, newPopulation);
+ ret = true;
}
int newProductionBonus = colony.getProductionBonus();
if (newProductionBonus != productionBonus) {
String pc = ColonyChangeEvent.BONUS_CHANGE.toString();
colony.firePropertyChange(pc, productionBonus,
newProductionBonus);
+ ret = true;
}
List newBuildQueue = colony.getBuildQueue();
if (!newBuildQueue.equals(buildQueue)) {
String pc = ColonyChangeEvent.BUILD_QUEUE_CHANGE.toString();
colony.firePropertyChange(pc, buildQueue, newBuildQueue);
+ ret = true;
}
if (colony.getGoodsContainer() != null) {
colony.getGoodsContainer().fireChanges();
+ ret = true;
}
+ return true;
}
}
diff --git a/src/net/sf/freecol/common/model/CombatModel.java b/src/net/sf/freecol/common/model/CombatModel.java
index 7cb6d1665..2791cfcb1 100644
--- a/src/net/sf/freecol/common/model/CombatModel.java
+++ b/src/net/sf/freecol/common/model/CombatModel.java
@@ -19,6 +19,7 @@
package net.sf.freecol.common.model;
+import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.Set;
@@ -66,11 +67,11 @@ public abstract class CombatModel {
* Odds a particular outcome will occur in combat.
*/
public static class CombatOdds {
- public static final float UNKNOWN_ODDS = -1.0f;
+ public static final double UNKNOWN_ODDS = -1.0;
- public final float win;
+ public final double win;
- public CombatOdds(float win) {
+ public CombatOdds(double win) {
this.win = win;
}
}
@@ -180,6 +181,16 @@ public abstract class CombatModel {
return false;
}
+ /**
+ * Get a comparator to order units by relative military strength
+ * with respect to this combat model.
+ *
+ * @return A suitable unit Comparator
.
+ */
+ public final Comparator getMilitaryStrengthComparator() {
+ return (u1, u2) -> Double.compare(calculateCombatOdds(u1, u2).win,
+ calculateCombatOdds(u2, u1).win);
+ }
/**
* Calculates the chance of the outcomes of a combat.
@@ -201,8 +212,8 @@ public abstract class CombatModel {
* @param defender The defender.
* @return The offensive power.
*/
- public abstract float getOffencePower(FreeColGameObject attacker,
- FreeColGameObject defender);
+ public abstract double getOffencePower(FreeColGameObject attacker,
+ FreeColGameObject defender);
/**
* Get the defensive power of a defender wrt an attacker.
@@ -211,8 +222,8 @@ public abstract class CombatModel {
* @param defender The defender.
* @return The defensive power.
*/
- public abstract float getDefencePower(FreeColGameObject attacker,
- FreeColGameObject defender);
+ public abstract double getDefencePower(FreeColGameObject attacker,
+ FreeColGameObject defender);
/**
* Collect all the offensive modifiers that apply to an attack.
diff --git a/src/net/sf/freecol/common/model/Consumer.java b/src/net/sf/freecol/common/model/Consumer.java
index fa7ff5513..982cacb4a 100644
--- a/src/net/sf/freecol/common/model/Consumer.java
+++ b/src/net/sf/freecol/common/model/Consumer.java
@@ -32,12 +32,9 @@ import java.util.Set;
*/
public interface Consumer {
- public static final Comparator COMPARATOR = new Comparator() {
- @Override
- public int compare(Consumer c1, Consumer c2) {
- return c2.getPriority() - c1.getPriority();
- }
- };
+ /** Compare consumers by descending priority. */
+ public static final Comparator COMPARATOR
+ = Comparator.comparingInt(Consumer::getPriority).reversed();
/**
* Default consumption priority for the Colony when producing new
diff --git a/src/net/sf/freecol/common/model/DiplomaticTrade.java b/src/net/sf/freecol/common/model/DiplomaticTrade.java
index c28084082..4e13b6fc4 100644
--- a/src/net/sf/freecol/common/model/DiplomaticTrade.java
+++ b/src/net/sf/freecol/common/model/DiplomaticTrade.java
@@ -22,12 +22,14 @@ package net.sf.freecol.common.model;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
+import java.util.stream.Collectors;
import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
import net.sf.freecol.common.model.Stance;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
import org.w3c.dom.Element;
@@ -207,7 +209,7 @@ public class DiplomaticTrade extends FreeColObject {
return StringTemplate.template("model.diplomaticTrade.send."
+ getContext().getKey())
.addStringTemplate("%nation%",
- settlement.getOwner().getNationName())
+ settlement.getOwner().getNationLabel())
.addStringTemplate("%settlement%",
settlement.getLocationLabelFor(player));
}
@@ -222,7 +224,7 @@ public class DiplomaticTrade extends FreeColObject {
public StringTemplate getReceiveMessage(Player player) {
return StringTemplate.template("model.diplomaticTrade.receive."
+ getContext().getKey())
- .addStringTemplate("%nation%", player.getNationName());
+ .addStringTemplate("%nation%", player.getNationLabel());
}
/**
@@ -311,11 +313,9 @@ public class DiplomaticTrade extends FreeColObject {
* @return A list of TradeItem
s offered by the player.
*/
public List getItemsGivenBy(Player player) {
- List goodsList = new ArrayList<>();
- for (TradeItem ti : items) {
- if (player == ti.getSource()) goodsList.add(ti);
- }
- return goodsList;
+ return items.stream()
+ .filter(ti -> ti.getSource() == player)
+ .collect(Collectors.toList());
}
/**
@@ -324,12 +324,8 @@ public class DiplomaticTrade extends FreeColObject {
* @return The Stance
offered in this trade, or null if none.
*/
public Stance getStance() {
- for (TradeItem ti : items) {
- if (ti instanceof StanceTradeItem) {
- return ti.getStance();
- }
- }
- return null;
+ TradeItem ti = find(items, i -> i instanceof StanceTradeItem);
+ return (ti == null) ? null : ti.getStance();
}
/**
@@ -354,12 +350,9 @@ public class DiplomaticTrade extends FreeColObject {
* @return The gold offered in this trade.
*/
public int getGoldGivenBy(Player player) {
- for (TradeItem ti : items) {
- if (ti instanceof GoldTradeItem && player == ti.getSource()) {
- return ti.getGold();
- }
- }
- return -1;
+ TradeItem ti = find(items, i -> i instanceof GoldTradeItem
+ && player == i.getSource());
+ return (ti == null) ? -1 : ti.getGold();
}
/**
@@ -383,12 +376,8 @@ public class DiplomaticTrade extends FreeColObject {
* @return The Player
to be incited against.
*/
public Player getVictim() {
- for (TradeItem ti : items) {
- if (ti instanceof InciteTradeItem) {
- return ti.getVictim();
- }
- }
- return null;
+ TradeItem ti = find(items, i -> i instanceof InciteTradeItem);
+ return (ti == null) ? null : ti.getVictim();
}
/**
diff --git a/src/net/sf/freecol/common/model/Direction.java b/src/net/sf/freecol/common/model/Direction.java
index 97bd8d952..e9b851f99 100644
--- a/src/net/sf/freecol/common/model/Direction.java
+++ b/src/net/sf/freecol/common/model/Direction.java
@@ -91,11 +91,9 @@ public enum Direction implements Named {
* @return The map position after the step.
*/
public Map.Position step(int x, int y) {
- if((y & 1) != 0) {
- return new Map.Position(x + oddDX, y + oddDY);
- } else {
- return new Map.Position(x + evenDX, y + evenDY);
- }
+ return ((y & 1) != 0)
+ ? new Map.Position(x + oddDX, y + oddDY)
+ : new Map.Position(x + evenDX, y + evenDY);
}
/**
diff --git a/src/net/sf/freecol/common/model/Disaster.java b/src/net/sf/freecol/common/model/Disaster.java
index 79ed3f98b..f23307dc9 100644
--- a/src/net/sf/freecol/common/model/Disaster.java
+++ b/src/net/sf/freecol/common/model/Disaster.java
@@ -102,8 +102,7 @@ public class Disaster extends FreeColGameObjectType {
*/
private void addEffect(Effect effect) {
if (effects == null) effects = new ArrayList<>();
- effects.add(new RandomChoice<>(effect,
- effect.getProbability()));
+ effects.add(new RandomChoice<>(effect, effect.getProbability()));
}
diff --git a/src/net/sf/freecol/common/model/Effect.java b/src/net/sf/freecol/common/model/Effect.java
index c5ac931e1..612c2d23e 100644
--- a/src/net/sf/freecol/common/model/Effect.java
+++ b/src/net/sf/freecol/common/model/Effect.java
@@ -27,6 +27,7 @@ import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
+import static net.sf.freecol.common.util.CollectionUtils.*;
/**
@@ -131,11 +132,8 @@ public class Effect extends FreeColGameObjectType {
* @return True if this effect applies.
*/
public boolean appliesTo(final FreeColGameObjectType objectType) {
- if (scopes == null || scopes.isEmpty()) return true;
- for (Scope scope : scopes) {
- if (scope.appliesTo(objectType)) return true;
- }
- return false;
+ return (scopes == null || scopes.isEmpty()) ? true
+ : any(scopes, s -> s.appliesTo(objectType));
}
diff --git a/src/net/sf/freecol/common/model/Europe.java b/src/net/sf/freecol/common/model/Europe.java
index 2ef0d1c27..6b8366608 100644
--- a/src/net/sf/freecol/common/model/Europe.java
+++ b/src/net/sf/freecol/common/model/Europe.java
@@ -257,15 +257,22 @@ public class Europe extends UnitLocation
// Override FreeColObject
/**
- * Gets the feature container for this Europe object.
- *
- * @return The FeatureContainer
.
+ * {@inheritDoc}
*/
@Override
public FeatureContainer getFeatureContainer() {
return featureContainer;
}
+ // Override FreeColGameObject
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public FreeColGameObject getLinkTarget(Player player) {
+ return (getOwner() == player) ? this : null;
+ }
// Interface Location (from UnitLocation)
// Inheriting:
@@ -318,6 +325,14 @@ public class Europe extends UnitLocation
return this;
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int getRank() {
+ return Location.LOCATION_RANK_EUROPE;
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/src/net/sf/freecol/common/model/EuropeWas.java b/src/net/sf/freecol/common/model/EuropeWas.java
index 682702315..5bdce9430 100644
--- a/src/net/sf/freecol/common/model/EuropeWas.java
+++ b/src/net/sf/freecol/common/model/EuropeWas.java
@@ -68,13 +68,17 @@ public class EuropeWas {
/**
* Fire any property changes resulting from actions in Europe.
+ *
+ * @return True if something changed.
*/
- public void fireChanges() {
+ public boolean fireChanges() {
int newUnitCount = europe.getUnitCount();
if (newUnitCount != unitCount) {
europe.firePropertyChange(Europe.UNIT_CHANGE,
unitCount, newUnitCount);
+ return true;
}
+ return false;
}
}
diff --git a/src/net/sf/freecol/common/model/Feature.java b/src/net/sf/freecol/common/model/Feature.java
index bf18eebad..c48d60e61 100644
--- a/src/net/sf/freecol/common/model/Feature.java
+++ b/src/net/sf/freecol/common/model/Feature.java
@@ -28,6 +28,7 @@ import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.i18n.Messages;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import net.sf.freecol.common.util.Utils;
@@ -224,11 +225,8 @@ public abstract class Feature extends FreeColObject implements Named {
* applicable to the object.
*/
public boolean appliesTo(final FreeColGameObjectType objectType) {
- if (!hasScope()) return true;
- for (Scope scope : scopes) {
- if (scope.appliesTo(objectType)) return true;
- }
- return false;
+ return (!hasScope()) ? true
+ : any(scopes, s -> s.appliesTo(objectType));
}
/**
@@ -332,18 +330,10 @@ public abstract class Feature extends FreeColObject implements Named {
} else if (feature.scopes == null) {
return false;
} else {
- // not very efficient, but we do not expect many
- // scopes
- for (Scope scope : scopes) {
- if (!feature.scopes.contains(scope)) {
- return false;
- }
- }
- for (Scope scope : feature.scopes) {
- if (!scopes.contains(scope)) {
- return false;
- }
- }
+ // Not very efficient, but we do not expect many scopes
+ if (!all(scopes, s -> feature.scopes.contains(s))
+ || !all(feature.scopes, s -> scopes.contains(s)))
+ return false;
}
return true;
}
diff --git a/src/net/sf/freecol/common/model/FeatureContainer.java b/src/net/sf/freecol/common/model/FeatureContainer.java
index 0039b01c9..81188b9d2 100644
--- a/src/net/sf/freecol/common/model/FeatureContainer.java
+++ b/src/net/sf/freecol/common/model/FeatureContainer.java
@@ -30,6 +30,8 @@ import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Logger;
+import static net.sf.freecol.common.util.CollectionUtils.*;
+
/**
* A container to hold abilities and modifiers for some FreeColObject-subclass.
@@ -106,11 +108,9 @@ public final class FeatureContainer {
* @return True if the ability set is `satisfied'.
*/
public static boolean hasAbility(Set abilitySet) {
- if (abilitySet == null || abilitySet.isEmpty()) return false;
- for (Ability ability : abilitySet) {
- if (!ability.getValue()) return false;
- }
- return true;
+ return (abilitySet == null || abilitySet.isEmpty())
+ ? false
+ : all(abilitySet, Ability::getValue);
}
/**
diff --git a/src/net/sf/freecol/common/model/FoundingFather.java b/src/net/sf/freecol/common/model/FoundingFather.java
index dd89faf2f..e3fc24298 100644
--- a/src/net/sf/freecol/common/model/FoundingFather.java
+++ b/src/net/sf/freecol/common/model/FoundingFather.java
@@ -29,6 +29,7 @@ import javax.xml.stream.XMLStreamException;
import net.sf.freecol.common.io.FreeColXMLReader;
import net.sf.freecol.common.io.FreeColXMLWriter;
+import static net.sf.freecol.common.util.CollectionUtils.*;
import static net.sf.freecol.common.util.StringUtils.*;
@@ -276,12 +277,9 @@ public class FoundingFather extends FreeColGameObjectType {
* @return True if the father is available.
*/
public boolean isAvailableTo(Player player) {
- if (!player.isEuropean()) return false;
- if (scopes == null) return true;
- for (Scope scope : scopes) {
- if (scope.appliesTo(player)) return true;
- }
- return false;
+ return (!player.isEuropean()) ? false
+ : (scopes == null) ? true
+ : any(scopes, s -> s.appliesTo(player));
}
diff --git a/src/net/sf/freecol/common/model/FreeColGameObject.java b/src/net/sf/freecol/common/model/FreeColGameObject.java
index 4f1329939..a55f79c58 100644
--- a/src/net/sf/freecol/common/model/FreeColGameObject.java
+++ b/src/net/sf/freecol/common/model/FreeColGameObject.java
@@ -215,6 +215,21 @@ public abstract class FreeColGameObject extends FreeColObject {
return null;
}
+ /**
+ * Get a suitable game object to use as a clickable link in messages
+ * to a player.
+ *
+ * Objects do not have links by default, hence the null return
+ * here. However, for example, a player's colony should return
+ * itself as a link target.
+ *
+ * @param player The Player
to make a link for.
+ * @return A suitable link target if available, although usually null.
+ */
+ public FreeColGameObject getLinkTarget(Player player) {
+ return null;
+ }
+
/**
* Checks the integrity of this game object.
*
diff --git a/src/net/sf/freecol/common/model/FreeColObject.java b/src/net/sf/freecol/common/model/FreeColObject.java
index a7290dd74..01c988718 100644
--- a/src/net/sf/freecol/common/model/FreeColObject.java
+++ b/src/net/sf/freecol/common/model/FreeColObject.java
@@ -37,6 +37,7 @@ import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
+import java.util.stream.Collectors;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
@@ -248,9 +249,7 @@ public abstract class FreeColObject
* @return A sorted copy of the collection.
*/
public static List