/** * This function analyses an event and calls the right methods to take care of the user's * requests. * * @param event The incoming ActionEvent. */ @Override public void actionPerformed(ActionEvent event) { final String FAIL = "FAIL"; if (colony.getOwner() == getMyPlayer()) { String command = event.getActionCommand(); List<BuildableType> buildables = getBuildableTypes(buildQueueList); while (!buildables.isEmpty() && lockReasons.get(buildables.get(0)) != null) { getGUI() .showInformationMessage( buildables.get(0), StringTemplate.template("colonyPanel.unbuildable") .addName("%colony%", colony.getName()) .add("%object%", buildables.get(0).getNameKey())); command = FAIL; removeBuildable(buildables.remove(0)); } getController().setBuildQueue(colony, buildables); if (FAIL.equals(command)) { // Let the user reconsider. updateAllLists(); return; } else if (OK.equals(command)) { // do nothing? } else if (BUY.equals(command)) { getController().payForBuilding(colony); } else { logger.warning("Unsupported command " + command); } } getGUI().removeFromCanvas(this); }
private void initialize(BuildableType buildable) { removeAll(); if (buildable == null) { String clickToBuild = Messages.message(getDefaultLabel()); int breakingPoint = Messages.getBreakingPoint(clickToBuild); if (breakingPoint > 0) { add(new JLabel(clickToBuild.substring(0, breakingPoint)), "span, align center"); add(new JLabel(clickToBuild.substring(breakingPoint + 1)), "span, align center"); } else { add(new JLabel(clickToBuild), "span, align center"); } } else { int turnsToComplete = colony.getTurnsToComplete(buildable); String turnsStr = Messages.getTurnsText(turnsToComplete); add( new JLabel(new ImageIcon(ResourceManager.getImage(buildable.getId() + ".image", 0.75))), "spany"); add( new JLabel( Messages.message( StringTemplate.template("colonyPanel.currentlyBuilding") .addName("%buildable%", buildable)))); add( new JLabel( Messages.message( StringTemplate.template("turnsToComplete.long").addName("%number%", turnsStr)))); for (AbstractGoods requiredGoods : buildable.getGoodsRequired()) { int amountNeeded = requiredGoods.getAmount(); int amountAvailable = colony.getGoodsCount(requiredGoods.getType()); int amountProduced = colony.getAdjustedNetProductionOf(requiredGoods.getType()); add( new FreeColProgressBar( gui, requiredGoods.getType(), 0, amountNeeded, amountAvailable, amountProduced), "height 20:"); } } revalidate(); repaint(); }
/** * Creates an information panel that shows the given texts and images, and an "OK" button. * * @param freeColClient The <code>FreeColClient</code> for the game. * @param texts The texts to be displayed in the panel. * @param fcos The source <code>FreeColObject</code> for the text. * @param images The images to be displayed in the panel. */ public InformationPanel( FreeColClient freeColClient, String[] texts, FreeColObject[] fcos, ImageIcon[] images) { super(freeColClient, new MigLayout("wrap 1, insets 200 10 10 10", "[510]", "[242]20[20]")); final GUI gui = getGUI(); JPanel textPanel = new MigPanel(); textPanel.setOpaque(false); textPanel.setLayout(new MigLayout("wrap 2", "", "top")); for (int i = 0; i < texts.length; i++) { if (images != null && images[i] != null) { textPanel.add(new JLabel(images[i])); textPanel.add( Utility.getDefaultTextArea( texts[i], new Dimension(490 - images[i].getIconWidth(), 225))); } else { textPanel.add(Utility.getDefaultTextArea(texts[i], new Dimension(490, 225)), "skip"); } StringTemplate disp = displayLabel(fcos[i]); if (disp == null) continue; JButton button = Utility.localizedButton( StringTemplate.template("informationPanel.display") .addStringTemplate("%object%", disp)); final FreeColObject fco = fcos[i]; button.addActionListener( new ActionListener() { @Override public void actionPerformed(ActionEvent e) { gui.displayObject(fco); } }); textPanel.add(button, "skip"); } JScrollPane scrollPane = new JScrollPane( textPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); // correct way to make scroll pane opaque scrollPane.getViewport().setOpaque(false); scrollPane.setBorder(null); setBorder(null); add(scrollPane); add(okButton, "tag ok"); }
/** * Create a panel to define trade route cargos. * * @param freeColClient The <code>FreeColClient</code> for the game. * @param newRoute The <code>TradeRoute</code> to operate on. */ public TradeRouteInputPanel(FreeColClient freeColClient, TradeRoute newRoute) { super(freeColClient, new MigLayout("wrap 4, fill", "[]20[fill]rel")); final Game game = freeColClient.getGame(); final Player player = getMyPlayer(); final TradeRoute tradeRoute = newRoute.copy(game, TradeRoute.class); this.newRoute = newRoute; this.cargoHandler = new CargoHandler(); this.dragListener = new DragListener(freeColClient, this); this.dropListener = new DropListener(); this.stopListModel = new DefaultListModel<>(); for (TradeRouteStop stop : tradeRoute.getStops()) { this.stopListModel.addElement(stop); } this.stopList = new JList<>(this.stopListModel); this.stopList.setCellRenderer(new StopRenderer()); this.stopList.setFixedCellHeight(48); this.stopList.setDragEnabled(true); this.stopList.setTransferHandler(new StopListHandler()); this.stopList.addKeyListener( new KeyListener() { @Override public void keyTyped(KeyEvent e) { if (e.getKeyChar() == KeyEvent.VK_DELETE) { deleteCurrentlySelectedStops(); } } @Override public void keyPressed(KeyEvent e) {} // Ignore @Override public void keyReleased(KeyEvent e) {} // Ignore }); this.stopList.addListSelectionListener(this); JScrollPane tradeRouteView = new JScrollPane(stopList); JLabel nameLabel = Utility.localizedLabel("tradeRouteInputPanel.nameLabel"); this.tradeRouteName = new JTextField(tradeRoute.getName()); JLabel destinationLabel = Utility.localizedLabel("tradeRouteInputPanel.destinationLabel"); this.destinationSelector = new JComboBox<>(); this.destinationSelector.setRenderer(new DestinationCellRenderer()); StringTemplate template = StringTemplate.template("tradeRouteInputPanel.allColonies"); this.destinationSelector.addItem(Messages.message(template)); if (player.getEurope() != null) { this.destinationSelector.addItem(player.getEurope().getId()); } for (Colony colony : freeColClient.getMySortedColonies()) { this.destinationSelector.addItem(colony.getId()); } this.messagesBox = new JCheckBox(Messages.message("tradeRouteInputPanel.silence")); this.messagesBox.setSelected(tradeRoute.isSilent()); this.messagesBox.addActionListener( (ActionEvent ae) -> { tradeRoute.setSilent(messagesBox.isSelected()); }); this.addStopButton = Utility.localizedButton("tradeRouteInputPanel.addStop"); this.addStopButton.addActionListener( (ActionEvent ae) -> { addSelectedStops(); }); this.removeStopButton = Utility.localizedButton("tradeRouteInputPanel.removeStop"); this.removeStopButton.addActionListener( (ActionEvent ae) -> { deleteCurrentlySelectedStops(); }); this.goodsPanel = new GoodsPanel(); this.goodsPanel.setTransferHandler(this.cargoHandler); this.goodsPanel.setEnabled(false); this.cargoPanel = new CargoPanel(); this.cargoPanel.setTransferHandler(this.cargoHandler); JButton cancelButton = Utility.localizedButton("cancel"); cancelButton.setActionCommand(CANCEL); cancelButton.addActionListener(this); setCancelComponent(cancelButton); add(Utility.localizedHeader("tradeRouteInputPanel.editRoute", false), "span, align center"); add(tradeRouteView, "span 1 5, grow"); add(nameLabel); add(this.tradeRouteName, "span"); add(destinationLabel); add(this.destinationSelector, "span"); add(this.messagesBox); add(this.addStopButton); add(this.removeStopButton, "span"); add(this.goodsPanel, "span"); add(this.cargoPanel, "span, height 80:, growy"); add(okButton, "newline 20, span, split 2, tag ok"); add(cancelButton, "tag cancel"); // update cargo panel if stop is selected if (this.stopListModel.getSize() > 0) { this.stopList.setSelectedIndex(0); TradeRouteStop selectedStop = this.stopListModel.firstElement(); this.cargoPanel.initialize(selectedStop); } // update buttons according to selection updateButtons(); getGUI().restoreSavedSize(this, getPreferredSize()); }
/** This panel represents a single building in a Colony. */ public class ConstructionPanel extends JPanel implements PropertyChangeListener { private final boolean openBuildQueue; private Colony colony; public static final String EVENT = Colony.ColonyChangeEvent.BUILD_QUEUE_CHANGE.toString(); /** The text to display if buildable == null. */ private StringTemplate defaultLabel = StringTemplate.key("colonyPanel.clickToBuild"); private GUI gui; /** * Creates a ConstructionPanel. * * @param gui The <code>GUI</code> to display on. * @param colony The <code>Colony</code> whose construction is to be modified. * @param openBuildQueue True if the build queue should be immediately shown. */ public ConstructionPanel(GUI gui, Colony colony, boolean openBuildQueue) { this.gui = gui; this.openBuildQueue = openBuildQueue; setLayout(new MigLayout("fill, gapy 2:5, wrap 2", "push[]10[center]push")); setColony(colony); } public void setColony(Colony newColony) { if (newColony != colony) { if (colony != null) { colony.removePropertyChangeListener(EVENT, this); for (MouseListener listener : getMouseListeners()) { removeMouseListener(listener); } } this.colony = newColony; // we are interested in changes to the build queue, as well as // changes to the warehouse and the colony's production bonus colony.addPropertyChangeListener(EVENT, this); if (openBuildQueue) { addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { gui.showBuildQueuePanel(colony); } }); } } initialize(colony.getCurrentlyBuilding()); } private void initialize(BuildableType buildable) { removeAll(); if (buildable == null) { String clickToBuild = Messages.message(getDefaultLabel()); int breakingPoint = Messages.getBreakingPoint(clickToBuild); if (breakingPoint > 0) { add(new JLabel(clickToBuild.substring(0, breakingPoint)), "span, align center"); add(new JLabel(clickToBuild.substring(breakingPoint + 1)), "span, align center"); } else { add(new JLabel(clickToBuild), "span, align center"); } } else { int turnsToComplete = colony.getTurnsToComplete(buildable); String turnsStr = Messages.getTurnsText(turnsToComplete); add( new JLabel(new ImageIcon(ResourceManager.getImage(buildable.getId() + ".image", 0.75))), "spany"); add( new JLabel( Messages.message( StringTemplate.template("colonyPanel.currentlyBuilding") .addName("%buildable%", buildable)))); add( new JLabel( Messages.message( StringTemplate.template("turnsToComplete.long").addName("%number%", turnsStr)))); for (AbstractGoods requiredGoods : buildable.getGoodsRequired()) { int amountNeeded = requiredGoods.getAmount(); int amountAvailable = colony.getGoodsCount(requiredGoods.getType()); int amountProduced = colony.getAdjustedNetProductionOf(requiredGoods.getType()); add( new FreeColProgressBar( gui, requiredGoods.getType(), 0, amountNeeded, amountAvailable, amountProduced), "height 20:"); } } revalidate(); repaint(); } public void update() { initialize(colony.getCurrentlyBuilding()); } /** * Get the <code>DefaultLabel</code> value. * * @return a <code>StringTemplate</code> value */ public final StringTemplate getDefaultLabel() { return defaultLabel; } /** * Set the <code>DefaultLabel</code> value. * * @param newDefaultLabel The new DefaultLabel value. */ public final void setDefaultLabel(final StringTemplate newDefaultLabel) { this.defaultLabel = newDefaultLabel; } public void propertyChange(PropertyChangeEvent event) { List<?> buildQueue = (List<?>) event.getNewValue(); if (buildQueue == null || buildQueue.isEmpty()) { initialize(null); } else { initialize((BuildableType) buildQueue.get(0)); } } public void removePropertyChangeListeners() { colony.removePropertyChangeListener(EVENT, this); } @Override public String getUIClassID() { return "ConstructionPanelUI"; } }
/** * Creates the high scores report. * * @param freeColClient The <code>FreeColClient</code> for the game. * @param prefix An optional message to add at the top of the panel. */ public ReportHighScoresPanel(FreeColClient freeColClient, String prefix) { super(freeColClient, Messages.message("reportHighScoresAction.name")); // Display Panel reportPanel.removeAll(); List<HighScore> highScores = getController().getHighScores(); reportPanel.setLayout(new MigLayout("wrap 3, gapx 30", "[][][align right]", "")); if (prefix != null) { reportPanel.add(new JLabel(Messages.message(prefix)), "span, wrap 10"); } for (HighScore highScore : highScores) { JLabel scoreValue = new JLabel(String.valueOf(highScore.getScore())); scoreValue.setFont(GUI.SMALL_HEADER_FONT); reportPanel.add(scoreValue); String messageID = null; if (highScore.getIndependenceTurn() > 0) { messageID = "report.highScores.president"; } else { messageID = "report.highScores.governor"; } String country = highScore.getNewLandName(); JLabel headline = localizedLabel( Messages.message( StringTemplate.template(messageID) .addName("%name%", highScore.getPlayerName()) .addName("%nation%", country))); headline.setFont(GUI.SMALL_HEADER_FONT); reportPanel.add(headline, "span, wrap 10"); reportPanel.add(new JLabel(Messages.message("report.highScores.turn")), "skip"); int retirementTurn = highScore.getRetirementTurn(); String retirementTurnStr = (retirementTurn <= 0) ? Messages.message("N/A") : Messages.message(Turn.getLabel(retirementTurn)); reportPanel.add(new JLabel(retirementTurnStr)); reportPanel.add(new JLabel(Messages.message("report.highScores.score")), "skip"); reportPanel.add(new JLabel(String.valueOf(highScore.getScore()))); reportPanel.add(new JLabel(Messages.message("report.highScores.difficulty")), "skip"); reportPanel.add(new JLabel(Messages.message(highScore.getDifficulty()))); reportPanel.add(new JLabel(Messages.message("report.highScores.independence")), "skip"); int independenceTurn = highScore.getIndependenceTurn(); String independence = (independenceTurn <= 0) ? Messages.message("no") : Messages.message(Turn.getLabel(independenceTurn)); reportPanel.add(new JLabel(independence)); reportPanel.add(new JLabel(Messages.message("report.highScores.nation")), "skip"); if (highScore.getIndependenceTurn() > 0) { reportPanel.add(new JLabel(highScore.getNationName())); } else { reportPanel.add(new JLabel(Messages.message(highScore.getOldNationNameKey()))); } reportPanel.add(new JLabel(Messages.message("report.highScores.nationType")), "skip"); reportPanel.add(new JLabel(Messages.message(highScore.getNationTypeId() + ".name"))); reportPanel.add(new JLabel(Messages.message("report.highScores.units")), "skip"); reportPanel.add(new JLabel(String.valueOf(highScore.getUnits()))); reportPanel.add(new JLabel(Messages.message("report.highScores.colonies")), "skip"); reportPanel.add(new JLabel(String.valueOf(highScore.getColonies()))); reportPanel.add(new JLabel(Messages.message("report.highScores.retired")), "skip"); DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); reportPanel.add(new JLabel(format.format(highScore.getDate())), "wrap 20"); } reportPanel.doLayout(); }
@SuppressWarnings("unchecked") // FIXME in Java7 private void updateBuildingList() { DefaultListModel buildings = (DefaultListModel) buildingList.getModel(); DefaultListModel current = (DefaultListModel) buildQueueList.getModel(); buildings.clear(); loop: for (BuildingType buildingType : getSpecification().getBuildingTypeList()) { // compare colony.getNoBuildReason() List<String> lockReason = new ArrayList<String>(); Building colonyBuilding = colony.getBuilding(buildingType); if (current.contains(buildingType) || hasBuildingType(buildingType)) { // only one building of any kind continue; } else if (unbuildableTypes.contains(buildingType)) { continue; } else if (!buildingType.needsGoodsToBuild()) { // pre-built continue; } else if (unbuildableTypes.contains(buildingType.getUpgradesFrom())) { // impossible upgrade path unbuildableTypes.add(buildingType); continue; } if (buildingType.getRequiredPopulation() > unitCount) { lockReason.add( Messages.message( StringTemplate.template("colonyPanel.populationTooSmall") .addAmount("%number%", buildingType.getRequiredPopulation()))); } for (Entry<String, Boolean> entry : buildingType.getRequiredAbilities().entrySet()) { if (colony.hasAbility(entry.getKey()) != entry.getValue() && FeatureContainer.hasAbility(featureContainer, entry.getKey(), null, null) != entry.getValue()) { List<FreeColGameObjectType> sources = getSpecification().getTypesProviding(entry.getKey(), entry.getValue()); if (sources.isEmpty()) { // no type provides the required ability unbuildableTypes.add(buildingType); continue loop; } else { lockReason.add(Messages.message(sources.get(0).getNameKey())); } } } if (buildingType.getLimits() != null) { for (Limit limit : buildingType.getLimits()) { if (!limit.evaluate(colony)) { lockReason.add(Messages.message(limit.getDescriptionKey())); } } } if (buildingType.getUpgradesFrom() != null && !current.contains(buildingType.getUpgradesFrom())) { if (colonyBuilding == null || colonyBuilding.getType() != buildingType.getUpgradesFrom()) { lockReason.add(Messages.message(buildingType.getUpgradesFrom().getNameKey())); } } if (lockReason.isEmpty()) { lockReasons.put(buildingType, null); } else { lockReasons.put( buildingType, Messages.message( StringTemplate.template("colonyPanel.requires") .addName("%string%", Utils.join("/", lockReason)))); } if (lockReason.isEmpty() || showAll.isSelected()) { buildings.addElement(buildingType); } } }
@SuppressWarnings("unchecked") // FIXME in Java7 private void updateUnitList() { final Specification spec = getSpecification(); DefaultListModel units = (DefaultListModel) unitList.getModel(); units.clear(); loop: for (UnitType unitType : buildableUnits) { // compare colony.getNoBuildReason() List<String> lockReason = new ArrayList<String>(); if (unbuildableTypes.contains(unitType)) { continue; } if (unitType.getRequiredPopulation() > unitCount) { lockReason.add( Messages.message( StringTemplate.template("colonyPanel.populationTooSmall") .addAmount("%number%", unitType.getRequiredPopulation()))); } if (unitType.getLimits() != null) { for (Limit limit : unitType.getLimits()) { if (!limit.evaluate(colony)) { lockReason.add(Messages.message(limit.getDescriptionKey())); } } } if (!(colony.hasAbility(Ability.BUILD, unitType, getGame().getTurn()) || FeatureContainer.hasAbility(featureContainer, Ability.BUILD, unitType, null))) { boolean builderFound = false; for (Ability ability : spec.getAbilities(Ability.BUILD)) { if (ability.appliesTo(unitType) && ability.getValue() && ability.getSource() != null && !unbuildableTypes.contains(ability.getSource())) { builderFound = true; lockReason.add(Messages.getName(ability.getSource())); break; } } if (!builderFound) { unbuildableTypes.add(unitType); continue; } } for (Entry<String, Boolean> entry : unitType.getRequiredAbilities().entrySet()) { if (colony.hasAbility(entry.getKey()) != entry.getValue() && FeatureContainer.hasAbility(featureContainer, entry.getKey(), null, null) != entry.getValue()) { List<FreeColGameObjectType> sources = spec.getTypesProviding(entry.getKey(), entry.getValue()); if (sources.isEmpty()) { // no type provides the required ability unbuildableTypes.add(unitType); continue loop; } else { lockReason.add(Messages.message(sources.get(0).getNameKey())); } } } if (lockReason.isEmpty()) { lockReasons.put(unitType, null); } else { lockReasons.put( unitType, Messages.message( StringTemplate.template("colonyPanel.requires") .addName("%string%", Utils.join("/", lockReason)))); } if (lockReason.isEmpty() || showAll.isSelected()) { units.addElement(unitType); } } }
@SuppressWarnings("unchecked") // FIXME in Java7 public BuildQueuePanel(FreeColClient freeColClient, GUI gui, Colony colony) { super( freeColClient, gui, new MigLayout("wrap 3", "[260:][390:, fill][260:]", "[][][300:400:][]")); this.colony = colony; this.unitCount = colony.getUnitCount(); featureContainer = new FeatureContainer(); for (UnitType unitType : getSpecification().getUnitTypeList()) { if (unitType.needsGoodsToBuild() && !unitType.hasAbility(Ability.BORN_IN_COLONY)) { buildableUnits.add(unitType); // can be built } } DefaultListModel current = new DefaultListModel(); for (BuildableType type : colony.getBuildQueue()) { current.addElement(type); FeatureContainer.addFeatures(featureContainer, type); } cellRenderer = getCellRenderer(); // remove previous listeners for (ItemListener listener : compact.getItemListeners()) { compact.removeItemListener(listener); } compact.setText(Messages.message("colonyPanel.compactView")); compact.addItemListener(this); // remove previous listeners for (ItemListener listener : showAll.getItemListeners()) { showAll.removeItemListener(listener); } showAll.setText(Messages.message("colonyPanel.showAll")); showAll.addItemListener(this); buildQueueList = new JList(current); buildQueueList.setTransferHandler(buildQueueHandler); buildQueueList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); buildQueueList.setDragEnabled(true); buildQueueList.setCellRenderer(cellRenderer); buildQueueList.addMouseListener(new BuildQueueMouseAdapter(false)); Action deleteAction = new AbstractAction() { @SuppressWarnings("deprecation") // FIXME in Java7 public void actionPerformed(ActionEvent e) { for (Object type : buildQueueList.getSelectedValues()) { removeBuildable(type); } updateAllLists(); } }; buildQueueList.getInputMap().put(KeyStroke.getKeyStroke("DELETE"), "delete"); buildQueueList.getActionMap().put("delete", deleteAction); Action addAction = new AbstractAction() { @SuppressWarnings("deprecation") // FIXME in Java7 public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) buildQueueList.getModel(); for (Object type : ((JList) e.getSource()).getSelectedValues()) { model.addElement(type); } updateAllLists(); } }; BuildQueueMouseAdapter adapter = new BuildQueueMouseAdapter(true); DefaultListModel units = new DefaultListModel(); unitList = new JList(units); unitList.setTransferHandler(buildQueueHandler); unitList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); unitList.setDragEnabled(true); unitList.setCellRenderer(cellRenderer); unitList.addMouseListener(adapter); unitList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "add"); unitList.getActionMap().put("add", addAction); DefaultListModel buildings = new DefaultListModel(); buildingList = new JList(buildings); buildingList.setTransferHandler(buildQueueHandler); buildingList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); buildingList.setDragEnabled(true); buildingList.setCellRenderer(cellRenderer); buildingList.addMouseListener(adapter); buildingList.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "add"); buildingList.getActionMap().put("add", addAction); JLabel headLine = new JLabel(Messages.message("colonyPanel.buildQueue")); headLine.setFont(bigHeaderFont); buyBuilding = new JButton(Messages.message("colonyPanel.buyBuilding")); buyBuilding.setActionCommand(BUY); buyBuilding.addActionListener(this); constructionPanel = new ConstructionPanel(gui, colony, false); constructionPanel.setOpaque(false); StringTemplate buildingNothing = StringTemplate.template("colonyPanel.currentlyBuilding").add("%buildable%", "nothing"); constructionPanel.setDefaultLabel(buildingNothing); updateAllLists(); add(headLine, "span 3, align center, wrap 40"); add(new JLabel(Messages.message("colonyPanel.units")), "align center"); add(new JLabel(Messages.message("colonyPanel.buildQueue")), "align center"); add(new JLabel(Messages.message("colonyPanel.buildings")), "align center"); add(new JScrollPane(unitList), "grow"); add(constructionPanel, "split 2, flowy"); add(new JScrollPane(buildQueueList), "grow"); add(new JScrollPane(buildingList), "grow, wrap 20"); add(buyBuilding, "span, split 4"); add(compact); add(showAll); add(okButton, "tag ok"); }