From: Erik V. <ev...@us...> - 2011-08-14 21:23:07
|
rails/ui/swing/GameStatus.java | 207 +++++++++++++++++++---------------------- 1 file changed, 97 insertions(+), 110 deletions(-) New commits: commit 0a746d147813b99417ec229d39d4b32e359732f0 Author: Erik Vos <eri...@xs...> Date: Sun Aug 14 23:21:14 2011 +0200 Fixed player highlighting in GameStatus window after a change in player order. diff --git a/rails/ui/swing/GameStatus.java b/rails/ui/swing/GameStatus.java index 41389af..71a1ce4 100644 --- a/rails/ui/swing/GameStatus.java +++ b/rails/ui/swing/GameStatus.java @@ -113,11 +113,11 @@ public class GameStatus extends GridPanel implements ActionListener { protected ClickField dummyButton; // To be selected if none else is. protected Map<PublicCompanyI, Integer> companyIndex = - new HashMap<PublicCompanyI, Integer>(); + new HashMap<PublicCompanyI, Integer>(); protected Map<Player, Integer> playerIndex = new HashMap<Player, Integer>(); protected static Logger log = - Logger.getLogger(GameStatus.class.getPackage().getName()); + Logger.getLogger(GameStatus.class.getPackage().getName()); public GameStatus() { super(); @@ -271,8 +271,8 @@ public class GameStatus extends GridPanel implements ActionListener { if (compCanHoldOwnShares) { addField(treasurySharesCaption = - new Caption(LocalText.getText("TREASURY_SHARES")), - certInTreasuryXOffset, 0, 1, 2, WIDE_RIGHT + WIDE_BOTTOM, true); + new Caption(LocalText.getText("TREASURY_SHARES")), + certInTreasuryXOffset, 0, 1, 2, WIDE_RIGHT + WIDE_BOTTOM, true); } if (this.hasParPrices) { @@ -289,7 +289,7 @@ public class GameStatus extends GridPanel implements ActionListener { } addField(new Caption(LocalText.getText("COMPANY_DETAILS")), compCashXOffset, 0, 4 + (compCanBuyPrivates ? 1 : 0) - + (hasCompanyLoans ? 1 : 0), 1, 0, true); + + (hasCompanyLoans ? 1 : 0), 1, 0, true); addField(new Caption(LocalText.getText("CASH")), compCashXOffset, 1, 1, 1, WIDE_BOTTOM, true); addField(new Caption(LocalText.getText("REVENUE")), compRevenueXOffset, @@ -318,7 +318,7 @@ public class GameStatus extends GridPanel implements ActionListener { c = companies[i]; companyIndex.put(c, new Integer(i)); rowVisibilityObservers[i] - = new RowVisibility (this, certPerPlayerYOffset + i, c.getInGameModel(), false); + = new RowVisibility (this, certPerPlayerYOffset + i, c.getInGameModel(), false); boolean visible = rowVisibilityObservers[i].lastValue(); f = new Caption(c.getName()); @@ -328,29 +328,29 @@ public class GameStatus extends GridPanel implements ActionListener { for (int j = 0; j < np; j++) { f = - certPerPlayer[i][j] = - new Field( - players[j].getPortfolio().getShareModel( - c)); + certPerPlayer[i][j] = + new Field( + players[j].getPortfolio().getShareModel( + c)); addField(f, certPerPlayerXOffset + j, certPerPlayerYOffset + i, 1, 1, 0, visible); f = - certPerPlayerButton[i][j] = - new ClickField("", SELL_CMD, - LocalText.getText("ClickForSell"), - this, buySellGroup); + certPerPlayerButton[i][j] = + new ClickField("", SELL_CMD, + LocalText.getText("ClickForSell"), + this, buySellGroup); addField(f, certPerPlayerXOffset + j, certPerPlayerYOffset + i, 1, 1, 0, false); } f = certInIPO[i] = new Field(ipo.getShareModel(c)); addField(f, certInIPOXOffset, certInIPOYOffset + i, 1, 1, WIDE_LEFT, visible); f = - certInIPOButton[i] = - new ClickField( - certInIPO[i].getText(), - BUY_FROM_IPO_CMD, - LocalText.getText("ClickToSelectForBuying"), - this, buySellGroup); + certInIPOButton[i] = + new ClickField( + certInIPO[i].getText(), + BUY_FROM_IPO_CMD, + LocalText.getText("ClickToSelectForBuying"), + this, buySellGroup); addField(f, certInIPOXOffset, certInIPOYOffset + i, 1, 1, WIDE_LEFT, false); certInIPO[i].setPreferredSize(certInIPOButton[i].getPreferredSize()); @@ -358,29 +358,29 @@ public class GameStatus extends GridPanel implements ActionListener { addField(f, certInPoolXOffset, certInPoolYOffset + i, 1, 1, WIDE_RIGHT, visible); f = - certInPoolButton[i] = - new ClickField( - certInPool[i].getText(), - BUY_FROM_POOL_CMD, - LocalText.getText("ClickToSelectForBuying"), - this, buySellGroup); + certInPoolButton[i] = + new ClickField( + certInPool[i].getText(), + BUY_FROM_POOL_CMD, + LocalText.getText("ClickToSelectForBuying"), + this, buySellGroup); addField(f, certInPoolXOffset, certInPoolYOffset + i, 1, 1, WIDE_RIGHT, false); certInPool[i].setPreferredSize(certInIPOButton[i].getPreferredSize());/* sic */ if (compCanHoldOwnShares) { f = - certInTreasury[i] = - new Field(c.getPortfolio().getShareModel(c)); + certInTreasury[i] = + new Field(c.getPortfolio().getShareModel(c)); addField(f, certInTreasuryXOffset, certInTreasuryYOffset + i, 1, 1, WIDE_RIGHT, visible); f = - certInTreasuryButton[i] = - new ClickField( - certInTreasury[i].getText(), - BUY_FROM_POOL_CMD, - LocalText.getText("ClickForSell"), - this, buySellGroup); + certInTreasuryButton[i] = + new ClickField( + certInTreasury[i].getText(), + BUY_FROM_POOL_CMD, + LocalText.getText("ClickForSell"), + this, buySellGroup); addField(f, certInTreasuryXOffset, certInTreasuryYOffset + i, 1, 1, WIDE_RIGHT, false); certInTreasury[i].setPreferredSize(certInTreasuryButton[i].getPreferredSize());/* sic */ @@ -399,13 +399,13 @@ public class GameStatus extends GridPanel implements ActionListener { addField(f, compCashXOffset, compCashYOffset + i, 1, 1, 0, visible); f = compCashButton[i] = - new ClickField( - compCash[i].getText(), - CASH_CORRECT_CMD, - LocalText.getText("CorrectCashToolTip"), - this, buySellGroup); + new ClickField( + compCash[i].getText(), + CASH_CORRECT_CMD, + LocalText.getText("CorrectCashToolTip"), + this, buySellGroup); addField(f, compCashXOffset, compCashYOffset + i, 1, 1, - WIDE_RIGHT, false); + WIDE_RIGHT, false); f = compRevenue[i] = new Field(c.getLastRevenueModel()); addField(f, compRevenueXOffset, compRevenueYOffset + i, 1, 1, 0, visible); @@ -418,9 +418,9 @@ public class GameStatus extends GridPanel implements ActionListener { if (this.compCanBuyPrivates) { f = - compPrivates[i] = - new Field( - c.getPortfolio().getPrivatesOwnedModel()); + compPrivates[i] = + new Field( + c.getPortfolio().getPrivatesOwnedModel()); addField(f, compPrivatesXOffset, compPrivatesYOffset + i, 1, 1, 0, visible); } @@ -432,7 +432,7 @@ public class GameStatus extends GridPanel implements ActionListener { } addField (f, compLoansXOffset, compLoansYOffset+i, 1, 1, 0, visible); } - + if (hasRights) { f = rights[i] = new Field (c.getRightsModel()); addField (f, rightsXOffset, rightsYOffset + i, 1, 1, 0, visible); @@ -455,11 +455,11 @@ public class GameStatus extends GridPanel implements ActionListener { WIDE_TOP, true); f = playerCashButton[i] = - new ClickField( - playerCash[i].getText(), - CASH_CORRECT_CMD, - LocalText.getText("CorrectCashToolTip"), - this, buySellGroup); + new ClickField( + playerCash[i].getText(), + CASH_CORRECT_CMD, + LocalText.getText("CorrectCashToolTip"), + this, buySellGroup); addField(f, playerCashXOffset + i, playerCashYOffset, 1, 1, WIDE_TOP, false); } @@ -468,9 +468,9 @@ public class GameStatus extends GridPanel implements ActionListener { WIDE_RIGHT, false); for (int i = 0; i < np; i++) { f = - playerPrivates[i] = - new Field( - players[i].getPortfolio().getPrivatesOwnedModel()); + playerPrivates[i] = + new Field( + players[i].getPortfolio().getPrivatesOwnedModel()); addField(f, playerPrivatesXOffset + i, playerPrivatesYOffset, 1, 1, 0, true); } @@ -493,8 +493,8 @@ public class GameStatus extends GridPanel implements ActionListener { WIDE_RIGHT + WIDE_TOP, true); for (int i = 0; i < np; i++) { f = - playerCertCount[i] = - new Field(players[i].getCertCountModel(), true); + playerCertCount[i] = + new Field(players[i].getCertCountModel(), true); addField(f, playerCertCountXOffset + i, playerCertCountYOffset, 1, 1, WIDE_TOP, true); } @@ -529,7 +529,7 @@ public class GameStatus extends GridPanel implements ActionListener { // Trains addField(new Caption(LocalText.getText("TRAINS")), poolTrainsXOffset - 1, poolTrainsYOffset - 1, 1, 2, WIDE_TOP - + WIDE_LEFT, true); + + WIDE_LEFT, true); addField(new Caption(LocalText.getText("USED")), poolTrainsXOffset, poolTrainsYOffset - 1, 1, 1, WIDE_TOP, true); poolTrains = new Field(pool.getTrainsModel()); @@ -586,12 +586,12 @@ public class GameStatus extends GridPanel implements ActionListener { for (int i = 1; i <= sale.getMaximumNumber(); i++) { options.add(LocalText.getText("SellShares", - i, + i, sale.getShare(), i * sale.getShare(), sale.getCompanyName(), Bank.format(i * sale.getShareUnits() - * sale.getPrice()) )); + * sale.getPrice()) )); sellActions.add(sale); sellAmounts.add(i); } @@ -600,17 +600,17 @@ public class GameStatus extends GridPanel implements ActionListener { if (options.size() > 1) { String message = LocalText.getText("PleaseSelect"); String sp = - (String) JOptionPane.showInputDialog(this, message, - message, JOptionPane.QUESTION_MESSAGE, - null, options.toArray(new String[0]), - options.get(0)); + (String) JOptionPane.showInputDialog(this, message, + message, JOptionPane.QUESTION_MESSAGE, + null, options.toArray(new String[0]), + options.get(0)); index = options.indexOf(sp); } else if (options.size() == 1) { String message = LocalText.getText("PleaseConfirm"); int result = - JOptionPane.showConfirmDialog(this, options.get(0), - message, JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + JOptionPane.showConfirmDialog(this, options.get(0), + message, JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); index = (result == JOptionPane.OK_OPTION ? 0 : -1); } if (index < 0) { @@ -624,7 +624,7 @@ public class GameStatus extends GridPanel implements ActionListener { List<String> options = new ArrayList<String>(); List<BuyCertificate> buyActions = - new ArrayList<BuyCertificate>(); + new ArrayList<BuyCertificate>(); List<Integer> buyAmounts = new ArrayList<Integer>(); BuyCertificate buy; PublicCertificateI cert; @@ -650,7 +650,7 @@ public class GameStatus extends GridPanel implements ActionListener { int[] startPrices; if (((StartCompany) buy).mustSelectAPrice()) { startPrices = - ((StartCompany) buy).getStartPrices(); + ((StartCompany) buy).getStartPrices(); Arrays.sort(startPrices); if (startPrices.length > 1) { for (int i = 0; i < startPrices.length; i++) { @@ -695,7 +695,7 @@ public class GameStatus extends GridPanel implements ActionListener { companyName, buy.getFromPortfolio().getName(), Bank.format(i * sharesPerCert - * buy.getPrice()) )); + * buy.getPrice()) )); buyActions.add(buy); buyAmounts.add(i); } @@ -704,34 +704,34 @@ public class GameStatus extends GridPanel implements ActionListener { int index = 0; if (options.size() > 1) { if (startCompany) { - RadioButtonDialog dialog = new RadioButtonDialog ( + RadioButtonDialog dialog = new RadioButtonDialog ( gameUIManager, parent, LocalText.getText("PleaseSelect"), LocalText.getText("WHICH_START_PRICE", playerName, companyName), - options.toArray(new String[0]), -1); + options.toArray(new String[0]), -1); gameUIManager.setCurrentDialog(dialog, actions.get(0)); return; } else { String sp = - (String) JOptionPane.showInputDialog(this, - LocalText.getText(startCompany - ? "WHICH_PRICE" - : "HOW_MANY_SHARES"), - LocalText.getText("PleaseSelect"), - JOptionPane.QUESTION_MESSAGE, null, - options.toArray(new String[0]), - options.get(0)); + (String) JOptionPane.showInputDialog(this, + LocalText.getText(startCompany + ? "WHICH_PRICE" + : "HOW_MANY_SHARES"), + LocalText.getText("PleaseSelect"), + JOptionPane.QUESTION_MESSAGE, null, + options.toArray(new String[0]), + options.get(0)); index = options.indexOf(sp); } } else if (options.size() == 1) { int result = - JOptionPane.showConfirmDialog(this, options.get(0), - LocalText.getText("PleaseConfirm"), - JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE); + JOptionPane.showConfirmDialog(this, options.get(0), + LocalText.getText("PleaseConfirm"), + JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE); index = (result == JOptionPane.OK_OPTION ? 0 : -1); } if (index < 0) { @@ -763,7 +763,7 @@ public class GameStatus extends GridPanel implements ActionListener { } else { chosenAction = - processGameSpecificActions(actor, actions.get(0)); + processGameSpecificActions(actor, actions.get(0)); } } else { @@ -789,22 +789,12 @@ public class GameStatus extends GridPanel implements ActionListener { ActionEvent actor, PossibleAction chosenAction) { return chosenAction; } - + public void initTurn(int actorIndex, boolean myTurn) { int i, j; dummyButton.setSelected(true); - // Reset previous highlights - if ((j = this.actorIndex) >= 0) { - upperPlayerCaption[j].setHighlight(false); - lowerPlayerCaption[j].setHighlight(false); - for (i = 0; i < nc; i++) { - setPlayerCertButton(i, j, false); - } - } else if (j == -1 && compCanHoldOwnShares) { - treasurySharesCaption.setHighlight(false); - } for (i = 0; i < nc; i++) { setIPOCertButton(i, false); setPoolCertButton(i, false); @@ -814,24 +804,21 @@ public class GameStatus extends GridPanel implements ActionListener { this.actorIndex = actorIndex; + highlightCurrentPlayer(playerIndex.get(gameUIManager.getCurrentPlayer())); + if (treasurySharesCaption != null) treasurySharesCaption.setHighlight(actorIndex == -1); + // Set new highlights if ((j = this.actorIndex) >= -1) { - if (j >= 0) { - upperPlayerCaption[j].setHighlight(true); - lowerPlayerCaption[j].setHighlight(true); - } else if (j == -1 && treasurySharesCaption != null) { - treasurySharesCaption.setHighlight(true); - } - + if (myTurn) { PublicCompanyI company; Portfolio holder; int index; CashHolder owner; - + List<BuyCertificate> buyableCerts = - possibleActions.getType(BuyCertificate.class); + possibleActions.getType(BuyCertificate.class); if (buyableCerts != null) { for (BuyCertificate bCert : buyableCerts) { company = bCert.getCompany(); @@ -849,9 +836,9 @@ public class GameStatus extends GridPanel implements ActionListener { } } } - + List<SellShares> sellableShares = - possibleActions.getType(SellShares.class); + possibleActions.getType(SellShares.class); if (sellableShares != null) { for (SellShares share : sellableShares) { company = share.getCompany(); @@ -863,11 +850,11 @@ public class GameStatus extends GridPanel implements ActionListener { } } } - + initGameSpecificActions(); - + List<NullAction> nullActions = - possibleActions.getType(NullAction.class); + possibleActions.getType(NullAction.class); if (nullActions != null) { for (NullAction na : nullActions) { (parent).setPassButton(na); @@ -924,10 +911,10 @@ public class GameStatus extends GridPanel implements ActionListener { for (int j = 0; j < np; j++) { upperPlayerCaption[j].setText(players[j].getName() - + (j == index ? " PD" : "")); + + (j == index ? " PD" : "")); } } - + public void highlightCurrentPlayer (int index) { for (int j = 0; j < np; j++) { upperPlayerCaption[j].setHighlight(j == index); @@ -1045,7 +1032,7 @@ public class GameStatus extends GridPanel implements ActionListener { compCashButton[i].setText(compCash[i].getText()); } else { compCashButton[i].clearPossibleActions(); -} + } compCash[i].setVisible(visible && !clickable); compCashButton[i].setVisible(visible && clickable); if (action != null) |
From: Stefan F. <ste...@us...> - 2011-11-03 11:56:34
|
rails/ui/swing/ORPanel.java | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) New commits: commit cea7752364090c76b28874e85cdb8f58e03ce90d Author: Stefan Frey <ste...@we...> Date: Wed Oct 12 16:14:20 2011 +0200 fixed display of operating companies in networkinfo menu diff --git a/rails/ui/swing/ORPanel.java b/rails/ui/swing/ORPanel.java index fa5313d..c81a82b 100644 --- a/rails/ui/swing/ORPanel.java +++ b/rails/ui/swing/ORPanel.java @@ -52,6 +52,7 @@ implements ActionListener, KeyListener, RevenueListener { private JMenuItem remainingTilesMenuItem; private JMenu trainsInfoMenu; private JMenu phasesInfoMenu; + private JMenu networkInfoMenu; private JMenu specialMenu; private JMenu loansMenu; private JMenu zoomMenu; @@ -231,6 +232,11 @@ implements ActionListener, KeyListener, RevenueListener { // Create new fields initFields(); + + // update the networkInfo menu + // TODO: This relies on a recreate as soon as companies have changed + addNetworkInfo(); + repaint(); } @@ -586,15 +592,21 @@ implements ActionListener, KeyListener, RevenueListener { } protected void addNetworkInfo() { + if (networkInfoMenu != null) infoMenu.remove(networkInfoMenu); + networkInfoMenu = createNetworkInfo(); + if (networkInfoMenu == null) return; + networkInfoMenu.setEnabled(true); + infoMenu.add(networkInfoMenu); + } + + protected JMenu createNetworkInfo() { boolean route_highlight = orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.ROUTE_HIGHLIGHT); boolean revenue_suggest = orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.REVENUE_SUGGEST); - if (!route_highlight && !revenue_suggest) return; + if (!route_highlight && !revenue_suggest) return null; JMenu networkMenu = new JMenu(LocalText.getText("NetworkInfo")); - networkMenu.setEnabled(true); - infoMenu.add(networkMenu); if (route_highlight) { JMenuItem item = new JMenuItem("Network"); @@ -613,6 +625,8 @@ implements ActionListener, KeyListener, RevenueListener { networkMenu.add(item); } } + + return networkMenu; } protected void executeNetworkInfo(String companyName) { |
From: Erik V. <ev...@us...> - 2012-01-05 14:29:07
|
rails/ui/swing/StartRoundWindow.java | 89 +++++++++++++++++++++++++---------- 1 file changed, 65 insertions(+), 24 deletions(-) New commits: commit 985d6827aa5b9d985ef97d0fd9f18165f388ff55 Author: Erik Vos <eri...@xs...> Date: Thu Jan 5 15:27:02 2012 +0100 Change president share price setting in Start rounds to use non-modal pop-up. The popup is the same RadioButtonDialog that is already used when setting a start share price in stock rounds. diff --git a/rails/ui/swing/StartRoundWindow.java b/rails/ui/swing/StartRoundWindow.java index d27294b..2282593 100644 --- a/rails/ui/swing/StartRoundWindow.java +++ b/rails/ui/swing/StartRoundWindow.java @@ -19,8 +19,9 @@ import rails.ui.swing.elements.*; /** * This displays the Auction Window */ -public class StartRoundWindow extends JFrame implements ActionListener, -KeyListener, ActionPerformer { +public class StartRoundWindow extends JFrame +implements ActionListener, KeyListener, ActionPerformer, DialogOwner { + private static final long serialVersionUID = 1L; // Gap sizes between screen cells, in pixels @@ -81,6 +82,11 @@ KeyListener, ActionPerformer { private StartRound round; private GameUIManager gameUIManager; + // For the non-modal dialog to ask for a company starting share price. + protected JDialog currentDialog = null; + protected PossibleAction currentDialogAction = null; + protected int[] startPrices = null; + private StartItem si; private JComponent f; @@ -516,7 +522,7 @@ KeyListener, ActionPerformer { StartItemAction action = (StartItemAction) nextAction; if (action instanceof BuyStartItem) { requestStartPrice((BuyStartItem) action); - return process(action); + return false; } } } @@ -577,8 +583,7 @@ KeyListener, ActionPerformer { if (source == buyButton) { if (activeItem instanceof BuyStartItem && ((BuyStartItem) activeItem).hasSharePriceToSet()) { - if (requestStartPrice((BuyStartItem) activeItem)) - process(activeItem); + if (requestStartPrice((BuyStartItem) activeItem)) return; } else { process(activeItem); } @@ -611,34 +616,70 @@ KeyListener, ActionPerformer { List<StockSpaceI> startSpaces = stockMarket.getStartSpaces(); Map<Integer, StockSpaceI> spacePerPrice = new HashMap<Integer, StockSpaceI>(); - int[] prices = new int[startSpaces.size()]; - StockSpaceI[] options = new StockSpaceI[startSpaces.size()]; + startPrices = new int[startSpaces.size()]; + String[] options = new String[startSpaces.size()]; for (int i = 0; i < startSpaces.size(); i++) { - prices[i] = startSpaces.get(i).getPrice(); - spacePerPrice.put(prices[i], startSpaces.get(i)); + startPrices[i] = startSpaces.get(i).getPrice(); + spacePerPrice.put(startPrices[i], startSpaces.get(i)); } - Arrays.sort(prices); + Arrays.sort(startPrices); for (int i = 0; i < startSpaces.size(); i++) { - options[i] = spacePerPrice.get(prices[i]); + options[i] = Bank.format(spacePerPrice.get(startPrices[i]).getPrice()); } - StockSpace sp = - (StockSpace) JOptionPane.showInputDialog(this, - LocalText.getText("WHICH_START_PRICE", - activeItem.getPlayerName(), - compName), - LocalText.getText("WHICH_PRICE"), - JOptionPane.QUESTION_MESSAGE, null, options, - options[0]); - if (sp == null) { - return false; - } - int price = sp.getPrice(); - activeItem.setAssociatedSharePrice(price); + RadioButtonDialog dialog = new RadioButtonDialog(this, + this, + LocalText.getText("PleaseSelect"), + LocalText.getText("WHICH_START_PRICE", + getSRPlayer(), + compName), + options, + -1); + setCurrentDialog (dialog, activeItem); + } return true; } + public JDialog getCurrentDialog() { + return currentDialog; + } + + public PossibleAction getCurrentDialogAction () { + return currentDialogAction; + } + + public void setCurrentDialog (JDialog dialog, PossibleAction action) { + if (currentDialog != null) { + currentDialog.dispose(); + } + currentDialog = dialog; + currentDialogAction = action; + } + + public void dialogActionPerformed () { + + if (currentDialog instanceof RadioButtonDialog + && currentDialogAction instanceof BuyStartItem) { + + RadioButtonDialog dialog = (RadioButtonDialog) currentDialog; + BuyStartItem action = (BuyStartItem) currentDialogAction; + + int index = dialog.getSelectedOption(); + if (index >= 0) { + int price = startPrices[index]; + action.setAssociatedSharePrice(price); + process (action); + } else { + // No selection done - no action + return; + } + + } else { + return; + } + } + public void close() { this.dispose(); } |
From: Frederick W. <fre...@us...> - 2012-01-10 11:22:28
|
rails/ui/swing/ImageLoader.java | 22 +++++++++- rails/ui/swing/MapPanel.java | 81 ++++++++++++++++++++++++++++++++++++-- rails/ui/swing/hexmap/HexMap.java | 44 ++------------------ 3 files changed, 105 insertions(+), 42 deletions(-) New commits: commit 38e4a6e05fae1349af459ed47c438271dc7373da Author: Frederick Weld <fre...@gm...> Date: Tue Jan 10 12:16:54 2012 +0100 Added round-off to the fit-to-xyz zoom (continuous zoom, scroll bar) The current logic of discrete zoom steps is still valid - but it is complemented by a continuous adjustment factor ("last mile adjustment"). In addition, the appearance and width of the scroll bar is now considered. diff --git a/rails/ui/swing/ImageLoader.java b/rails/ui/swing/ImageLoader.java index b22bcbf..f663639 100644 --- a/rails/ui/swing/ImageLoader.java +++ b/rails/ui/swing/ImageLoader.java @@ -27,6 +27,9 @@ public class ImageLoader { private static Map<Integer, Document> svgMap; private static double[] zoomFactors = new double[21]; + //defines adjustment of zoom factor (should be close to 1) + //(used for perfect-fit sizing that requires arbitrary zoom) + private static double zoomAdjustmentFactor = 1; private static double svgWidth = 75; private static double svgHeight = svgWidth * 0.5 * Math.sqrt(3.0); @@ -129,11 +132,28 @@ public class ImageLoader { if (zoomStep < 0) zoomStep = 0; else if (zoomStep > 20) zoomStep = 20; if (zoomFactors[zoomStep] == 0.0) { - zoomFactors[zoomStep] = 1.0 * Math.pow(2.0, 0.25*(zoomStep-10)); + zoomFactors[zoomStep] = zoomAdjustmentFactor * Math.pow(2.0, 0.25*(zoomStep-10)); } return zoomFactors[zoomStep]; } + + /** + * @param zoomAdjustmentFactor Additional factor applied to zoom factor. Used + * for precisely adjusting zoom-step based zoom factors for perfect fit requirements. + */ + public void setZoomAdjustmentFactor (double zoomAdjustmentFactor) { + ImageLoader.zoomAdjustmentFactor = zoomAdjustmentFactor; + + //invalidate buffered zoom step zoom factors + for (int i = 0 ; i < zoomFactors.length ; i++) { + zoomFactors[i] = 0; + } + } + + public void resetAdjustmentFactor() { + setZoomAdjustmentFactor(1); + } public ImageLoader() { directories.add(tileRootDir + svgTileDir); diff --git a/rails/ui/swing/MapPanel.java b/rails/ui/swing/MapPanel.java index e1be54b..6175b9b 100644 --- a/rails/ui/swing/MapPanel.java +++ b/rails/ui/swing/MapPanel.java @@ -20,11 +20,14 @@ import rails.ui.swing.hexmap.*; public class MapPanel extends JPanel { private static final long serialVersionUID = 1L; + //defines how many pixels should be left as safety margin when calculating fit zooms + private static final int zoomFitSafetyMargin = 4; + private MapManager mmgr; private HexMap map; private HexMapImage mapImage; private JScrollPane scrollPane; - + private GameUIManager gameUIManager; private JLayeredPane layeredPane; @@ -132,8 +135,80 @@ public class MapPanel extends JPanel { adjustToNewMapZoom(); } - private void zoomFit (boolean fitWidth, boolean fitHeight) { - map.zoomFit (getSize(), fitWidth, fitHeight); + /** + * Zoom-to-fit functionality is based on the discrete zoom steps. + * In order to achieve correctly fitting zoom, continuous adjustment factors are + * determined on top of that. + */ + private void zoomFit (boolean fitToWidth, boolean fitToHeight) { + ImageLoader imageLoader = GameUIManager.getImageLoader(); + int zoomStep = map.getZoomStep(); + + //reset adjustment factor + imageLoader.resetAdjustmentFactor(); + + //determine the available size to fit to + //(double needed for subsequent calculations) + double width = getSize().width - zoomFitSafetyMargin; + double height = getSize().height - zoomFitSafetyMargin; + + double idealFactorWidth = width / originalMapSize.width; + double idealFactorHeight = height / originalMapSize.height; + + //determine which dimension will be the critical one for the resize + boolean isWidthCritical = ( !fitToHeight + || (fitToWidth && idealFactorWidth < idealFactorHeight)); + + //check whether scrollbar will appear in the fit-to dimension and + //reduce available size accordingly (not relevant for fit-to-window) + if (isWidthCritical && idealFactorWidth > idealFactorHeight) { + width -= scrollPane.getVerticalScrollBar().getPreferredSize().width; + idealFactorWidth = width / originalMapSize.width; + } + if (!isWidthCritical && idealFactorWidth < idealFactorHeight) { + height -= scrollPane.getHorizontalScrollBar().getPreferredSize().height; + idealFactorHeight = height / originalMapSize.height; + } + + //abort resize if no space available + if (width < 0 || height < 0) return; + + //increase zoomFactor until constraints do not hold + //OR zoom cannot be increased any more + while + ( + ( + (!fitToWidth || idealFactorWidth > imageLoader.getZoomFactor(zoomStep)) + && + (!fitToHeight || idealFactorHeight > imageLoader.getZoomFactor(zoomStep)) + ) + && + imageLoader.getZoomFactor(zoomStep+1) != imageLoader.getZoomFactor(zoomStep) + ) + zoomStep++; + + //decrease zoomFactor until constraints do hold + //OR zoom cannot be decreased any more + while + ( + ( + (fitToWidth && idealFactorWidth < imageLoader.getZoomFactor(zoomStep)) + || + (fitToHeight && idealFactorHeight < imageLoader.getZoomFactor(zoomStep)) + ) + && + imageLoader.getZoomFactor(zoomStep-1) != imageLoader.getZoomFactor(zoomStep) + ) + zoomStep--; + + //Determine and apply adjustment factor for precise fit + double idealFactor = isWidthCritical ? idealFactorWidth : idealFactorHeight; + imageLoader.setZoomAdjustmentFactor ( + idealFactor / imageLoader.getZoomFactor(zoomStep)); + + //trigger zoom execution + map.setZoomStep(zoomStep); + adjustToNewMapZoom(); } diff --git a/rails/ui/swing/hexmap/HexMap.java b/rails/ui/swing/hexmap/HexMap.java index 0dc3c1a..e862f6d 100644 --- a/rails/ui/swing/hexmap/HexMap.java +++ b/rails/ui/swing/hexmap/HexMap.java @@ -562,43 +562,15 @@ public abstract class HexMap implements MouseListener, zoom(); } -/** - * Zoom-to-fit functionality is based on the discrete zoom steps. - * This means that no pixel precision is to be expected - */ - public void zoomFit (Dimension availableSize, boolean fitToWidth, boolean fitToHeight) { - double idealFactorWidth = availableSize.getWidth() / originalSize.width; - double idealFactorHeight = availableSize.getHeight() / originalSize.height; - //increase zoomFactor until constraints do not hold - //OR zoom cannot be increased any more - while - ( - ( - (!fitToWidth || idealFactorWidth > GameUIManager.getImageLoader().getZoomFactor(zoomStep)) - && - (!fitToHeight || idealFactorHeight > GameUIManager.getImageLoader().getZoomFactor(zoomStep)) - ) - && - GameUIManager.getImageLoader().getZoomFactor(zoomStep+1) != GameUIManager.getImageLoader().getZoomFactor(zoomStep) - ) - zoomStep++; - //decrease zoomFactor until constraints do hold - //OR zoom cannot be decreased any more - while - ( - ( - (fitToWidth && idealFactorWidth < GameUIManager.getImageLoader().getZoomFactor(zoomStep)) - || - (fitToHeight && idealFactorHeight < GameUIManager.getImageLoader().getZoomFactor(zoomStep)) - ) - && - GameUIManager.getImageLoader().getZoomFactor(zoomStep-1) != GameUIManager.getImageLoader().getZoomFactor(zoomStep) - ) - zoomStep--; - //trigger zoom execution + public void setZoomStep (int zoomStep) { + this.zoomStep = zoomStep; zoom(); } + public int getZoomStep () { + return zoomStep; + } + private void zoom() { zoomFactor = GameUIManager.getImageLoader().getZoomFactor(zoomStep); log.debug("HexMap: zoomStep = "+ zoomStep); @@ -614,10 +586,6 @@ public abstract class HexMap implements MouseListener, scale = (Scale.get() * zoomFactor); } - public int getZoomStep () { - return zoomStep; - } - public Dimension getOriginalSize() { return originalSize; } |
From: Frederick W. <fre...@us...> - 2012-01-10 22:29:25
|
rails/ui/swing/ImageLoader.java | 3 +++ rails/ui/swing/MapPanel.java | 3 +++ rails/ui/swing/ORPanel.java | 7 +------ 3 files changed, 7 insertions(+), 6 deletions(-) New commits: commit 1f0b89df9bde415058747b361b366dec5fe6202c Author: Frederick Weld <fre...@gm...> Date: Tue Jan 10 23:25:06 2012 +0100 Fixed resize issues: tiles (adjustment zoom), routes (fit zoom) There is a buffer for tile scalings - it is now invalidated whenever the adjustmentZoomFactor is changed. (This tile buffer is the reason why maintaining zoom steps made sense in the past.) In addition, redrawal of routes is now also triggered upon auto-resize diff --git a/rails/ui/swing/ImageLoader.java b/rails/ui/swing/ImageLoader.java index f663639..fd64570 100644 --- a/rails/ui/swing/ImageLoader.java +++ b/rails/ui/swing/ImageLoader.java @@ -149,6 +149,9 @@ public class ImageLoader { for (int i = 0 ; i < zoomFactors.length ; i++) { zoomFactors[i] = 0; } + + //invalidate buffered tile scalings + if (tileMap != null) tileMap.clear(); } public void resetAdjustmentFactor() { diff --git a/rails/ui/swing/MapPanel.java b/rails/ui/swing/MapPanel.java index 23e4a24..66c81d6 100644 --- a/rails/ui/swing/MapPanel.java +++ b/rails/ui/swing/MapPanel.java @@ -138,6 +138,9 @@ public class MapPanel extends JPanel { if (mapImage != null) { mapImage.setBoundsAndResize(currentMapSize,map.getZoomStep()); } + //access from map panel to or panel not nice but currently necessary for route drawing + if (gameUIManager.getORUIManager() != null && gameUIManager.getORUIManager().getORPanel() != null) + gameUIManager.getORUIManager().getORPanel().redrawRoutes(); layeredPane.revalidate(); } diff --git a/rails/ui/swing/ORPanel.java b/rails/ui/swing/ORPanel.java index 959d644..aeb19e7 100644 --- a/rails/ui/swing/ORPanel.java +++ b/rails/ui/swing/ORPanel.java @@ -790,7 +790,7 @@ implements ActionListener, KeyListener, RevenueListener { disableRoutesDisplay(); } - private void redrawRoutes() { + public void redrawRoutes() { if (revenueAdapter != null && isDisplayRoutes()) { revenueAdapter.drawOptimalRunAsPath(orUIManager.getMap()); } @@ -827,19 +827,16 @@ implements ActionListener, KeyListener, RevenueListener { fitToWidth.setSelected(false); fitToHeight.setSelected(false); orWindow.getMapPanel().zoom(true); - redrawRoutes(); } else if (source == zoomOut) { fitToWindow.setSelected(false); fitToWidth.setSelected(false); fitToHeight.setSelected(false); orWindow.getMapPanel().zoom(false); - redrawRoutes(); } else if (source == fitToWindow) { if (fitToWindow.isSelected()) { fitToWidth.setSelected(false); fitToHeight.setSelected(false); orWindow.getMapPanel().fitToWindow(); - redrawRoutes(); } else { orWindow.getMapPanel().removeFitToOption(); } @@ -848,7 +845,6 @@ implements ActionListener, KeyListener, RevenueListener { fitToWindow.setSelected(false); fitToHeight.setSelected(false); orWindow.getMapPanel().fitToWidth(); - redrawRoutes(); } else { orWindow.getMapPanel().removeFitToOption(); } @@ -857,7 +853,6 @@ implements ActionListener, KeyListener, RevenueListener { fitToWindow.setSelected(false); fitToWidth.setSelected(false); orWindow.getMapPanel().fitToHeight(); - redrawRoutes(); } else { orWindow.getMapPanel().removeFitToOption(); } |
From: Erik V. <ev...@us...> - 2012-01-12 15:07:15
|
rails/ui/swing/GameStatus.java | 1 rails/ui/swing/ORPanel.java | 193 ++++---- rails/ui/swing/ORUIManager.java | 325 +++++++------- rails/ui/swing/StartRoundWindow.java | 7 rails/ui/swing/StatusWindow.java | 86 +-- rails/ui/swing/gamespecific/_1835/StatusWindow_1835.java | 25 - rails/ui/swing/gamespecific/_1856/StatusWindow_1856.java | 18 rails/ui/swing/gamespecific/_18EU/GameStatus_18EU.java | 8 rails/ui/swing/gamespecific/_18EU/GameUIManager_18EU.java | 110 ++-- 9 files changed, 397 insertions(+), 376 deletions(-) New commits: commit 80327b9fd861613e417dbdbe76aec32703ec16cf Author: Erik Vos <eri...@xs...> Date: Thu Jan 12 16:05:58 2012 +0100 Disable buttons on non-modal popups. diff --git a/rails/ui/swing/GameStatus.java b/rails/ui/swing/GameStatus.java index bab6fb0..6cc5c2e 100644 --- a/rails/ui/swing/GameStatus.java +++ b/rails/ui/swing/GameStatus.java @@ -746,6 +746,7 @@ public class GameStatus extends GridPanel implements ActionListener { companyName), options.toArray(new String[0]), -1); gameUIManager.setCurrentDialog(dialog, actions.get(0)); + parent.disableButtons(); return; } else { String sp = diff --git a/rails/ui/swing/ORPanel.java b/rails/ui/swing/ORPanel.java index e8f8254..b2251c3 100644 --- a/rails/ui/swing/ORPanel.java +++ b/rails/ui/swing/ORPanel.java @@ -9,7 +9,6 @@ import java.util.List; import javax.swing.*; import org.apache.log4j.Logger; - import org.jgrapht.graph.SimpleGraph; import rails.algorithms.*; @@ -61,7 +60,7 @@ implements ActionListener, KeyListener, RevenueListener { private JMenuItem zoomIn, zoomOut, fitToWindow, fitToWidth, fitToHeight, calibrateMap; private ActionMenuItem takeLoans; private ActionMenuItem repayLoans; - + // Grid elements per function private Caption leftCompName[]; private int leftCompNameXOffset, leftCompNameYOffset; @@ -102,7 +101,7 @@ implements ActionListener, KeyListener, RevenueListener { private boolean hasRights; private Caption tileCaption, tokenCaption, revenueCaption, trainCaption, - privatesCaption, loansCaption; + privatesCaption, loansCaption; private ActionButton buttonOC; // sfy: button for operating costs private ActionButton button1; @@ -116,13 +115,13 @@ implements ActionListener, KeyListener, RevenueListener { private int orCompIndex = -1; private PublicCompanyI orComp = null; - + private boolean isRevenueValueToBeSet = false; private RevenueAdapter revenueAdapter = null; private Thread revenueThread = null; protected static Logger log = - Logger.getLogger(ORPanel.class.getPackage().getName()); + Logger.getLogger(ORPanel.class.getPackage().getName()); public ORPanel(ORWindow parent, ORUIManager orUIManager) { super(); @@ -141,7 +140,7 @@ implements ActionListener, KeyListener, RevenueListener { parentFrame = parent; round = gameUIManager.getCurrentRound(); -// noMapMode = gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.NO_MAP_MODE); + // noMapMode = gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.NO_MAP_MODE); privatesCanBeBought = gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.CAN_ANY_COMPANY_BUY_PRIVATES); bonusTokensExist = gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.DO_BONUS_TOKENS_EXIST); hasCompanyLoans = gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.HAS_ANY_COMPANY_LOANS); @@ -168,7 +167,7 @@ implements ActionListener, KeyListener, RevenueListener { infoMenu = new JMenu(LocalText.getText("Info")); infoMenu.setEnabled(true); remainingTilesMenuItem = - new JMenuItem(LocalText.getText("RemainingTiles")); + new JMenuItem(LocalText.getText("RemainingTiles")); remainingTilesMenuItem.addActionListener(this); remainingTilesMenuItem.setActionCommand(REM_TILES_CMD); infoMenu.add(remainingTilesMenuItem); @@ -240,14 +239,14 @@ implements ActionListener, KeyListener, RevenueListener { JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(name); menuItem.addActionListener(this); menuItem.setEnabled(true); - + //check whether this is the default fit to option if (name.equalsIgnoreCase(Config.get("map.defaultZoomFitOption"))) { menuItem.setSelected(true); } return menuItem; } - + public void recreate(OperatingRound or) { log.debug("ORPanel.recreate() called"); @@ -260,11 +259,11 @@ implements ActionListener, KeyListener, RevenueListener { // Create new fields initFields(); - + // update the networkInfo menu // TODO: This relies on a recreate as soon as companies have changed addNetworkInfo(); - + repaint(); } @@ -333,7 +332,7 @@ implements ActionListener, KeyListener, RevenueListener { public void mouseReleased(MouseEvent e) {} }; } - + private void initFields() { leftCompName = new Caption[nc]; rightCompName = new Caption[nc]; @@ -360,7 +359,7 @@ implements ActionListener, KeyListener, RevenueListener { leftCompNameYOffset = 2; int currentXOffset = leftCompNameXOffset; int lastXWidth = 0; - + MouseListener companyCaptionMouseClickListener = getCompanyCaptionMouseClickListener(); /* Top titles */ @@ -399,7 +398,7 @@ implements ActionListener, KeyListener, RevenueListener { addField (loansCaption = new Caption(LocalText.getText("LOANS")), loansXOffset, 0, lastXWidth = 1, 2, WIDE_RIGHT); } - + if (hasRights) { rightsXOffset = currentXOffset += lastXWidth; rightsYOffset = leftCompNameYOffset; @@ -413,7 +412,7 @@ implements ActionListener, KeyListener, RevenueListener { lastXWidth = 2, 1, WIDE_RIGHT); addField(new Caption("laid"), tilesXOffset, 1, 1, 1, WIDE_BOTTOM); addField(new Caption("cost"), tilesXOffset + 1, 1, 1, 1, WIDE_BOTTOM - + WIDE_RIGHT); + + WIDE_RIGHT); tokensXOffset = currentXOffset += lastXWidth; tokensYOffset = leftCompNameYOffset; @@ -435,7 +434,7 @@ implements ActionListener, KeyListener, RevenueListener { lastXWidth = 2, 1, WIDE_RIGHT); addField(new Caption("earned"), revXOffset, 1, 1, 1, WIDE_BOTTOM); addField(new Caption("payout"), revXOffset + 1, 1, 1, 1, WIDE_BOTTOM - + WIDE_RIGHT); + + WIDE_RIGHT); trainsXOffset = currentXOffset += lastXWidth; trainsYOffset = leftCompNameYOffset; @@ -443,7 +442,7 @@ implements ActionListener, KeyListener, RevenueListener { lastXWidth = 2, 1, WIDE_RIGHT); addField(new Caption("owned"), trainsXOffset, 1, 1, 1, WIDE_BOTTOM); addField(new Caption("cost"), trainsXOffset + 1, 1, 1, 1, WIDE_BOTTOM - + WIDE_RIGHT); + + WIDE_RIGHT); rightCompNameXOffset = currentXOffset += lastXWidth; rightCompNameYOffset = leftCompNameYOffset; @@ -456,7 +455,7 @@ implements ActionListener, KeyListener, RevenueListener { for (int i = 0; i < nc; i++) { c = companies[i]; rowVisibilityObservers[i] - = new RowVisibility (this, leftCompNameYOffset + i, c.getInGameModel(), true); + = new RowVisibility (this, leftCompNameYOffset + i, c.getInGameModel(), true); observers.add(rowVisibilityObservers[i]); boolean visible = !c.isClosed(); @@ -465,17 +464,17 @@ implements ActionListener, KeyListener, RevenueListener { f.setBackground(c.getBgColour()); f.setForeground(c.getFgColour()); HexHighlightMouseListener.addMouseListener(f, - orUIManager,(PublicCompanyI)c,false); + orUIManager,c,false); f.addMouseListener(companyCaptionMouseClickListener); f.setToolTipText(LocalText.getText("NetworkInfoDialogTitle",c.getName())); addField(f, leftCompNameXOffset, leftCompNameYOffset + i, 1, 1, WIDE_RIGHT, visible); f = - president[i] = -// new Field(c.hasStarted() && !c.isClosed() -// ? c.getPresident().getNameAndPriority() : ""); - new Field(c.getPresidentModel()); + president[i] = + // new Field(c.hasStarted() && !c.isClosed() + // ? c.getPresident().getNameAndPriority() : ""); + new Field(c.getPresidentModel()); addField(f, presidentXOffset, presidentYOffset + i, 1, 1, 0, visible); f = sharePrice[i] = new Field(c.getCurrentPriceModel()); @@ -486,17 +485,17 @@ implements ActionListener, KeyListener, RevenueListener { if (privatesCanBeBought) { f = - privates[i] = - new Field( - c.getPortfolio().getPrivatesOwnedModel()); + privates[i] = + new Field( + c.getPortfolio().getPrivatesOwnedModel()); HexHighlightMouseListener.addMouseListener(f, orUIManager,c.getPortfolio()); addField(f, privatesXOffset, privatesYOffset + i, 1, 1, WIDE_RIGHT, visible); f = - newPrivatesCost[i] = - new Field(c.getPrivatesSpentThisTurnModel()); + newPrivatesCost[i] = + new Field(c.getPrivatesSpentThisTurnModel()); addField(f, privatesXOffset + 1, privatesYOffset + i, 1, 1, WIDE_RIGHT, visible); } @@ -510,7 +509,7 @@ implements ActionListener, KeyListener, RevenueListener { } addField (f, loansXOffset, loansYOffset + i, 1, 1, WIDE_RIGHT, visible); } - + if (hasRights) { f = rights[i] = new Field (c.getRightsModel()); addField (f, rightsXOffset, rightsYOffset + i, 1, 1, WIDE_RIGHT, visible); @@ -560,7 +559,7 @@ implements ActionListener, KeyListener, RevenueListener { f.setBackground(companies[i].getBgColour()); f.setForeground(companies[i].getFgColour()); HexHighlightMouseListener.addMouseListener(f, - orUIManager,(PublicCompanyI)c,false); + orUIManager,c,false); f.addMouseListener(companyCaptionMouseClickListener); f.setToolTipText(LocalText.getText("NetworkInfoDialogTitle",c.getName())); addField(f, rightCompNameXOffset, rightCompNameYOffset + i, 1, 1, 0, visible); @@ -571,30 +570,30 @@ implements ActionListener, KeyListener, RevenueListener { protected void addCompanyInfo() { - CompanyManagerI cm = orUIManager.getGameUIManager().getGameManager().getCompanyManager(); - List<CompanyTypeI> comps = cm.getCompanyTypes(); - JMenu compMenu, menu, item; + CompanyManagerI cm = orUIManager.getGameUIManager().getGameManager().getCompanyManager(); + List<CompanyTypeI> comps = cm.getCompanyTypes(); + JMenu compMenu, menu, item; compMenu = new JMenu(LocalText.getText("Companies")); compMenu.setEnabled(true); infoMenu.add(compMenu); - for (CompanyTypeI type : comps) { - menu = new JMenu (LocalText.getText(type.getName())); - menu.setEnabled(true); + for (CompanyTypeI type : comps) { + menu = new JMenu (LocalText.getText(type.getName())); + menu.setEnabled(true); compMenu.add(menu); - for (CompanyI comp : type.getCompanies()) { - item = new JMenu(comp.getName()); - item.setEnabled(true); - JMenuItem menuItem = new JMenuItem(comp.getInfoText()); - if (comp instanceof PrivateCompanyI) { - //highlighting on menu items always enabled irrespective of config + for (CompanyI comp : type.getCompanies()) { + item = new JMenu(comp.getName()); + item.setEnabled(true); + JMenuItem menuItem = new JMenuItem(comp.getInfoText()); + if (comp instanceof PrivateCompanyI) { + //highlighting on menu items always enabled irrespective of config HexHighlightMouseListener.addMouseListener(menuItem, orUIManager,(PrivateCompanyI)comp,true); HexHighlightMouseListener.addMouseListener(item, orUIManager,(PrivateCompanyI)comp,true); - } + } if (comp instanceof PublicCompanyI) { //highlighting on menu items always enabled irrespective of config HexHighlightMouseListener.addMouseListener(menuItem, @@ -603,9 +602,9 @@ implements ActionListener, KeyListener, RevenueListener { orUIManager,(PublicCompanyI)comp,true); } item.add(menuItem); - menu.add(item); - } - } + menu.add(item); + } + } } protected void addTrainsInfo() { @@ -670,16 +669,16 @@ implements ActionListener, KeyListener, RevenueListener { networkInfoMenu.setEnabled(true); infoMenu.add(networkInfoMenu); } - + protected JMenu createNetworkInfo() { boolean route_highlight = orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.ROUTE_HIGHLIGHT); - boolean revenue_suggest = orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.REVENUE_SUGGEST); - - if (!route_highlight && !revenue_suggest) return null; - + boolean revenue_suggest = orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.REVENUE_SUGGEST); + + if (!route_highlight && !revenue_suggest) return null; + JMenu networkMenu = new JMenu(LocalText.getText("NetworkInfo")); - + //network graphs only for developers if (route_highlight && Game.getDevelop()) { JMenuItem item = new JMenuItem("Network"); @@ -687,7 +686,7 @@ implements ActionListener, KeyListener, RevenueListener { item.setActionCommand(NETWORK_INFO_CMD); networkMenu.add(item); } - + if (revenue_suggest) { CompanyManagerI cm = orUIManager.getGameUIManager().getGameManager().getCompanyManager(); for (PublicCompanyI comp : cm.getAllPublicCompanies()) { @@ -698,35 +697,35 @@ implements ActionListener, KeyListener, RevenueListener { networkMenu.add(item); } } - + return networkMenu; } - + protected void executeNetworkInfo(String companyName) { GameManagerI gm = orUIManager.getGameUIManager().getGameManager(); - + if (companyName.equals("Network")) { NetworkGraphBuilder nwGraph = NetworkGraphBuilder.create(gm); SimpleGraph<NetworkVertex, NetworkEdge> mapGraph = nwGraph.getMapGraph(); - -// NetworkGraphBuilder.visualize(mapGraph, "Map Network"); + + // NetworkGraphBuilder.visualize(mapGraph, "Map Network"); mapGraph = NetworkGraphBuilder.optimizeGraph(mapGraph); NetworkGraphBuilder.visualize(mapGraph, "Optimized Map Network"); } else { CompanyManagerI cm = gm.getCompanyManager(); PublicCompanyI company = cm.getPublicCompany(companyName); //handle the case of invalid parameters - //could occur if the method is not invoked by the menu (but by the click listener) + //could occur if the method is not invoked by the menu (but by the click listener) if (company == null) return; -// -// NetworkGraphBuilder nwGraph = NetworkGraphBuilder.create(gm); -// NetworkCompanyGraph companyGraph = NetworkCompanyGraph.create(nwGraph, company); -// companyGraph.createRouteGraph(false); -// companyGraph.createRevenueGraph(new ArrayList<NetworkVertex>()); -// Multigraph<NetworkVertex, NetworkEdge> graph= companyGraph.createPhaseTwoGraph(); -// NetworkGraphBuilder.visualize(graph, "Phase Two Company Network"); -// JOptionPane.showMessageDialog(orWindow, -// "Vertices = " + graph.vertexSet().size() + ", Edges = " + graph.edgeSet().size()); + // + // NetworkGraphBuilder nwGraph = NetworkGraphBuilder.create(gm); + // NetworkCompanyGraph companyGraph = NetworkCompanyGraph.create(nwGraph, company); + // companyGraph.createRouteGraph(false); + // companyGraph.createRevenueGraph(new ArrayList<NetworkVertex>()); + // Multigraph<NetworkVertex, NetworkEdge> graph= companyGraph.createPhaseTwoGraph(); + // NetworkGraphBuilder.visualize(graph, "Phase Two Company Network"); + // JOptionPane.showMessageDialog(orWindow, + // "Vertices = " + graph.vertexSet().size() + ", Edges = " + graph.edgeSet().size()); List<String> addTrainList = new ArrayList<String>(); boolean anotherTrain = true; RevenueAdapter ra = null; @@ -742,24 +741,24 @@ implements ActionListener, KeyListener, RevenueListener { log.debug("Revenue Value:" + revenueValue); log.debug("Revenue Run:" + ra.getOptimalRunPrettyPrint(true)); ra.drawOptimalRunAsPath(orUIManager.getMap()); - + if (!Game.getDevelop()) { //parent component is ORPanel so that dialog won't hide the routes painted on the map - JOptionPane.showMessageDialog(this, + JOptionPane.showMessageDialog(this, LocalText.getText("NetworkInfoDialogMessage",company.getName(),Bank.format(revenueValue)) , LocalText.getText("NetworkInfoDialogTitle",company.getName()), JOptionPane.INFORMATION_MESSAGE); //train simulation only for developers break; } - + JOptionPane.showMessageDialog(orWindow, "RevenueValue = " + revenueValue + "\nRevenueRun = \n" + ra.getOptimalRunPrettyPrint(true)); - + String trainString = JOptionPane.showInputDialog(null, "Enter train string (Examples: 5, 3+3, 4D, 6E, D)", - "Add another train to run?", - JOptionPane.QUESTION_MESSAGE); + "Add another train to run?", + JOptionPane.QUESTION_MESSAGE); if (trainString == null || trainString.equals("")) { anotherTrain = false; } else { @@ -773,7 +772,7 @@ implements ActionListener, KeyListener, RevenueListener { if (revenueAdapter != null) revenueAdapter.drawOptimalRunAsPath(orUIManager.getMap()); } } - + private void appendInfoText (StringBuffer b, String text) { if (text == null || text.length() == 0) return; if (b.length() > 6) b.append("<br>"); @@ -797,7 +796,7 @@ implements ActionListener, KeyListener, RevenueListener { revenueAdapter.drawOptimalRunAsPath(orUIManager.getMap()); } } - + public void actionPerformed(ActionEvent actor) { // What kind action has been taken? @@ -904,7 +903,7 @@ implements ActionListener, KeyListener, RevenueListener { if (hasCompanyLoans) { loansCaption.setHighlight(false); } - + for (JMenuItem item : menuItemsToReset) { item.setEnabled(false); if (item instanceof ActionMenuItem) { @@ -912,7 +911,7 @@ implements ActionListener, KeyListener, RevenueListener { } } undoButton.setEnabled(false); - + } public void resetORCompanyTurn(int orCompIndex) { @@ -925,7 +924,7 @@ implements ActionListener, KeyListener, RevenueListener { public void resetCurrentRevenueDisplay() { setSelect(revenue[orCompIndex], revenueSelect[orCompIndex], false); } - + /** * * @return True if route should be displayed (at least for the set revenue step) @@ -933,11 +932,11 @@ implements ActionListener, KeyListener, RevenueListener { private boolean isDisplayRoutes() { return (orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.ROUTE_HIGHLIGHT)); } - + private boolean isSuggestRevenue() { return (orUIManager.gameUIManager.getGameParameterAsBoolean(GuiDef.Parm.REVENUE_SUGGEST)); } - + /** * * @return True if the routes of the currently active company should be displayed. @@ -947,7 +946,7 @@ implements ActionListener, KeyListener, RevenueListener { return (isDisplayRoutes() && "yes".equalsIgnoreCase(Config.get("map.displayCurrentRoutes"))); } - + /** * any routes currently displayed on the map are removed * In addition, revenue adapter and its thread are interrupted / removed. @@ -956,7 +955,7 @@ implements ActionListener, KeyListener, RevenueListener { clearRevenueAdapter(); orUIManager.getMap().setTrainPaths(null); } - + private void clearRevenueAdapter() { if (revenueThread != null) { revenueThread.interrupt(); @@ -967,9 +966,9 @@ implements ActionListener, KeyListener, RevenueListener { revenueAdapter = null; } } - + private void updateCurrentRoutes(boolean isSetRevenueStep) { - + // initialize and start the revenue adapter if routes to be displayed // or revenue to be suggested in the revenue step if (isDisplayCurrentRoutes() || (isSuggestRevenue() && isSetRevenueStep)) { @@ -993,7 +992,7 @@ implements ActionListener, KeyListener, RevenueListener { } } - + public void initORCompanyTurn(PublicCompanyI orComp, int orCompIndex) { this.orComp = orComp; @@ -1009,7 +1008,7 @@ implements ActionListener, KeyListener, RevenueListener { button1.setEnabled(false); button2.setEnabled(false); button3.setEnabled(false); - + updateCurrentRoutes(false); } @@ -1018,7 +1017,7 @@ implements ActionListener, KeyListener, RevenueListener { tileCaption.setHighlight(true); button1.setVisible(false); - + } public void initTokenLayingStep() { @@ -1034,7 +1033,7 @@ implements ActionListener, KeyListener, RevenueListener { revenueCaption.setHighlight(true); revenueSelect[orCompIndex].setValue(action.getPresetRevenue()); - + setSelect(revenue[orCompIndex], revenueSelect[orCompIndex], true); button1.setText(LocalText.getText("SET_REVENUE")); @@ -1043,7 +1042,7 @@ implements ActionListener, KeyListener, RevenueListener { button1.setMnemonic(KeyEvent.VK_R); button1.setEnabled(true); button1.setVisible(true); - + //indicate interest in setting revenue values (and not only displaying routes) updateCurrentRoutes(true); } @@ -1062,12 +1061,12 @@ implements ActionListener, KeyListener, RevenueListener { } } } - + public void stopRevenueUpdate() { isRevenueValueToBeSet = false; } - - + + public void initPayoutStep(int orCompIndex, SetDividend action, boolean withhold, boolean split, boolean payout) { @@ -1207,6 +1206,14 @@ implements ActionListener, KeyListener, RevenueListener { button1.setVisible(true); } + public void disableButtons () { + button1.setEnabled(false); + button2.setEnabled(false); + button3.setEnabled(false); + undoButton.setEnabled(false); + redoButton.setEnabled(false); + } + public void finishORCompanyTurn(int orCompIndex) { for (Field field : president) { diff --git a/rails/ui/swing/ORUIManager.java b/rails/ui/swing/ORUIManager.java index 40da760..a097bf7 100644 --- a/rails/ui/swing/ORUIManager.java +++ b/rails/ui/swing/ORUIManager.java @@ -20,7 +20,7 @@ import rails.game.special.*; import rails.ui.swing.elements.*; import rails.ui.swing.hexmap.GUIHex; import rails.ui.swing.hexmap.HexMap; -import rails.util.*; +import rails.util.Util; public class ORUIManager implements DialogOwner { @@ -46,7 +46,7 @@ public class ORUIManager implements DialogOwner { protected PossibleActions possibleActions = PossibleActions.getInstance(); private boolean privatesCanBeBoughtNow; public List<PossibleAction> mapRelatedActions = - new ArrayList<PossibleAction>(); + new ArrayList<PossibleAction>(); private boolean tileLayingEnabled = false; public List<LayTile> allowedTileLays = new ArrayList<LayTile>(); @@ -84,13 +84,13 @@ public class ORUIManager implements DialogOwner { /* Message key per substep */ protected static final String[] messageKey = - new String[] { "Inactive", "SelectAHexForTile", "SelectATile", - "RotateTile", "SelectAHexForToken", "SelectAToken", - "ConfirmToken", "SetRevenue", "SelectPayout", - "CorrectMap" }; + new String[] { "Inactive", "SelectAHexForTile", "SelectATile", + "RotateTile", "SelectAHexForToken", "SelectAToken", + "ConfirmToken", "SetRevenue", "SelectPayout", + "CorrectMap" }; protected static Logger log = - Logger.getLogger(ORUIManager.class.getPackage().getName()); + Logger.getLogger(ORUIManager.class.getPackage().getName()); public ORUIManager() { @@ -296,9 +296,9 @@ public class ORUIManager implements DialogOwner { // For now, this only has an effect during tile and token laying. // Perhaps we need to centralise message updating here in a later stage. log.debug("Calling updateMessage, subStep=" + localStep/* - * , new - * Exception("TRACE") - */); + * , new + * Exception("TRACE") + */); if (localStep == ORUIManager.INACTIVE) return; String message = LocalText.getText(ORUIManager.messageKey[localStep]); @@ -349,9 +349,9 @@ public class ORUIManager implements DialogOwner { } if (normalTileMessage.length() > 1) { message += - " " - + LocalText.getText("TileColours", - normalTileMessage); + " " + + LocalText.getText("TileColours", + normalTileMessage); } } else if (localStep == ORUIManager.SELECT_HEX_FOR_TOKEN) { @@ -361,7 +361,7 @@ public class ORUIManager implements DialogOwner { StringBuffer normalTokenMessage = new StringBuffer(" "); List<LayBaseToken> tokenLays = - possibleActions.getType(LayBaseToken.class); + possibleActions.getType(LayBaseToken.class); log.debug("There are " + tokenLays.size() + " TokenLay objects"); int ii = 0; for (LayBaseToken tokenLay : tokenLays) { @@ -380,7 +380,7 @@ public class ORUIManager implements DialogOwner { } if (normalTokenMessage.length() > 1) { message += " " + LocalText.getText("NormalToken", - normalTokenMessage); + normalTokenMessage); } } if (extraMessage.length() > 0) { @@ -400,10 +400,10 @@ public class ORUIManager implements DialogOwner { public void processAction(String command, List<PossibleAction> actions) { if (actions != null && actions.size() > 0 - && !processGameSpecificActions(actions)) { + && !processGameSpecificActions(actions)) { Class<? extends PossibleAction> actionType = - actions.get(0).getClass(); + actions.get(0).getClass(); if (actionType == SetDividend.class) { @@ -426,7 +426,7 @@ public class ORUIManager implements DialogOwner { buyBonusToken ((BuyBonusToken)actions.get(0)); } else if (actionType == NullAction.class - || actionType == GameAction.class ) { + || actionType == GameAction.class ) { orWindow.process(actions.get(0)); @@ -495,7 +495,7 @@ public class ORUIManager implements DialogOwner { action.setActualRevenue(amount); if (amount == 0 || action.getRevenueAllocation() != SetDividend.UNKNOWN) { log.debug("Allocation is known: " - + action.getRevenueAllocation()); + + action.getRevenueAllocation()); orWindow.process(action); } else { log.debug("Allocation is unknown, asking for it"); @@ -597,6 +597,7 @@ public class ORUIManager implements DialogOwner { public void setCurrentDialog (JDialog dialog, PossibleAction action) { gameUIManager.setCurrentDialog(dialog, action); + if (!(dialog instanceof MessageDialog)) orPanel.disableButtons(); } public void hexClicked(GUIHex clickedHex, GUIHex selectedHex) { @@ -628,10 +629,10 @@ public class ORUIManager implements DialogOwner { return; } List<LayToken> allowances = - map.getTokenAllowanceForHex(clickedHex.getHexModel()); + map.getTokenAllowanceForHex(clickedHex.getHexModel()); if (allowances.size() > 0) { log.debug("Hex " + clickedHex.getName() - + " clicked, allowances:"); + + " clicked, allowances:"); for (LayToken allowance : allowances) { log.debug(allowance.toString()); } @@ -645,7 +646,7 @@ public class ORUIManager implements DialogOwner { } else if (tileLayingEnabled) { if (localStep == ROTATE_OR_CONFIRM_TILE - && clickedHex == selectedHex) { + && clickedHex == selectedHex) { selectedHex.rotateTile(); return; @@ -660,16 +661,16 @@ public class ORUIManager implements DialogOwner { setLocalStep(SELECT_HEX_FOR_TILE); } else { if (clickedHex.getHexModel().isUpgradeableNow()) - /* - * Direct call to Model to be replaced later by use of - * allowedTilesPerHex. Would not work yet. - */ + /* + * Direct call to Model to be replaced later by use of + * allowedTilesPerHex. Would not work yet. + */ { map.selectHex(clickedHex); setLocalStep(SELECT_TILE); } else { JOptionPane.showMessageDialog(mapPanel, - "This hex cannot be upgraded now"); + "This hex cannot be upgraded now"); } } } @@ -695,11 +696,11 @@ public class ORUIManager implements DialogOwner { // Check if the new tile must be connected to some other track boolean mustConnect = - tile.getColourName().equalsIgnoreCase(Tile.YELLOW_COLOUR_NAME) - // Does not apply to the current company's home hex(es) - && !hex.getHexModel().isHomeFor(orComp) - // Does not apply to special tile lays - && !isUnconnectedTileLayTarget(hex); + tile.getColourName().equalsIgnoreCase(Tile.YELLOW_COLOUR_NAME) + // Does not apply to the current company's home hex(es) + && !hex.getHexModel().isHomeFor(orComp) + // Does not apply to special tile lays + && !isUnconnectedTileLayTarget(hex); if (hex.dropTile(tileId, mustConnect)) { /* Lay tile */ @@ -707,7 +708,7 @@ public class ORUIManager implements DialogOwner { } else { /* Tile cannot be laid in a valid orientation: refuse it */ JOptionPane.showMessageDialog(mapPanel, - "This tile cannot be laid in a valid orientation."); + "This tile cannot be laid in a valid orientation."); tileUpgrades.remove(tile); setLocalStep(ORUIManager.SELECT_TILE); upgradePanel.showUpgrades(); @@ -719,7 +720,7 @@ public class ORUIManager implements DialogOwner { MapHex mapHex = hex.getHexModel(); for (LayTile action : possibleActions.getType(LayTile.class)) { if (action.getType() == LayTile.SPECIAL_PROPERTY - && action.getSpecialProperty().getLocations().contains(mapHex)) { + && action.getSpecialProperty().getLocations().contains(mapHex)) { // log.debug(hex.getName()+" is a special property target"); return true; } @@ -746,7 +747,7 @@ public class ORUIManager implements DialogOwner { if (selectedHex != null && selectedHex.canFixTile()) { List<LayTile> allowances = - map.getTileAllowancesForHex(selectedHex.getHexModel()); + map.getTileAllowancesForHex(selectedHex.getHexModel()); LayTile allowance = null; TileI tile = selectedHex.getProvisionalTile(); if (allowances.size() == 1) { @@ -769,7 +770,7 @@ public class ORUIManager implements DialogOwner { && !sp_tiles.contains(tile)) continue; // 2. SP refers to specified hexes, (one of) which is chosen: // (example: 1830 hex B20) - if ((sp_hexes = lt.getLocations()) != null + if ((sp_hexes = lt.getLocations()) != null && !sp_hexes.contains(selectedHex.getModel())) continue; spec_lt = lt; } else { @@ -777,12 +778,12 @@ public class ORUIManager implements DialogOwner { gen_lt = lt; } } - + allowance = spec_lt == null ? gen_lt : - gen_lt == null ? spec_lt : - spec_lt.getSpecialProperty().getPriority() - == SpecialPropertyI.Priority.FIRST ? spec_lt : gen_lt; - + gen_lt == null ? spec_lt : + spec_lt.getSpecialProperty().getPriority() + == SpecialPropertyI.Priority.FIRST ? spec_lt : gen_lt; + } allowance.setChosenHex(selectedHex.getHexModel()); allowance.setOrientation(selectedHex.getProvisionalTileRotation()); @@ -835,11 +836,11 @@ public class ORUIManager implements DialogOwner { if (city.hasTokenSlotsLeft()) { prompt = LocalText.getText( "SelectStationForTokenOption", - city.getNumber(), - ((MapHex) selectedHex.getModel()).getConnectionString( - selectedHex.getCurrentTile(), - ((MapHex) selectedHex.getModel()).getCurrentTileRotation(), - city.getRelatedStation().getNumber())) ; + city.getNumber(), + ((MapHex) selectedHex.getModel()).getConnectionString( + selectedHex.getCurrentTile(), + ((MapHex) selectedHex.getModel()).getCurrentTileRotation(), + city.getRelatedStation().getNumber())) ; prompts.add(prompt); promptToCityMap.put(prompt, city); } @@ -847,17 +848,17 @@ public class ORUIManager implements DialogOwner { if (prompts.isEmpty()) { return; } - // If more than one City to choose from, ask the player. Otherwise use Element zero (first) for the station. + // If more than one City to choose from, ask the player. Otherwise use Element zero (first) for the station. if (prompts.size() > 1) { String selected = - (String) JOptionPane.showInputDialog(orWindow, - LocalText.getText("SelectStationForToken", - action.getPlayerName(), - selectedHex.getName(), - action.getCompanyName()), - LocalText.getText("WhichStation"), - JOptionPane.PLAIN_MESSAGE, null, - prompts.toArray(), prompts.get(0)); + (String) JOptionPane.showInputDialog(orWindow, + LocalText.getText("SelectStationForToken", + action.getPlayerName(), + selectedHex.getName(), + action.getCompanyName()), + LocalText.getText("WhichStation"), + JOptionPane.PLAIN_MESSAGE, null, + prompts.toArray(), prompts.get(0)); if (selected == null) return; station = promptToCityMap.get(selected).getNumber(); } else { @@ -891,7 +892,7 @@ public class ORUIManager implements DialogOwner { MapHex hex = action.getChosenHex(); TileI newTile = action.getLaidTile(); TileI oldTile = hex.getCurrentTile(); - if (!action.isRelayBaseTokens() + if (!action.isRelayBaseTokens() && !oldTile.relayBaseTokensOnUpgrade()) return; for (Stop oldStop : hex.getStops()) { if (oldStop.hasTokens()) { @@ -906,9 +907,9 @@ public class ORUIManager implements DialogOwner { prompt = LocalText.getText("SelectStationForTokenOption", newStation.getNumber(), hex.getConnectionString( - newTile, - action.getOrientation(), - newStation.getNumber()) ); + newTile, + action.getOrientation(), + newStation.getNumber()) ); prompts.add(prompt); promptToCityMap.put(prompt, newStation.getNumber()); } @@ -918,21 +919,21 @@ public class ORUIManager implements DialogOwner { } if (prompts.size () > 1) { String selected = - (String) JOptionPane.showInputDialog(orWindow, - LocalText.getText("SelectStationForToken", - action.getPlayerName(), - hex.getName(), - company.getName() - ), - LocalText.getText("WhichStation"), - JOptionPane.PLAIN_MESSAGE, null, - prompts.toArray(), prompts.get(0)); + (String) JOptionPane.showInputDialog(orWindow, + LocalText.getText("SelectStationForToken", + action.getPlayerName(), + hex.getName(), + company.getName() + ), + LocalText.getText("WhichStation"), + JOptionPane.PLAIN_MESSAGE, null, + prompts.toArray(), prompts.get(0)); if (selected == null) return; action.addRelayBaseToken(company.getName(), promptToCityMap.get(selected)); } else { action.addRelayBaseToken(company.getName(), promptToCityMap.get(prompts.toArray() [0])); } - } + } } } @@ -945,15 +946,15 @@ public class ORUIManager implements DialogOwner { Map<String, Station> promptToStationMap = new HashMap<String, Station>(); String prompt; for (Station station:possibleStations) { - prompt = LocalText.getText( - "SelectStationForTokenOption", - station.getNumber(), - ((MapHex) selectedHex.getModel()).getConnectionString( - selectedHex.getProvisionalTile(), - selectedHex.getProvisionalTileRotation(), - station.getNumber())) ; - prompts.add(prompt); - promptToStationMap.put(prompt, station); + prompt = LocalText.getText( + "SelectStationForTokenOption", + station.getNumber(), + ((MapHex) selectedHex.getModel()).getConnectionString( + selectedHex.getProvisionalTile(), + selectedHex.getProvisionalTileRotation(), + station.getNumber())) ; + prompts.add(prompt); + promptToStationMap.put(prompt, station); } String selected = (String) JOptionPane.showInputDialog(orWindow, @@ -1012,11 +1013,11 @@ public class ORUIManager implements DialogOwner { OperatingCost.OCType t = ac.getOCType(); if (t == OperatingCost.OCType.LAY_TILE) textOC.add(LocalText.getText("OCLayTile", - suggestedCostText )); + suggestedCostText )); if (t == OperatingCost.OCType.LAY_BASE_TOKEN) textOC.add(LocalText.getText("OCLayBaseToken", - suggestedCostText )); + suggestedCostText )); } if (!textOC.isEmpty()) { @@ -1056,7 +1057,7 @@ public class ORUIManager implements DialogOwner { List<String> prompts = new ArrayList<String>(); Map<String, PossibleAction> promptToTrain = - new HashMap<String, PossibleAction>(); + new HashMap<String, PossibleAction>(); TrainI train; String usingPrivates = ""; @@ -1082,7 +1083,7 @@ public class ORUIManager implements DialogOwner { from.getName() )); if (bTrain.isForExchange()) { b.append(" (").append(LocalText.getText("EXCHANGED")).append( - ")"); + ")"); } if (cost > 0) { b.append(" ").append( @@ -1090,7 +1091,7 @@ public class ORUIManager implements DialogOwner { } if (bTrain.hasSpecialProperty()) { String priv = - (bTrain.getSpecialProperty()).getOriginalCompany().getName(); + (bTrain.getSpecialProperty()).getOriginalCompany().getName(); b.append(" ").append(LocalText.getText("USING_SP", priv)); usingPrivates += ", " + priv; } @@ -1119,7 +1120,7 @@ public class ORUIManager implements DialogOwner { } StringBuffer msgbuf = - new StringBuffer(LocalText.getText("SelectTrain")); + new StringBuffer(LocalText.getText("SelectTrain")); if (usingPrivates.length() > 0) { msgbuf.append("<br><font color=\"red\">"); msgbuf.append(LocalText.getText("SelectCheapTrain", @@ -1129,11 +1130,11 @@ public class ORUIManager implements DialogOwner { setMessage(msgbuf.toString()); String selectedActionText = - (String) JOptionPane.showInputDialog(orWindow, - LocalText.getText("BUY_WHICH_TRAIN"), - LocalText.getText("WHICH_TRAIN"), - JOptionPane.QUESTION_MESSAGE, null, prompts.toArray(), - prompts.get(0)); + (String) JOptionPane.showInputDialog(orWindow, + LocalText.getText("BUY_WHICH_TRAIN"), + LocalText.getText("WHICH_TRAIN"), + JOptionPane.QUESTION_MESSAGE, null, prompts.toArray(), + prompts.get(0)); if (!Util.hasValue(selectedActionText)) return; selectedAction = promptToTrain.get(selectedActionText); @@ -1146,15 +1147,15 @@ public class ORUIManager implements DialogOwner { if (price == 0 && seller.getOwner() instanceof PublicCompanyI) { prompt = LocalText.getText("WHICH_TRAIN_PRICE", - orComp.getName(), - train.getName(), - seller.getName() ); + orComp.getName(), + train.getName(), + seller.getName() ); String response; for (;;) { response = - JOptionPane.showInputDialog(orWindow, prompt, - LocalText.getText("WHICH_PRICE"), - JOptionPane.QUESTION_MESSAGE); + JOptionPane.showInputDialog(orWindow, prompt, + LocalText.getText("WHICH_PRICE"), + JOptionPane.QUESTION_MESSAGE); if (response == null) return; // Cancel try { price = Integer.parseInt(response); @@ -1165,8 +1166,8 @@ public class ORUIManager implements DialogOwner { if (!prompt.startsWith("Please")) { prompt = - LocalText.getText("ENTER_PRICE_OR_CANCEL") + "\n" - + prompt; + LocalText.getText("ENTER_PRICE_OR_CANCEL") + "\n" + + prompt; } } } @@ -1178,21 +1179,21 @@ public class ORUIManager implements DialogOwner { exchangedTrain = oldTrains.get(0); } else { List<String> oldTrainOptions = - new ArrayList<String>(oldTrains.size()); + new ArrayList<String>(oldTrains.size()); String[] options = new String[oldTrains.size()]; int jj = 0; for (int j = 0; j < oldTrains.size(); j++) { options[jj + j] = - LocalText.getText("N_Train", oldTrains.get(j).getName()); + LocalText.getText("N_Train", oldTrains.get(j).getName()); oldTrainOptions.add(options[jj + j]); } String exchangedTrainName = - (String) JOptionPane.showInputDialog(orWindow, - LocalText.getText("WHICH_TRAIN_EXCHANGE_FOR", - Bank.format(price)), - LocalText.getText("WHICH_TRAIN_TO_EXCHANGE"), - JOptionPane.QUESTION_MESSAGE, null, options, - options[0]); + (String) JOptionPane.showInputDialog(orWindow, + LocalText.getText("WHICH_TRAIN_EXCHANGE_FOR", + Bank.format(price)), + LocalText.getText("WHICH_TRAIN_TO_EXCHANGE"), + JOptionPane.QUESTION_MESSAGE, null, options, + options[0]); if (exchangedTrainName != null) { int index = oldTrainOptions.indexOf(exchangedTrainName); if (index >= 0) { @@ -1209,7 +1210,7 @@ public class ORUIManager implements DialogOwner { if (train != null) { // Remember the old off-board revenue step int oldOffBoardRevenueStep = - gameUIManager.getCurrentPhase().getOffBoardRevenueStep(); + gameUIManager.getCurrentPhase().getOffBoardRevenueStep(); buyAction.setPricePaid(price); buyAction.setExchangedTrain(exchangedTrain); @@ -1231,11 +1232,11 @@ public class ORUIManager implements DialogOwner { gameUIManager.discardTrains(dt); } - */ + */ } int newOffBoardRevenueStep = - gameUIManager.getCurrentPhase().getOffBoardRevenueStep(); + gameUIManager.getCurrentPhase().getOffBoardRevenueStep(); if (newOffBoardRevenueStep != oldOffBoardRevenueStep) { map.updateOffBoardToolTips(); } @@ -1262,7 +1263,7 @@ public class ORUIManager implements DialogOwner { } else { priceRange = Bank.format(maxPrice); } - + privatesForSale.add(LocalText.getText("BuyPrivatePrompt", action.getPrivateCompany().getName(), action.getPrivateCompany().getPortfolio().getName(), @@ -1271,11 +1272,11 @@ public class ORUIManager implements DialogOwner { if (privatesForSale.size() > 0) { chosenOption = - (String) JOptionPane.showInputDialog(orWindow, - LocalText.getText("BUY_WHICH_PRIVATE"), - LocalText.getText("WHICH_PRIVATE"), - JOptionPane.QUESTION_MESSAGE, null, - privatesForSale.toArray(), privatesForSale.get(0)); + (String) JOptionPane.showInputDialog(orWindow, + LocalText.getText("BUY_WHICH_PRIVATE"), + LocalText.getText("WHICH_PRIVATE"), + JOptionPane.QUESTION_MESSAGE, null, + privatesForSale.toArray(), privatesForSale.get(0)); if (chosenOption != null) { index = privatesForSale.indexOf(chosenOption); chosenAction = privates.get(index); @@ -1283,13 +1284,13 @@ public class ORUIManager implements DialogOwner { maxPrice = chosenAction.getMaximumPrice(); if (minPrice < maxPrice) { String price = - JOptionPane.showInputDialog(orWindow, - LocalText.getText("WHICH_PRIVATE_PRICE", - chosenOption, - Bank.format(minPrice), - Bank.format(maxPrice) ), - LocalText.getText("WHICH_PRICE"), - JOptionPane.QUESTION_MESSAGE); + JOptionPane.showInputDialog(orWindow, + LocalText.getText("WHICH_PRIVATE_PRICE", + chosenOption, + Bank.format(minPrice), + Bank.format(maxPrice) ), + LocalText.getText("WHICH_PRICE"), + JOptionPane.QUESTION_MESSAGE); try { amount = Integer.parseInt(price); } catch (NumberFormatException e) { @@ -1386,8 +1387,8 @@ public class ORUIManager implements DialogOwner { action.getCompanyName(), Bank.format(action.getPrice())); if (JOptionPane.showConfirmDialog(orWindow, prompt, - message, JOptionPane.OK_CANCEL_OPTION, - JOptionPane.QUESTION_MESSAGE) + message, JOptionPane.OK_CANCEL_OPTION, + JOptionPane.QUESTION_MESSAGE) == JOptionPane.OK_OPTION) { action.setNumberTaken(1); orWindow.process(action); @@ -1433,9 +1434,9 @@ public class ORUIManager implements DialogOwner { orWindow, LocalText.getText("Select"), LocalText.getText("SelectLoansToRepay", action.getCompanyName()), - options, + options, 0); - gameUIManager.setCurrentDialog (currentDialog, action); + setCurrentDialog (currentDialog, action); } } @@ -1490,7 +1491,7 @@ public class ORUIManager implements DialogOwner { orPanel.initORCompanyTurn(orComp, orCompIndex); if (!myTurn) return; - + privatesCanBeBoughtNow = possibleActions.contains(BuyPrivate.class); orPanel.initPrivateBuying(privatesCanBeBoughtNow); @@ -1526,14 +1527,14 @@ public class ORUIManager implements DialogOwner { log.debug("Tiles can be laid"); mapRelatedActions.addAll(possibleActions.getType(LayTile.class)); - //} else if (possibleActions.contains(LayBaseToken.class)) { + //} else if (possibleActions.contains(LayBaseToken.class)) { } else if (orStep == GameDef.OrStep.LAY_TOKEN) { orWindow.requestFocus(); // Include bonus tokens List<LayToken> possibleTokenLays = - possibleActions.getType(LayToken.class); + possibleActions.getType(LayToken.class); mapRelatedActions.addAll(possibleTokenLays); allowedTokenLays = possibleTokenLays; @@ -1542,7 +1543,7 @@ public class ORUIManager implements DialogOwner { log.debug("BaseTokens can be laid"); } else if (possibleActions.contains(SetDividend.class) - && localStep == SELECT_PAYOUT) { + && localStep == SELECT_PAYOUT) { SetDividend action; if (actionToComplete != null) { @@ -1563,7 +1564,7 @@ public class ORUIManager implements DialogOwner { } else if (possibleActions.contains(SetDividend.class)) { SetDividend action = - possibleActions.getType(SetDividend.class).get(0); + possibleActions.getType(SetDividend.class).get(0); orPanel.initRevenueEntryStep(orCompIndex, action); @@ -1572,13 +1573,13 @@ public class ORUIManager implements DialogOwner { message += "<br><font color=\"red\">" + LocalText.getText("WarningNeedCash", Bank.format(action.getRequiredCash())) - + "</font>"; + + "</font>"; } setMessage(message); } else if (orStep == GameDef.OrStep.BUY_TRAIN) { - boolean canBuyTrain = possibleActions.contains(BuyTrain.class); + boolean canBuyTrain = possibleActions.contains(BuyTrain.class); orPanel.initTrainBuying(canBuyTrain); StringBuffer b = new StringBuffer(LocalText.getText("BuyTrain")); @@ -1621,7 +1622,7 @@ public class ORUIManager implements DialogOwner { if (possibleActions.contains(NullAction.class)) { List<NullAction> actions = - possibleActions.getType(NullAction.class); + possibleActions.getType(NullAction.class); for (NullAction action : actions) { switch (action.getMode()) { case NullAction.DONE: @@ -1634,7 +1635,7 @@ public class ORUIManager implements DialogOwner { if (possibleActions.contains(GameAction.class)) { List<GameAction> actions = - possibleActions.getType(GameAction.class); + possibleActions.getType(GameAction.class); for (GameAction action : actions) { switch (action.getMode()) { case GameAction.UNDO: @@ -1657,7 +1658,7 @@ public class ORUIManager implements DialogOwner { && orStep != GameDef.OrStep.LAY_TOKEN) { List<LayToken> tokenActions = - possibleActions.getType(LayToken.class); + possibleActions.getType(LayToken.class); for (LayToken tAction : tokenActions) { if (tAction instanceof LayBaseToken @@ -1678,14 +1679,14 @@ public class ORUIManager implements DialogOwner { if (possibleActions.contains(BuyBonusToken.class)) { List<BuyBonusToken> bonusTokenActions = - possibleActions.getType(BuyBonusToken.class); + possibleActions.getType(BuyBonusToken.class); for (BuyBonusToken bbt : bonusTokenActions) { String text = - LocalText.getText("BuyBonusToken", - bbt.getName(), - Bank.format(bbt.getValue()), - bbt.getSellerName(), - Bank.format(bbt.getPrice()) ); + LocalText.getText("BuyBonusToken", + bbt.getName(), + Bank.format(bbt.getValue()), + bbt.getSellerName(), + Bank.format(bbt.getPrice()) ); orPanel.addSpecialAction(bbt, text); } } @@ -1747,7 +1748,7 @@ public class ORUIManager implements DialogOwner { public void setLocalStep(int localStep) { log.debug("Setting upgrade step to " + localStep + " " - + ORUIManager.messageKey[localStep]); + + ORUIManager.messageKey[localStep]); this.localStep = localStep; updateMessage(); @@ -1758,7 +1759,7 @@ public class ORUIManager implements DialogOwner { if (upgradePanel != null) { log.debug("Initial localStep is " + localStep + " " - + ORUIManager.messageKey[localStep]); + + ORUIManager.messageKey[localStep]); ... [truncated message content] |
From: Frederick W. <fre...@us...> - 2012-01-12 15:17:30
|
rails/ui/swing/hexmap/HexMapImage.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) New commits: commit 37094a814afed9d7da83d61d68c2fdd85293ae25 Author: Frederick Weld <fre...@gm...> Date: Thu Jan 12 16:07:48 2012 +0100 Fixed missing initial map image scaling (if no auto-zoom configured) diff --git a/rails/ui/swing/hexmap/HexMapImage.java b/rails/ui/swing/hexmap/HexMapImage.java index ec64685..b8e95f4 100644 --- a/rails/ui/swing/hexmap/HexMapImage.java +++ b/rails/ui/swing/hexmap/HexMapImage.java @@ -87,7 +87,7 @@ public final class HexMapImage extends JSVGCanvas { initialized = true; //catch up on setting the bounds (if bounds setting were called before rendering prepare) - if (initialMapSize != null) setBoundsAndResize(initialMapSize,initialZoomStep); + setBoundsAndResize(hexMap.getCurrentSize(),hexMap.getZoomStep()); } addGVTTreeRendererListener(null); } |
From: Frederick W. <fre...@us...> - 2012-01-13 20:26:14
|
rails/ui/swing/GUIToken.java | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) New commits: commit 9d1152f5efce158c43ebf25a984ba89a35cf5502 Author: Frederick Weld <fre...@gm...> Date: Fri Jan 13 21:24:04 2012 +0100 Enhanced readability of token texts (condensed, multi-line) Texts containing 3 characters are displayed in condensed mode. Texts with more than 4 characters are split into two lines. With these changes, 1830 labels are readable on 800x600. diff --git a/rails/ui/swing/GUIToken.java b/rails/ui/swing/GUIToken.java index 5a02f08..7e07c63 100644 --- a/rails/ui/swing/GUIToken.java +++ b/rails/ui/swing/GUIToken.java @@ -2,8 +2,11 @@ package rails.ui.swing; import java.awt.*; +import java.awt.font.TextAttribute; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; +import java.util.HashMap; +import java.util.Map; import javax.swing.JPanel; @@ -109,19 +112,41 @@ public class GUIToken extends JPanel { public static void drawTokenText (String text, Graphics g, Color c, Point tokenCenter, double tokenDiameter) { + //recursion if text contains more than 3 characters + //not perfect (heuristic!) but good enough for this exceptional case + if (text.length() > 3) { + drawTokenText( text.substring(0, text.length() / 2), g, c, + new Point (tokenCenter.x, (int)((double)tokenCenter.y - tokenDiameter / 4 / 1.3)), + tokenDiameter / 2 / (1 - tokenTextMargin) * 1.2); + drawTokenText( text.substring(text.length() / 2, text.length()), g, c, + new Point (tokenCenter.x, (int)((double)tokenCenter.y + tokenDiameter / 4 * 1.1)), + tokenDiameter / 2 / (1 - tokenTextMargin) * 1.2); + return; + } + + //create condensed font if more than 2 chars in a line + Font fontTemplate; + if (text.length() > 2) { + Map<TextAttribute, Object> attributes = new HashMap<TextAttribute, Object>(); + attributes.put(TextAttribute.WIDTH, TextAttribute.WIDTH_CONDENSED); + fontTemplate = tokenFontTemplate.deriveFont(attributes); + } else { + fontTemplate = tokenFontTemplate; + } + //first calculate font size double allowedTextDiameter = tokenDiameter * (1 - tokenTextMargin); - Rectangle2D textBoundsInTemplate = g.getFontMetrics(tokenFontTemplate).getStringBounds(text, g); + Rectangle2D textBoundsInTemplate = g.getFontMetrics(fontTemplate).getStringBounds(text, g); double fontScalingX = allowedTextDiameter / textBoundsInTemplate.getWidth(); double fontScalingY = allowedTextDiameter / textBoundsInTemplate.getHeight(); double fontScaling = (fontScalingX < fontScalingY) ? fontScalingX : fontScalingY; - int fontSize = (int) Math.floor(fontScaling * tokenFontTemplate.getSize()); + int fontSize = (int) Math.floor(fontScaling * fontTemplate.getSize()); //draw text Color oldColor = g.getColor(); Font oldFont = g.getFont(); g.setColor(c); - g.setFont(tokenFontTemplate.deriveFont((float)fontSize)); //float needed to indicate size (not style) + g.setFont(fontTemplate.deriveFont((float)fontSize)); //float needed to indicate size (not style) Rectangle2D textBounds = g.getFontMetrics().getStringBounds(text, g); g.drawString(text, tokenCenter.x - (int)textBounds.getCenterX(), |
From: Frederick W. <fre...@us...> - 2012-01-21 18:15:33
|
rails/ui/swing/GridPanel.java | 38 ++++++++++++++++++++------------------ rails/ui/swing/ORPanel.java | 16 +++++++++++----- 2 files changed, 31 insertions(+), 23 deletions(-) New commits: commit a6d8c72b5d2cebe6ef49788daa5e197427af2524 Author: Frederick Weld <fre...@gm...> Date: Sat Jan 21 19:12:00 2012 +0100 Enhanced OR panel highlighting (highlights for multi-cell & spinner) Now all relevant cells of a company's turn are highlighted (eg. all token related cells during the lay token turn). The revenue spinner cell's highlighting is now aligned with the one of standard cells. Re-adjusted highlighting scope (eg., revenue is not highlighted any more during the decision turn). diff --git a/rails/ui/swing/GridPanel.java b/rails/ui/swing/GridPanel.java index 4941867..a64f955 100644 --- a/rails/ui/swing/GridPanel.java +++ b/rails/ui/swing/GridPanel.java @@ -62,7 +62,7 @@ implements ActionListener, KeyListener { protected static Logger log = Logger.getLogger(GridPanel.class.getPackage().getName()); - private JComponent highlightedComp = null; + private List<JComponent> highlightedComps = new ArrayList<JComponent>(); protected Color tableBorderColor; protected Color cellOutlineColor; protected Color highlightedBorderColor; @@ -142,31 +142,33 @@ implements ActionListener, KeyListener { /** * highlights given component by altering its border's attributes - * If another component had been highlighted before, it's highlighting is first - * undone before highlighting the new given component. */ protected void setHighlight(JComponent comp,boolean isToBeHighlighted) { //quit if nothing is to be done - if (isToBeHighlighted && comp == highlightedComp) return; - removeHighlight(); - if (isToBeHighlighted) { - if (comp.getBorder() instanceof FieldBorder) { - FieldBorder fb = (FieldBorder)comp.getBorder(); - fb.setHighlight(isToBeHighlighted); - comp.repaint(); + if (isToBeHighlighted && highlightedComps.contains(comp)) return; + if (!isToBeHighlighted && !highlightedComps.contains(comp)) return; + + if (comp.getBorder() instanceof FieldBorder) { + FieldBorder fb = (FieldBorder)comp.getBorder(); + fb.setHighlight(isToBeHighlighted); + comp.repaint(); + if (isToBeHighlighted) { + highlightedComps.add(comp); + } else { + highlightedComps.remove(comp); } - highlightedComp = comp; } } - protected void removeHighlight() { - if (highlightedComp == null) return; - if (highlightedComp.getBorder() instanceof FieldBorder) { - FieldBorder fb = (FieldBorder)highlightedComp.getBorder(); - fb.setHighlight(false); - highlightedComp.repaint(); + protected void removeAllHighlights() { + for (JComponent c : highlightedComps) { + if (c.getBorder() instanceof FieldBorder) { + FieldBorder fb = (FieldBorder)c.getBorder(); + fb.setHighlight(false); + c.repaint(); + } } - highlightedComp = null; + highlightedComps.clear(); } public void keyPressed(KeyEvent e) { diff --git a/rails/ui/swing/ORPanel.java b/rails/ui/swing/ORPanel.java index ffeabf8..f3b8b18 100644 --- a/rails/ui/swing/ORPanel.java +++ b/rails/ui/swing/ORPanel.java @@ -396,7 +396,7 @@ implements ActionListener, KeyListener, RevenueListener { loansXOffset = currentXOffset += lastXWidth; loansYOffset = leftCompNameYOffset; addField (loansCaption = new Caption(LocalText.getText("LOANS")), - loansXOffset, 0, lastXWidth = 1, 2, WIDE_RIGHT); + loansXOffset, 0, lastXWidth = 1, 2, WIDE_BOTTOM + WIDE_RIGHT); } if (hasRights) { @@ -541,7 +541,8 @@ implements ActionListener, KeyListener, RevenueListener { addField(f, revXOffset, revYOffset + i, 1, 1, 0, visible); f = revenueSelect[i] = new Spinner(0, 0, 0, 10); //zero-border so that size matches revenue field (thus, averting or panel resize) - f.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0)); + f.setPreferredSize(revenue[i].getPreferredSize()); + //f.setBorder(new javax.swing.border.EmptyBorder(0,0,0,0)); addField(f, revXOffset, revYOffset + i, 1, 1, 0, false); // deactived below, as this caused problems by gridpanel rowvisibility function -- sfy // revenue[i].addDependent(revenueSelect[i]); @@ -916,7 +917,7 @@ implements ActionListener, KeyListener, RevenueListener { } undoButton.setEnabled(false); - removeHighlight(); + removeAllHighlights(); } @@ -1005,7 +1006,7 @@ implements ActionListener, KeyListener, RevenueListener { this.orCompIndex = orCompIndex; president[orCompIndex].setHighlight(true); - removeHighlight(); + removeAllHighlights(); buttonOC.clearPossibleActions(); button1.clearPossibleActions(); @@ -1025,6 +1026,7 @@ implements ActionListener, KeyListener, RevenueListener { tileCaption.setHighlight(true); setHighlight(tiles[orCompIndex],true); + setHighlight(tileCost[orCompIndex],true); button1.setVisible(false); } @@ -1033,6 +1035,9 @@ implements ActionListener, KeyListener, RevenueListener { tokenCaption.setHighlight(true); setHighlight(tokens[orCompIndex],true); + setHighlight(tokenCost[orCompIndex],true); + setHighlight(tokensLeft[orCompIndex],true); + setHighlight(tokenBonus[orCompIndex],true); button1.setEnabled(false); button1.setVisible(false); button3.setEnabled(false); @@ -1081,7 +1086,7 @@ implements ActionListener, KeyListener, RevenueListener { public void initPayoutStep(int orCompIndex, SetDividend action, boolean withhold, boolean split, boolean payout) { - setHighlight(revenue[orCompIndex],true); + setHighlight(decision[orCompIndex],true); SetDividend clonedAction; @@ -1130,6 +1135,7 @@ implements ActionListener, KeyListener, RevenueListener { trainCaption.setHighlight(true); setHighlight(trains[orCompIndex],true); + setHighlight(newTrainCost[orCompIndex],true); button1.setText(LocalText.getText("BUY_TRAIN")); button1.setActionCommand(BUY_TRAIN_CMD); |
From: Frederick W. <fre...@us...> - 2012-01-21 18:27:47
|
rails/ui/swing/MessagePanel.java | 4 ++-- rails/ui/swing/ORPanel.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) New commits: commit 0c3a97d2c55df8ab8e8d06064e5d909bc89448fa Author: Frederick Weld <fre...@gm...> Date: Sat Jan 21 19:26:03 2012 +0100 Fixed MessagePanel's revalidate invocation diff --git a/rails/ui/swing/MessagePanel.java b/rails/ui/swing/MessagePanel.java index 6c50471..3b3d2cc 100644 --- a/rails/ui/swing/MessagePanel.java +++ b/rails/ui/swing/MessagePanel.java @@ -74,7 +74,7 @@ public class MessagePanel extends JPanel { if (showDetails) { showDetails = false; parentSlider.setPreferredSize(new Dimension(minWidth,defaultHeight)); - parentSlider.getParent().revalidate(); + ((JComponent)parentSlider.getParent()).revalidate(); } } @@ -82,7 +82,7 @@ public class MessagePanel extends JPanel { if (!showDetails && currentDetails != null) { showDetails = true; parentSlider.setPreferredSize(new Dimension(minWidth,fullHeight)); - parentSlider.getParent().revalidate(); + ((JComponent)parentSlider.getParent()).revalidate(); } } diff --git a/rails/ui/swing/ORPanel.java b/rails/ui/swing/ORPanel.java index f3b8b18..c8193ac 100644 --- a/rails/ui/swing/ORPanel.java +++ b/rails/ui/swing/ORPanel.java @@ -1037,7 +1037,7 @@ implements ActionListener, KeyListener, RevenueListener { setHighlight(tokens[orCompIndex],true); setHighlight(tokenCost[orCompIndex],true); setHighlight(tokensLeft[orCompIndex],true); - setHighlight(tokenBonus[orCompIndex],true); + if (tokenBonus != null) setHighlight(tokenBonus[orCompIndex],true); button1.setEnabled(false); button1.setVisible(false); button3.setEnabled(false); |
From: Frederick W. <fre...@us...> - 2012-02-01 17:59:52
|
rails/ui/swing/ORUIManager.java | 6 + rails/ui/swing/UpgradesPanel.java | 30 ++++++++- rails/ui/swing/hexmap/GUIHex.java | 7 +- rails/ui/swing/hexmap/GUITile.java | 120 ++++++++++++++++++++++++++++++------- 4 files changed, 136 insertions(+), 27 deletions(-) New commits: commit f69750118d746100e0f16eb7b1b2ebe3813810dd Author: Frederick Weld <fre...@gm...> Date: Wed Feb 1 18:54:15 2012 +0100 Rotate upgrade panel tiles to the first valid orientation The existing logic of determining validity of orientations was re-used (required some refactoring). This means that, once this logic is further improved, the upgrade panel's tile orientations will also get more accurate. The other source of complexity is that svg tile images are not centered and that image rotation by AOP result in additional borders on the bottom/right. Code that is able to handle that complexity is put to GUITile, as the former tile paint code is also there. diff --git a/rails/ui/swing/ORUIManager.java b/rails/ui/swing/ORUIManager.java index 6f7f8c6..226a8b5 100644 --- a/rails/ui/swing/ORUIManager.java +++ b/rails/ui/swing/ORUIManager.java @@ -731,7 +731,11 @@ public class ORUIManager implements DialogOwner { } } - private boolean getMustConnectRequirement (GUIHex hex,TileI tile) { + /** + * @return True if the indicated tile must be connected to some other track if + * placed on indicated hex. + */ + public boolean getMustConnectRequirement (GUIHex hex,TileI tile) { if (tile == null || hex == null) return false; return tile.getColourName().equalsIgnoreCase(Tile.YELLOW_COLOUR_NAME) // Does not apply to the current company's home hex(es) diff --git a/rails/ui/swing/UpgradesPanel.java b/rails/ui/swing/UpgradesPanel.java index 16486b5..1ac2332 100644 --- a/rails/ui/swing/UpgradesPanel.java +++ b/rails/ui/swing/UpgradesPanel.java @@ -19,11 +19,14 @@ import rails.game.action.*; import rails.game.correct.MapCorrectionAction; import rails.ui.swing.elements.ActionLabel; import rails.ui.swing.hexmap.GUIHex; +import rails.ui.swing.hexmap.GUITile; import rails.ui.swing.hexmap.HexHighlightMouseListener; import rails.ui.swing.hexmap.HexMap; public class UpgradesPanel extends Box implements MouseListener, ActionListener { private static final long serialVersionUID = 1L; + + private static final int UPGRADE_TILE_ZOOM_STEP = 10; private ORUIManager orUIManager; private List<ActionLabel> tokenLabels; @@ -61,7 +64,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener this.orUIManager = orUIManager; - preferredSize = new Dimension((int)Math.round(100 * (2 + Scale.getFontScale())/3), 200); + preferredSize = new Dimension((int)Math.round(110 * (2 + Scale.getFontScale())/3), 200); setSize(preferredSize); setVisible(true); @@ -220,7 +223,28 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } private HexLabel createHexLabel(TileI tile,String toolTipHeaderLine) { - BufferedImage hexImage = getHexImage(tile.getPictureId()); + BufferedImage hexImage = null; + + //get a buffered image of the tile in the first valid orientation + GUIHex selectedGUIHex = hexMap.getSelectedHex(); + if (selectedGUIHex != null) { + GUITile tempGUITile = selectedGUIHex.createUpgradeTileIfValid ( + tile.getId(), + orUIManager.getMustConnectRequirement(selectedGUIHex, tile)); + + if (tempGUITile != null) { + //tile has been rotated to valid orientation + //get unscaled image for this orientation + hexImage = tempGUITile.getTileImage(UPGRADE_TILE_ZOOM_STEP); + } + } + + //fallback if no valid orientation exists: + //get the image in the standard orientation + if (hexImage == null) { + hexImage = getHexImage(tile.getPictureId()); + } + ImageIcon hexIcon = new ImageIcon(hexImage); // Cheap n' Easy rescaling. @@ -375,7 +399,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } private BufferedImage getHexImage(int tileId) { - return GameUIManager.getImageLoader().getTile(tileId, 10); + return GameUIManager.getImageLoader().getTile(tileId, UPGRADE_TILE_ZOOM_STEP); } @Override diff --git a/rails/ui/swing/hexmap/GUIHex.java b/rails/ui/swing/hexmap/GUIHex.java index f67de31..af052cb 100644 --- a/rails/ui/swing/hexmap/GUIHex.java +++ b/rails/ui/swing/hexmap/GUIHex.java @@ -889,7 +889,12 @@ public class GUIHex implements ViewObject { return (provisionalGUITile != null); } - private GUITile createUpgradeTileIfValid (int tileId, boolean upgradeMustConnect) { + /** + * Creates an upgrade tile onto this hex without dropping it on the hex. + * This means that this hex won't consider the returned tile being part of it + * (even not on a temporary base). + */ + public GUITile createUpgradeTileIfValid (int tileId, boolean upgradeMustConnect) { GUITile t = new GUITile(tileId, this); /* Check if we can find a valid orientation of this tile */ return ( t.rotate(0, currentGUITile, upgradeMustConnect) ? t : null); diff --git a/rails/ui/swing/hexmap/GUITile.java b/rails/ui/swing/hexmap/GUITile.java index 9adfa4c..becbe56 100644 --- a/rails/ui/swing/hexmap/GUITile.java +++ b/rails/ui/swing/hexmap/GUITile.java @@ -25,7 +25,6 @@ public class GUITile { protected String tileType = null; protected int picId; - protected BufferedImage tileImage = null; protected int rotation = 0; @@ -38,7 +37,7 @@ public class GUITile { protected static ImageLoader imageLoader = GameUIManager.getImageLoader(); - protected AffineTransform af = new AffineTransform(); + protected RenderingHints renderingHints = null; public static final double DEG60 = Math.PI / 3; @@ -248,11 +247,32 @@ public class GUITile { tileScale = scale; } + private RenderingHints getTileRenderingHints() { + if (renderingHints == null) { + renderingHints = new RenderingHints(null); + renderingHints.put(RenderingHints.KEY_ALPHA_INTERPOLATION, + RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); + renderingHints.put(RenderingHints.KEY_ANTIALIASING, + RenderingHints.VALUE_ANTIALIAS_ON); + renderingHints.put(RenderingHints.KEY_COLOR_RENDERING, + RenderingHints.VALUE_COLOR_RENDER_QUALITY); + renderingHints.put(RenderingHints.KEY_DITHERING, + RenderingHints.VALUE_DITHER_DISABLE); + renderingHints.put(RenderingHints.KEY_INTERPOLATION, + RenderingHints.VALUE_INTERPOLATION_BICUBIC); + renderingHints.put(RenderingHints.KEY_RENDERING, + RenderingHints.VALUE_RENDER_QUALITY); + renderingHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, + RenderingHints.VALUE_TEXT_ANTIALIAS_ON); + } + return renderingHints; + } + public void paintTile(Graphics2D g2, int x, int y) { int zoomStep = guiHex.getHexMap().getZoomStep(); - tileImage = imageLoader.getTile(picId, zoomStep); + BufferedImage tileImage = imageLoader.getTile(picId, zoomStep); if (tileImage != null) { @@ -262,33 +282,89 @@ public class GUITile { int yCenter = (int) Math.round(tileImage.getHeight() * SVG_Y_CENTER_LOC * tileScale); - af = AffineTransform.getRotateInstance(radians, xCenter, yCenter); + AffineTransform af = AffineTransform.getRotateInstance(radians, xCenter, yCenter); af.scale(tileScale, tileScale); - RenderingHints rh = new RenderingHints(null); - rh.put(RenderingHints.KEY_ALPHA_INTERPOLATION, - RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); - rh.put(RenderingHints.KEY_ANTIALIASING, - RenderingHints.VALUE_ANTIALIAS_ON); - rh.put(RenderingHints.KEY_COLOR_RENDERING, - RenderingHints.VALUE_COLOR_RENDER_QUALITY); - rh.put(RenderingHints.KEY_DITHERING, - RenderingHints.VALUE_DITHER_DISABLE); - rh.put(RenderingHints.KEY_INTERPOLATION, - RenderingHints.VALUE_INTERPOLATION_BICUBIC); - rh.put(RenderingHints.KEY_RENDERING, - RenderingHints.VALUE_RENDER_QUALITY); - rh.put(RenderingHints.KEY_TEXT_ANTIALIASING, - RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - - AffineTransformOp aop = new AffineTransformOp(af, rh); + AffineTransformOp aop = new AffineTransformOp(af, + getTileRenderingHints()); g2.drawImage(tileImage, aop, x - xCenter, y - yCenter); + } else { - log.error("No image for tile "+tileId+" on hex "+guiHex.getName()); + log.error("No image for tile "+tileId+" on hex "+guiHex.getName()); } } + + /** + * Provides the image of the tile based on the zoomStep. + * tileScale is not considered for producing this image. + */ + public BufferedImage getTileImage(int zoomStep) { + + // STEP 1: GET IMAGE FROM SVG + // image not centered as there will be a bottom border to assign square bounds to the image + + BufferedImage uncenteredTileImage = imageLoader.getTile(picId, zoomStep); + if (uncenteredTileImage == null) return null; + + //svg always in NS orientation, hence wide diagonal can be directly taken from image size + int wideDiagonal = uncenteredTileImage.getWidth(); + + //narrow diagonal cannot be taken from image height due to the bottom border + int narrowDiagonal = (int)Math.round( wideDiagonal * 0.5 * Math.sqrt(3) ); + + int border = wideDiagonal - narrowDiagonal; + + // STEP 2: CENTER TILE IN IMAGE + // apply the bottom border also the left / top / right + + //center tile by translation + AffineTransform centeringAT = AffineTransform.getTranslateInstance( border, border ); + AffineTransformOp centeringATOp = new AffineTransformOp(centeringAT, null); + + //centered tile image create manually since it also needs a border on the right + BufferedImage centeredTileImage = new BufferedImage( + uncenteredTileImage.getWidth() + border * 2, + uncenteredTileImage.getHeight() + border, + uncenteredTileImage.getType()); + + centeringATOp.filter(uncenteredTileImage, centeredTileImage); + + // STEP 3: ROTATE TILE IMAGE + // feasible only now since there are enough margins to ensure tile won't exceed bounds + + double radians = baseRotation + rotation * DEG60; + int xCenter = (int) Math.round(centeredTileImage.getWidth() / 2 ); + int yCenter = (int) Math.round(centeredTileImage.getHeight() / 2 ); + + AffineTransform af = AffineTransform.getRotateInstance(radians, xCenter, yCenter); + AffineTransformOp aop = new AffineTransformOp(af, getTileRenderingHints()); + + BufferedImage rotatedTileImage = aop.filter(centeredTileImage, null); + + // STEP 4: CROP ROTATED TILE IMAGE + // rotation result will have additional borders on the right/bottom as a result of the AOP + + int croppedWidth, croppedHeight; + if (baseRotation == 0) { + //tile in NS orientation after rotation + croppedWidth = wideDiagonal; + croppedHeight = narrowDiagonal; + } else { + //tile in EW orientation after rotation + croppedWidth = narrowDiagonal; + croppedHeight = wideDiagonal; + } + BufferedImage croppedTileImage = rotatedTileImage.getSubimage( + xCenter - croppedWidth / 2, + yCenter - croppedHeight / 2, + croppedWidth, + croppedHeight ); + + return croppedTileImage; + } + public TileI getTile() { return tile; } |
From: Frederick W. <fre...@us...> - 2012-02-05 10:26:18
|
rails/ui/swing/ORWindow.java | 126 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 125 insertions(+), 1 deletion(-) New commits: commit 9b2b2d123eee75c646a4e0159f8420b672865504 Author: Frederick Weld <fre...@gm...> Date: Sun Feb 5 11:16:10 2012 +0100 Added support for docking externalized panels to each other Solution consists of adding a SplitDockStation in between and fine tuning the default dockable options (maximize button). Based on http://forum.byte-welt.de/showthread.php?t=3097&page=2 diff --git a/rails/ui/swing/ORWindow.java b/rails/ui/swing/ORWindow.java index 5f75ad9..b35bc3e 100644 --- a/rails/ui/swing/ORWindow.java +++ b/rails/ui/swing/ORWindow.java @@ -12,13 +12,28 @@ import java.util.Locale; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; import org.apache.log4j.Logger; +import bibliothek.gui.DockController; +import bibliothek.gui.Dockable; +import bibliothek.gui.DockStation; +import bibliothek.gui.dock.ScreenDockStation; +import bibliothek.gui.dock.SplitDockStation; import bibliothek.gui.dock.common.CControl; import bibliothek.gui.dock.common.CGrid; +import bibliothek.gui.dock.common.CStation; import bibliothek.gui.dock.common.DefaultSingleCDockable; +import bibliothek.gui.dock.common.action.predefined.CBlank; +import bibliothek.gui.dock.common.event.CDockableStateListener; +import bibliothek.gui.dock.common.intern.CDockable; +import bibliothek.gui.dock.common.intern.DefaultCDockable; +import bibliothek.gui.dock.common.intern.ui.CSingleParentRemover; +import bibliothek.gui.dock.common.mode.ExtendedMode; import bibliothek.gui.dock.common.theme.ThemeMap; +import bibliothek.gui.dock.event.DockStationAdapter; +import bibliothek.gui.dock.station.LayoutLocked; import rails.common.GuiDef; import rails.common.LocalText; @@ -92,7 +107,11 @@ public class ORWindow extends JFrame implements ActionPerformer { orWindowControl.setTheme( ThemeMap.KEY_SMOOTH_THEME ); add( orWindowControl.getContentArea() ); CGrid orWindowLayout = new CGrid( orWindowControl ); - + + //ensure that externalized dockables get a split station as parent + //necessary, otherwise externalized dockables cannot be docked together + alwaysAddStationsToExternalizedDockables(orWindowControl); + //set docks tooltip language if ("en_us".equalsIgnoreCase(Config.get("locale"))) { //hard setting to default in case of US as this is DockingFrames default language @@ -350,6 +369,111 @@ public class ORWindow extends JFrame implements ActionPerformer { orWindowControl.load(getLayoutName()); } catch (Exception e) {} //skip if layout not found } + + //ensure that all dockables that are externalized according to layout + //information don't have the deault maximize button (as it won't work + //for the adjusted externalization setup) + for (int i = 0 ; i < orWindowControl.getCDockableCount() ; i++ ) { + CDockable d = orWindowControl.getCDockable(i); + if (d instanceof DefaultCDockable) { + DefaultCDockable dd = (DefaultCDockable)d; + if (ExtendedMode.EXTERNALIZED.equals(d.getExtendedMode())) { + dd.putAction( CDockable.ACTION_KEY_MAXIMIZE, CBlank.BLANK ); + } + } + } + } + + /** + * The behavior of the specified CControl is altered by the following: + * If a dockable is detached / externalized, it would normally put directly + * under the ScreenDockStation - thus inhibiting any docking to/from this + * dockable. This is changed such that a split station (that would allow for + * that) is put in between the ScreenDockStation and the Dockable. + */ + private void alwaysAddStationsToExternalizedDockables(CControl cc) { + + // access the DockStation which shows our detached (externalized) items + CStation<?> screen = (CStation<?>) + cc.getStation( CControl.EXTERNALIZED_STATION_ID ); + + // remove the standard maximize action when externalizing + // and adds it back when unexternalizing + // (as maximize won't work for the adjusted externalization setup) + cc.addStateListener( new CDockableStateListener() { + public void visibilityChanged( CDockable cd ){ + // ignore + } + + public void extendedModeChanged( CDockable cd, ExtendedMode mode ){ + if( cd instanceof DefaultCDockable ) { + DefaultCDockable dockable = (DefaultCDockable) cd; + if( mode.equals( ExtendedMode.EXTERNALIZED ) ) { + dockable.putAction( CDockable.ACTION_KEY_MAXIMIZE, CBlank.BLANK ); + } + else { + dockable.putAction( CDockable.ACTION_KEY_MAXIMIZE, null ); + } + } + } + }); + + // if a Dockable is added to that station... + screen.getStation().addDockStationListener( new ScreenDockStationListener()); + + // make sure a SplitDockStation with one child and a parent + // that is a ScreenDockStation does not get removed + cc.intern().getController().setSingleParentRemover( + new CSingleParentRemover( cc ){ + @Override + protected boolean shouldTest( DockStation station ){ + if( station instanceof SplitDockStation ) { + SplitDockStation split = (SplitDockStation) station; + if( split.getDockParent() instanceof ScreenDockStation ) { + // but we want to remove the station if it does + // not have any children at all + return split.getDockableCount() == 0; + } + } + return super.shouldTest( station ); + } + } ); } + @LayoutLocked(locked = false) + private class ScreenDockStationListener extends DockStationAdapter { + public void dockableAdded( DockStation station, final Dockable dockable ){ + // ... and the new child is not a SplitDockStation ... + if( !(dockable instanceof SplitDockStation) ) { + SwingUtilities.invokeLater( new Runnable(){ + public void run(){ + checkAndReplace( dockable ); + } + } ); + } + } + private void checkAndReplace( Dockable dockable ){ + DockStation station = dockable.getDockParent(); + if( !(station instanceof ScreenDockStation) ) { + // cancel + return; + } + + // .. then we just insert a SplitDockStation + SplitDockStation split = new SplitDockStation(); + DockController controller = station.getController(); + + try { + // disable events while rearranging our layout + controller.freezeLayout(); + + station.replace( dockable, split ); + split.drop( dockable ); + } + finally { + // and enable events after we finished + controller.meltLayout(); + } + } + } } |
From: Frederick W. <fre...@us...> - 2012-02-05 13:24:18
|
rails/ui/swing/ORWindow.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) New commits: commit 6d5f311591d781cecd4bfe4bb2fcf3e2a9b8be65 Author: Frederick Weld <fre...@gm...> Date: Sun Feb 5 14:21:31 2012 +0100 Fixed: Externalized panels taken into account when close/open OR window Stefan had observed that externalized panels were not correctly restored when closing / re-opening the OR Window. diff --git a/rails/ui/swing/ORWindow.java b/rails/ui/swing/ORWindow.java index b35bc3e..441be07 100644 --- a/rails/ui/swing/ORWindow.java +++ b/rails/ui/swing/ORWindow.java @@ -191,7 +191,11 @@ public class ORWindow extends JFrame implements ActionPerformer { public void windowClosing(WindowEvent e) { saveDockableLayout(); StatusWindow.uncheckMenuItemBox(StatusWindow.MAP_CMD); - frame.dispose(); + if (!isDockablePanelsEnabled()) { + frame.dispose(); + } else { + setVisible(false); + } } }); addComponentListener(new ComponentAdapter() { |
From: Frederick W. <fre...@us...> - 2012-02-07 16:37:37
|
rails/ui/swing/GridPanel.java | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) New commits: commit 59e98fa0bda31a4f2944fee0dac6bd123b322bb0 Author: Frederick Weld <fre...@gm...> Date: Tue Feb 7 17:36:03 2012 +0100 Increased robustness of grid panel highlighting getBorderInsets was reported to return null under some conditions. Now, GridPanel is able to handle that. diff --git a/rails/ui/swing/GridPanel.java b/rails/ui/swing/GridPanel.java index 9f11f42..d2ea42b 100644 --- a/rails/ui/swing/GridPanel.java +++ b/rails/ui/swing/GridPanel.java @@ -252,12 +252,16 @@ implements ActionListener, KeyListener { this.nativeInnerBorder = innerBorder; this.outlineBorder = outlineBorder; this.outerBorder = outerBorder; + Insets nativeInnerBorderInsets = nativeInnerBorder.getBorderInsets(null); + if (nativeInnerBorderInsets == null) { + nativeInnerBorderInsets = new Insets(0,0,0,0); + } this.highlightedInnerBorder = new DynamicBorder( highlightedBorderColor, - nativeInnerBorder.getBorderInsets(null).top, - nativeInnerBorder.getBorderInsets(null).left, - nativeInnerBorder.getBorderInsets(null).bottom, - nativeInnerBorder.getBorderInsets(null).right); + nativeInnerBorderInsets.top, + nativeInnerBorderInsets.left, + nativeInnerBorderInsets.bottom, + nativeInnerBorderInsets.right); } public void setHighlight(boolean isToBeHighlighted) { outlineBorder.setHighlight(isToBeHighlighted); |
From: Frederick W. <fre...@us...> - 2012-02-08 16:50:21
|
rails/ui/swing/GridPanel.java | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) New commits: commit 5f70d21472cf24abf7ac417896273245f39074e8 Author: Frederick Weld <fre...@gm...> Date: Wed Feb 8 17:49:20 2012 +0100 Increased robustness for GridPanel(2): Added field may have null-border diff --git a/rails/ui/swing/GridPanel.java b/rails/ui/swing/GridPanel.java index d2ea42b..ddc4582 100644 --- a/rails/ui/swing/GridPanel.java +++ b/rails/ui/swing/GridPanel.java @@ -244,24 +244,30 @@ implements ActionListener, KeyListener { private class FieldBorder extends CompoundBorder { private static final long serialVersionUID = 1L; Border nativeInnerBorder; - DynamicBorder highlightedInnerBorder; + /** + * remains null if nativeInnerBorder is null or broken + */ + DynamicBorder highlightedInnerBorder = null; DynamicBorder outlineBorder; DynamicBorder outerBorder; public FieldBorder(Border innerBorder,DynamicBorder outlineBorder,DynamicBorder outerBorder) { super(new CompoundBorder(outerBorder,outlineBorder),innerBorder); - this.nativeInnerBorder = innerBorder; + nativeInnerBorder = innerBorder; this.outlineBorder = outlineBorder; this.outerBorder = outerBorder; - Insets nativeInnerBorderInsets = nativeInnerBorder.getBorderInsets(null); - if (nativeInnerBorderInsets == null) { - nativeInnerBorderInsets = new Insets(0,0,0,0); + + //prepare highlighted inner border + if (nativeInnerBorder != null) { + Insets nativeInnerBorderInsets = nativeInnerBorder.getBorderInsets(null); + if (nativeInnerBorderInsets != null) { + highlightedInnerBorder = new DynamicBorder( + highlightedBorderColor, + nativeInnerBorderInsets.top, + nativeInnerBorderInsets.left, + nativeInnerBorderInsets.bottom, + nativeInnerBorderInsets.right); + } } - this.highlightedInnerBorder = new DynamicBorder( - highlightedBorderColor, - nativeInnerBorderInsets.top, - nativeInnerBorderInsets.left, - nativeInnerBorderInsets.bottom, - nativeInnerBorderInsets.right); } public void setHighlight(boolean isToBeHighlighted) { outlineBorder.setHighlight(isToBeHighlighted); |
From: Frederick W. <fre...@us...> - 2012-02-08 18:31:46
|
rails/ui/swing/MessagePanel.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) New commits: commit f9839fa2ddce01e0b850d384fa10613f7de51812 Author: Frederick Weld <fre...@gm...> Date: Wed Feb 8 19:29:33 2012 +0100 Allowed for dynamic line breaks and vertical centering of message panel Main motivation for rework is that the dockable message text might be put in a vertical alignment (of narrow width). For the message panel, new behavior is that - no horizontal scroll bar is used - if panel's width inferior to message label's native width, a line break is inserted into the label text - technically done by using a layout manager and basing the panel's preferred width on the parent scrollpane's one An additional benefit of using the layout manager is that, for the first time since having added the scrollbar to the panel, messages are vertically centered. diff --git a/rails/ui/swing/MessagePanel.java b/rails/ui/swing/MessagePanel.java index 3b3d2cc..ed785de 100644 --- a/rails/ui/swing/MessagePanel.java +++ b/rails/ui/swing/MessagePanel.java @@ -3,6 +3,7 @@ package rails.ui.swing; import java.awt.Color; import java.awt.Dimension; +import java.awt.GridLayout; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; @@ -37,6 +38,10 @@ public class MessagePanel extends JPanel { setBackground(background); setBorder(new EmptyBorder(0,0,0,0)); + //add layout manager + //necessary for auto word-wrap when diminishing width + setLayout(new GridLayout(1,1)); + message = new JLabel(""); message.setBackground(background); message.setVerticalAlignment(SwingConstants.CENTER); @@ -138,5 +143,15 @@ public class MessagePanel extends JPanel { currentDetails = "<BR>" + detailText; updateMessageText(); } - + + @Override + public Dimension getPreferredSize() { + Dimension nativeSize = super.getPreferredSize(); + if (parentSlider == null) return nativeSize; + int width = parentSlider.getSize().width + - parentSlider.getVerticalScrollBar().getWidth() + - 5; + if (width <= 0) width = 1; + return new Dimension (width , nativeSize.height); + } } |
From: Frederick W. <fre...@us...> - 2012-02-12 09:39:03
|
rails/ui/swing/ORPanel.java | 20 +++++++++++ rails/ui/swing/ORWindow.java | 6 ++- rails/ui/swing/UpgradesPanel.java | 64 +++++++++++++++++++++++++++++--------- 3 files changed, 74 insertions(+), 16 deletions(-) New commits: commit 223e9fc1754a08fd2eca8aba99b63fb9aeb1bd45 Author: Frederick Weld <fre...@gm...> Date: Sun Feb 12 10:37:37 2012 +0100 Moved upgrade panel buttons to ORPanel button panel (dockable layout only) diff --git a/rails/ui/swing/ORPanel.java b/rails/ui/swing/ORPanel.java index 0dd18ce..58d4967 100644 --- a/rails/ui/swing/ORPanel.java +++ b/rails/ui/swing/ORPanel.java @@ -1366,4 +1366,24 @@ implements ActionListener, KeyListener, RevenueListener { public JMenuBar getMenuBar() { return menuBar; } + + /** + * Adds buttons to the button panel (adjusting their size to the standard size) + * @param index The position where to add the buttons + */ + public void addToButtonPanel(RailsIconButton[] buttons, int index) { + //get standard size + Dimension standardSize = null; + Component[] existingButtons = buttonPanel.getComponents(); + if (existingButtons != null && existingButtons.length > 0) { + standardSize = existingButtons[0].getPreferredSize(); + } + + //apply sizing to new buttons + //add buttons to the panel + for (int i=buttons.length-1 ; i >= 0 ; i--) { + buttons[i].setPreferredSize(standardSize); + buttonPanel.add(buttons[i],index); + } + } } diff --git a/rails/ui/swing/ORWindow.java b/rails/ui/swing/ORWindow.java index 9b049a5..6fc127a 100644 --- a/rails/ui/swing/ORWindow.java +++ b/rails/ui/swing/ORWindow.java @@ -66,7 +66,7 @@ public class ORWindow extends DockingFrame implements ActionPerformer { JScrollPane messagePanelSlider = new JScrollPane(messagePanel); messagePanel.setParentSlider(messagePanelSlider); - upgradePanel = new UpgradesPanel(orUIManager); + upgradePanel = new UpgradesPanel(orUIManager,isDockingFrameworkEnabled()); addMouseListener(upgradePanel); mapPanel = new MapPanel(gameUIManager); @@ -76,6 +76,10 @@ public class ORWindow extends DockingFrame implements ActionPerformer { //create docking / conventional layout if (isDockingFrameworkEnabled()) { + //set up the button panel (which is separated from its OR panel parent) + //adding upgrade panel buttons on top + orPanel.addToButtonPanel(upgradePanel.getButtons(),0); + //initialize remaining tile panel as it is no optional part in the docking layout JScrollPane remainingTilesPanelSlider = new RemainingTilesWindow(this).getScrollPane(); diff --git a/rails/ui/swing/UpgradesPanel.java b/rails/ui/swing/UpgradesPanel.java index c1a9df7..a471004 100644 --- a/rails/ui/swing/UpgradesPanel.java +++ b/rails/ui/swing/UpgradesPanel.java @@ -50,6 +50,13 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener private RailsIconButton doneButton = new RailsIconButton(RailsIcon.LAY_TILE); private HexMap hexMap; + /** + * If set, done/cancel buttons are not added to the pane. Instead, the + * visibility property of these buttons are handled such that they are set to + * visible if they normally would be added to the pane. + */ + private boolean omitButtons; + //list of tiles with an attached reason why it would represent an invalid upgrade private Map<TileI,String> invalidTileUpgrades = null; private static final String invalidUpgradeNoTilesLeft = "NoTilesLeft"; @@ -58,10 +65,11 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener protected static Logger log = Logger.getLogger(UpgradesPanel.class.getPackage().getName()); - public UpgradesPanel(ORUIManager orUIManager) { + public UpgradesPanel(ORUIManager orUIManager,boolean omitButtons) { super(BoxLayout.Y_AXIS); this.orUIManager = orUIManager; + this.omitButtons = omitButtons; preferredSize = new Dimension((int)Math.round(110 * (2 + Scale.getFontScale())/3), 200); setSize(preferredSize); @@ -85,6 +93,11 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener cancelButton.setActionCommand("Cancel"); cancelButton.setMnemonic(KeyEvent.VK_C); cancelButton.addActionListener(this); + + if (omitButtons) { + doneButton.setVisible(false); + cancelButton.setVisible(false); + } add(scrollPane); } @@ -136,7 +149,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } public void showUpgrades() { - upgradePanel.removeAll(); + clearPanel(); // reset to the number of elements GridLayout panelLayout = (GridLayout)upgradePanel.getLayout(); @@ -214,9 +227,8 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } } - upgradePanel.add(doneButton); - upgradePanel.add(cancelButton); - + addButtons(); + //repaint(); revalidate(); } @@ -269,7 +281,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener tokenMode = false; // activate upgrade panel - upgradePanel.removeAll(); + clearPanel(); GridLayout panelLayout = (GridLayout)upgradePanel.getLayout(); List<TileI> tiles = orUIManager.tileUpgrades; @@ -304,8 +316,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } } - upgradePanel.add(doneButton); - upgradePanel.add(cancelButton); + addButtons(); // repaint(); revalidate(); @@ -318,7 +329,7 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener tokenMode = false; // activate upgrade panel - upgradePanel.removeAll(); + clearPanel(); GridLayout panelLayout = (GridLayout)upgradePanel.getLayout(); List<? extends TokenI> tokens = orUIManager.tokenLays; @@ -357,8 +368,8 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } } - upgradePanel.add(doneButton); - upgradePanel.add(cancelButton); + + addButtons(); // repaint(); revalidate(); @@ -366,9 +377,8 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener } public void clear() { - upgradePanel.removeAll(); - upgradePanel.add(doneButton); - upgradePanel.add(cancelButton); + clearPanel(); + addButtons(); upgradePanel.repaint(); } @@ -537,7 +547,31 @@ public class UpgradesPanel extends Box implements MouseListener, ActionListener setDoneEnabled(false); setCancelEnabled(false); } - + + private void clearPanel() { + upgradePanel.removeAll(); + if (omitButtons) { + doneButton.setVisible(false); + cancelButton.setVisible(false); + } + } + + private void addButtons() { + if (omitButtons) { + //only set externally managed buttons to visible if at least + //one of them is enabled + boolean isVisible = doneButton.isEnabled() || cancelButton.isEnabled(); + doneButton.setVisible(isVisible); + cancelButton.setVisible(isVisible); + } else { + upgradePanel.add(doneButton); + upgradePanel.add(cancelButton); + } + } + + public RailsIconButton[] getButtons() { + return new RailsIconButton[] {doneButton, cancelButton}; + } /** ActionLabel extension that allows to attach the token */ private class CorrectionTokenLabel extends ActionLabel { |
From: Stefan F. <ste...@us...> - 2012-02-13 21:52:59
|
dev/null |binary rails/ui/images/train.png |binary 2 files changed New commits: commit 7f69d992ea2f4a1d019748b147f9b44840ae8276 Author: Stefan Frey <ste...@we...> Date: Mon Feb 13 22:31:25 2012 +0100 fixed type in filename of train.png diff --git a/rails/ui/images/Train.png b/rails/ui/images/Train.png deleted file mode 100644 index 0957b13..0000000 Binary files a/rails/ui/images/Train.png and /dev/null differ diff --git a/rails/ui/images/train.png b/rails/ui/images/train.png new file mode 100644 index 0000000..0957b13 Binary files /dev/null and b/rails/ui/images/train.png differ |
From: Frederick W. <fre...@us...> - 2012-02-19 12:21:52
|
rails/ui/swing/ReportWindowDynamic.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) New commits: commit 5467d59293b48a45470ccf779b84520040495ffa Author: Frederick Weld <fre...@gm...> Date: Sun Feb 19 13:19:39 2012 +0100 Fixed order of initing DynamicReportWindow (pack only after layout done) Found out issue when running on other computer: Report window gets zero size. This commit fixes this issue which was traced back to a premature call of super.init to the AbstractReportWindow's pack - dyn report window only sets up layout afterwards (against EDT rules). This is fixed by postponing the super.init call to the point in time when the layout is ready. diff --git a/rails/ui/swing/ReportWindowDynamic.java b/rails/ui/swing/ReportWindowDynamic.java index 00daad2..df789f8 100644 --- a/rails/ui/swing/ReportWindowDynamic.java +++ b/rails/ui/swing/ReportWindowDynamic.java @@ -55,8 +55,6 @@ public class ReportWindowDynamic extends AbstractReportWindow implements Action @Override public void init() { - super.init(); - setLayout(new BorderLayout()); JPanel messagePanel = new JPanel(); @@ -142,6 +140,8 @@ public class ReportWindowDynamic extends AbstractReportWindow implements Action ); buttonPanel.add(commentButton); + super.init(); + } @Override |
From: Erik V. <ev...@us...> - 2012-03-01 20:47:09
|
rails/ui/swing/GameSetupWindow.java | 73 +++++++++++++++++------------------- 1 file changed, 36 insertions(+), 37 deletions(-) New commits: commit c4ba582a4f59b45f182179c8e3c0d600df3bec40 Author: Erik Vos <eri...@xs...> Date: Thu Mar 1 21:45:10 2012 +0100 Fixed 'Load Recent' by running it in a separate thread. This is required since the new Splash Window. diff --git a/rails/ui/swing/GameSetupWindow.java b/rails/ui/swing/GameSetupWindow.java index 9282195..d948ff4 100644 --- a/rails/ui/swing/GameSetupWindow.java +++ b/rails/ui/swing/GameSetupWindow.java @@ -8,21 +8,13 @@ import java.util.List; import javax.swing.*; -import rails.common.parser.ConfigurationException; -import rails.common.parser.GameInfoParser; - import org.apache.log4j.Logger; -import rails.common.Config; -import rails.common.DisplayBuffer; -import rails.common.GuiDef; -import rails.common.LocalText; -import rails.common.ConfigManager; -import rails.common.parser.GameOption; -import rails.common.parser.GameInfo; +import rails.common.*; +import rails.common.parser.*; import rails.game.*; import rails.sound.SoundManager; -import rails.util.*; +import rails.util.Util; /** * The Game Setup Window displays the first window presented to the user. This @@ -34,7 +26,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { GridBagConstraints gc; JPanel gameListPane, playersPane, buttonPane, optionsPane; JButton newButton, loadButton, recentButton, recoveryButton, quitButton, optionButton, infoButton, - creditsButton, randomizeButton, configureButton; + creditsButton, randomizeButton, configureButton; JComboBox configureBox; JComboBox gameNameBox = new JComboBox(); JComboBox[] playerBoxes = new JComboBox[Player.MAX_PLAYERS]; @@ -62,11 +54,11 @@ public class GameSetupWindow extends JDialog implements ActionListener { static final int AI_PLAYER = 2; protected static Logger log = - Logger.getLogger(GameSetupWindow.class.getPackage().getName()); + Logger.getLogger(GameSetupWindow.class.getPackage().getName()); public GameSetupWindow() { super(); - + GameInfoParser gip = new GameInfoParser(); try { gameInfoList = gip.processGameList(); @@ -113,7 +105,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); populateGameList(gameInfoList, gameNameBox); - + final ConfigManager cm = ConfigManager.getInstance(); configureBox = new JComboBox(cm.getProfiles().toArray()); configureBox.setSelectedItem(cm.getActiveProfile()); @@ -161,7 +153,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { // This needs to happen after we have a valid gameName. fillPlayersPane(); - + // Notify the sound manager about having started the setup menu SoundManager.notifyOfGameSetup(); } @@ -263,6 +255,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { if (arg0.getSource().equals(newButton)) { //start in new thread so that swing thread is not used for game setup new Thread() { + @Override public void run() { startNewGame(); } @@ -288,6 +281,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { final File selectedFile = jfc.getSelectedFile(); //start in new thread so that swing thread is not used for game setup new Thread() { + @Override public void run() { loadAndStartGame(selectedFile.getPath(), selectedFile.getParent()); } @@ -297,7 +291,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { } } else if (arg0.getSource().equals(recentButton)) { File saveDirectory = new File(Config.get("save.directory")); - + recentFiles = new TreeSet<File>(new Comparator<File> (){ public int compare (File a, File b) { return Math.round(b.lastModified() - a.lastModified()); @@ -321,12 +315,17 @@ public class GameSetupWindow extends JDialog implements ActionListener { } String text = LocalText.getText("Select"); String result = (String) JOptionPane.showInputDialog(this, text, text, - JOptionPane.OK_CANCEL_OPTION, + JOptionPane.OK_CANCEL_OPTION, null, options, options[0]); if (result == null) return; - File selectedFile = files[Arrays.asList(options).indexOf(result)]; + final File selectedFile = files[Arrays.asList(options).indexOf(result)]; if (selectedFile != null) { - loadAndStartGame(selectedFile.getPath(), selectedFile.getParent()); + new Thread() { + @Override + public void run() { + loadAndStartGame(selectedFile.getPath(), selectedFile.getParent()); + } + }.start(); } else { // cancel pressed return; } @@ -335,14 +334,14 @@ public class GameSetupWindow extends JDialog implements ActionListener { loadAndStartGame(filePath, null); } else if (arg0.getSource().equals(infoButton)) { GameInfo gameInfo = this.getSelectedGameInfo(); - JOptionPane.showMessageDialog(this, - gameInfo.getDescription(), + JOptionPane.showMessageDialog(this, + gameInfo.getDescription(), "Information about " + gameInfo.getName(), JOptionPane.INFORMATION_MESSAGE); } else if (arg0.getSource().equals(quitButton)) { System.exit(0); } else if (arg0.getSource().equals(creditsButton)) { - JOptionPane.showMessageDialog(this, + JOptionPane.showMessageDialog(this, new JLabel(credits), //enable html rendering LocalText.getText("CREDITS"), JOptionPane.INFORMATION_MESSAGE); @@ -381,9 +380,9 @@ public class GameSetupWindow extends JDialog implements ActionListener { List<String> playerList = new ArrayList<String>(); for (int i = 0; i < playerNameFields.length; i++) { if (playerNameFields[i] != null - && playerNameFields[i].getText().length() > 0) { - playerList.add(playerNameFields[i].getText()); - playerNameFields[i].setText(""); + && playerNameFields[i].getText().length() > 0) { + playerList.add(playerNameFields[i].getText()); + playerNameFields[i].setText(""); } } Collections.shuffle(playerList); @@ -394,7 +393,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { } } } - + private void getRecentFiles (File dir) { if (!dir.exists() || !dir.isDirectory()) return; for (File entry : dir.listFiles()) { @@ -422,7 +421,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { for (GameOption option : availableOptions) { if (option.isBoolean()) { JCheckBox checkbox = - new JCheckBox(option.getLocalisedName()); + new JCheckBox(option.getLocalisedName()); if (option.getDefaultValue().equalsIgnoreCase("yes")) { checkbox.setSelected(true); } @@ -460,14 +459,14 @@ public class GameSetupWindow extends JDialog implements ActionListener { for (int i = 0; i < playerBoxes.length; i++) { if (playerBoxes[i] != null - && playerBoxes[i].getSelectedIndex() == HUMAN_PLAYER - && !playerNameFields[i].getText().equals("")) { + && playerBoxes[i].getSelectedIndex() == HUMAN_PLAYER + && !playerNameFields[i].getText().equals("")) { playerNames.add(playerNameFields[i].getText()); } } if (playerNames.size() < Player.MIN_PLAYERS - || playerNames.size() > Player.MAX_PLAYERS) { + || playerNames.size() > Player.MAX_PLAYERS) { if (JOptionPane.showConfirmDialog(this, "Not enough players. Continue Anyway?", "Are you sure?", JOptionPane.YES_NO_OPTION) == JOptionPane.NO_OPTION) { @@ -477,7 +476,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { } catch (NullPointerException e) { e.printStackTrace(); JOptionPane.showMessageDialog(this, - "Unable to load selected rails.game. Exiting..."); + "Unable to load selected rails.game. Exiting..."); System.exit(-1); } @@ -514,9 +513,9 @@ public class GameSetupWindow extends JDialog implements ActionListener { } String gameName = getSelectedGameInfo().getName(); - + SplashWindow splashWindow = new SplashWindow(false,gameName); - + game = new Game(gameName, playerNames, selectedOptions); if (!game.setup()) { @@ -541,12 +540,12 @@ public class GameSetupWindow extends JDialog implements ActionListener { } } - + private void prepareGameUIInit() { setVisible(false); if (configWindow != null) configWindow.setVisible(false); } - + private void completeGameUIInit(SplashWindow splashWindow) { if (configWindow != null) { configWindow.dispose(); @@ -584,7 +583,7 @@ public class GameSetupWindow extends JDialog implements ActionListener { // Remember names that have already been filled-in... for (int i = 0; i < playerNameFields.length; i++) { if (playerNameFields[i] != null - && playerNameFields[i].getText().length() > 0) { + && playerNameFields[i].getText().length() > 0) { playerList[i] = playerNameFields[i].getText(); } else if (i < testPlayers.length && testPlayers[i].length() > 0) { playerList[i] = testPlayers[i]; |
From: Erik V. <ev...@us...> - 2012-03-19 10:07:26
|
rails/ui/swing/hexmap/GUITile.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) New commits: commit 5b0f187fd940b9162d9690793eed1e5d65883d24 Author: Erik Vos <eri...@xs...> Date: Mon Mar 19 11:06:27 2012 +0100 Fix to previous commit diff --git a/rails/ui/swing/hexmap/GUITile.java b/rails/ui/swing/hexmap/GUITile.java index 9f34078..e28e64c 100644 --- a/rails/ui/swing/hexmap/GUITile.java +++ b/rails/ui/swing/hexmap/GUITile.java @@ -54,7 +54,7 @@ public class GUITile { TileManager tileManager = guiHex.getHexMap().orUIManager.getTileManager(); tile = tileManager.getTile(tileId); - if (tile.getId() > 0) { + if (tile.getPictureId() > 0) { // Layable tiles can have a different picture ID, defined per tile only. picId = tile.getPictureId(); } else { |
From: Erik V. <ev...@us...> - 2012-04-03 13:32:41
|
rails/ui/swing/ORUIManager.java | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) New commits: commit 7394b2bb745bfd1cc665fb3ee5513f7a9461c6e2 Author: Erik Vos <eri...@xs...> Date: Tue Apr 3 15:32:06 2012 +0200 Fixed: after 'Destinations reached' dialog with no checks, buttons remained disabled. Reported by John David Galt. diff --git a/rails/ui/swing/ORUIManager.java b/rails/ui/swing/ORUIManager.java index 0c634df..0224995 100644 --- a/rails/ui/swing/ORUIManager.java +++ b/rails/ui/swing/ORUIManager.java @@ -9,9 +9,7 @@ import org.apache.log4j.Logger; import org.jgrapht.graph.SimpleGraph; import rails.algorithms.*; -import rails.common.Config; -import rails.common.GuiDef; -import rails.common.LocalText; +import rails.common.*; import rails.game.*; import rails.game.action.*; import rails.game.correct.*; @@ -590,12 +588,13 @@ public class ORUIManager implements DialogOwner { // Prevent that a null action gets processed if (action.getReachedCompanies() == null - || action.getReachedCompanies().isEmpty()) return; + || action.getReachedCompanies().isEmpty()) currentDialogAction = null; } else { - return; + currentDialogAction = null; } + // Required even if no action is executed, to update the UI, re-enable buttons etc. gameUIManager.processAction(currentDialogAction); } |
From: Erik V. <ev...@us...> - 2012-05-08 10:04:56
|
rails/ui/swing/MapPanel.java | 79 +++++++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 39 deletions(-) New commits: commit bd86c17a13a6cb75d35af0d102a740ba7a234bb9 Author: Erik Vos <eri...@xs...> Date: Tue May 8 12:03:06 2012 +0200 Fix exception in Map panel scrolling diff --git a/rails/ui/swing/MapPanel.java b/rails/ui/swing/MapPanel.java index 265defe..ba92268 100644 --- a/rails/ui/swing/MapPanel.java +++ b/rails/ui/swing/MapPanel.java @@ -2,9 +2,7 @@ package rails.ui.swing; import java.awt.*; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyEvent; +import java.awt.event.*; import java.util.List; import javax.swing.*; @@ -14,7 +12,8 @@ import org.apache.log4j.Logger; import rails.game.MapManager; import rails.game.action.LayTile; import rails.game.action.LayToken; -import rails.ui.swing.hexmap.*; +import rails.ui.swing.hexmap.HexMap; +import rails.ui.swing.hexmap.HexMapImage; /** * MapWindow class displays the Map Window. It's shocking, I know. @@ -23,31 +22,31 @@ public class MapPanel extends JPanel { private static final long serialVersionUID = 1L; //defines how many pixels should be left as safety margin when calculating fit zooms - private static final int zoomFitSafetyMargin = 4; - + private static final int zoomFitSafetyMargin = 4; + private MapManager mmgr; private HexMap map; private HexMapImage mapImage; private JScrollPane scrollPane; - + private GameUIManager gameUIManager; - + private JLayeredPane layeredPane; private Dimension originalMapSize; private Dimension currentMapSize; - + //active fit-to zoom options private boolean fitToWidth = false; private boolean fitToHeight = false; protected static Logger log = - Logger.getLogger(MapPanel.class.getPackage().getName()); + Logger.getLogger(MapPanel.class.getPackage().getName()); public MapPanel(GameUIManager gameUIManager) { this.gameUIManager = gameUIManager; //Scale.set(15); Scale.set(16); - + setLayout(new BorderLayout()); mmgr = gameUIManager.getGameManager().getMapManager(); @@ -72,7 +71,7 @@ public class MapPanel extends JPanel { layeredPane.setPreferredSize(originalMapSize); map.setBounds(0, 0, originalMapSize.width, originalMapSize.height); map.addLayers(layeredPane, 1); - + if (mmgr.isMapImageUsed()) { mapImage = new HexMapImage (); mapImage.init(mmgr,map); @@ -80,14 +79,14 @@ public class MapPanel extends JPanel { mapImage.setBounds(0, 0, originalMapSize.width, originalMapSize.height); layeredPane.add(mapImage, -1); } - + scrollPane = new JScrollPane(layeredPane); scrollPane.setSize(originalMapSize); add(scrollPane, BorderLayout.CENTER); - + setSize(originalMapSize); setLocation(25, 25); - + //add listener for auto fit upon resize events addComponentListener(new ComponentAdapter() { @Override @@ -98,9 +97,11 @@ public class MapPanel extends JPanel { }); } - + public void scrollPaneShowRectangle(Rectangle rectangle) { - + + if (rectangle == null) return; + JViewport viewport = scrollPane.getViewport(); log.debug("ScrollPane viewPort =" + viewport); @@ -108,23 +109,23 @@ public class MapPanel extends JPanel { log.debug("Map size =" + map.getSize()); log.debug("ScrollPane visibleRect =" + scrollPane.getVisibleRect()); log.debug("viewport size =" + viewport.getSize()); - + double setX, setY; setX = Math.max(0, (rectangle.getCenterX() - viewport.getWidth() / 2)); setY = Math.max(0, (rectangle.getCenterY() - viewport.getHeight() / 2)); - + setX = Math.min(setX, Math.max(0, map.getSize().getWidth() - viewport.getWidth())); setY = Math.min(setY, Math.max(0, map.getSize().getHeight() - viewport.getHeight())); - + final Point viewPosition = new Point((int)setX, (int)setY); log.debug("ViewPosition for ScrollPane = " + viewPosition); SwingUtilities.invokeLater(new Runnable() { public void run() { - scrollPane.getViewport().setViewPosition(viewPosition); + scrollPane.getViewport().setViewPosition(viewPosition); } }); } - + public void setAllowedTileLays(List<LayTile> allowedTileLays) { map.setAllowedTileLays(allowedTileLays); } @@ -147,21 +148,21 @@ public class MapPanel extends JPanel { gameUIManager.getORUIManager().getORPanel().redrawRoutes(); layeredPane.revalidate(); } - + public void zoom (boolean in) { removeFitToOption(); map.zoom(in); adjustToNewMapZoom(); } - + /** * Zoom-to-fit functionality is based on the discrete zoom steps. * In order to achieve correctly fitting zoom, continuous adjustment factors are - * determined on top of that. + * determined on top of that. */ private void zoomFit (boolean fitToWidth, boolean fitToHeight) { if (!fitToWidth && !fitToHeight) return; - + ImageLoader imageLoader = GameUIManager.getImageLoader(); int zoomStep = map.getZoomStep(); @@ -179,7 +180,7 @@ public class MapPanel extends JPanel { //determine which dimension will be the critical one for the resize boolean isWidthCritical = ( !fitToHeight || (fitToWidth && idealFactorWidth < idealFactorHeight)); - + //check whether scrollbar will appear in the fit-to dimension and //reduce available size accordingly (not relevant for fit-to-window) if (isWidthCritical && idealFactorWidth > idealFactorHeight) { @@ -190,7 +191,7 @@ public class MapPanel extends JPanel { height -= scrollPane.getHorizontalScrollBar().getPreferredSize().height; idealFactorHeight = height / originalMapSize.height; } - + //abort resize if no space available if (width < 0 || height < 0) return; @@ -207,7 +208,7 @@ public class MapPanel extends JPanel { imageLoader.getZoomFactor(zoomStep+1) != imageLoader.getZoomFactor(zoomStep) ) zoomStep++; - + //decrease zoomFactor until constraints do hold //OR zoom cannot be decreased any more while @@ -221,44 +222,44 @@ public class MapPanel extends JPanel { imageLoader.getZoomFactor(zoomStep-1) != imageLoader.getZoomFactor(zoomStep) ) zoomStep--; - + //Determine and apply adjustment factor for precise fit double idealFactor = isWidthCritical ? idealFactorWidth : idealFactorHeight; imageLoader.setZoomAdjustmentFactor ( - idealFactor / imageLoader.getZoomFactor(zoomStep)); - + idealFactor / imageLoader.getZoomFactor(zoomStep)); + //trigger zoom execution map.setZoomStep(zoomStep); adjustToNewMapZoom(); } - + private void fitToOption (boolean fitToWidth, boolean fitToHeight) { //ignore if nothing has changed if (this.fitToWidth == fitToWidth && this.fitToHeight == fitToHeight ) return; - + this.fitToWidth = fitToWidth; this.fitToHeight = fitToHeight; zoomFit(fitToWidth, fitToHeight); } - + public void fitToWindow () { fitToOption (true, true); } - + public void fitToWidth () { fitToOption (true, false); } - + public void fitToHeight () { fitToOption (false, true); } - + public void removeFitToOption () { fitToWidth = false; fitToHeight = false; } - + public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_F1) { HelpWindow.displayHelp(gameUIManager.getHelp()); |
From: Erik V. <ev...@us...> - 2012-05-28 13:29:27
|
rails/ui/swing/elements/NonModalDialog.java | 1 + 1 file changed, 1 insertion(+) New commits: commit 3429f9f58e6993b09c89f7f56fd4a7230ef1ede9 Author: Erik Vos <eri...@xs...> Date: Mon May 28 15:28:49 2012 +0200 Fixed non-modal dialog bug during loading game. Non-modal dialogs try to center location on the 'parent' window, but centering fails if the parent is not visible. It is now also set visible beforehand. diff --git a/rails/ui/swing/elements/NonModalDialog.java b/rails/ui/swing/elements/NonModalDialog.java index 36d8581..15a3b37 100644 --- a/rails/ui/swing/elements/NonModalDialog.java +++ b/rails/ui/swing/elements/NonModalDialog.java @@ -83,6 +83,7 @@ public abstract class NonModalDialog extends JDialog implements ActionListener { pack(); // Center on owner + window.setVisible(true); // Window must be visible to find its location! int x = (int) window.getLocationOnScreen().getX() + (window.getWidth() - getWidth()) / 2; int y = (int) window.getLocationOnScreen().getY() |
From: Erik V. <ev...@us...> - 2012-06-14 13:47:39
|
rails/ui/swing/ORUIManager.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) New commits: commit ce10cb981aa82985380177433571aed4789f75ae Author: Erik Vos <eri...@xs...> Date: Thu Jun 14 15:44:15 2012 +0200 Fix to 1835 (etc.) token relay fix (previous commit). It failed in a typical 1830 Erie case. diff --git a/rails/ui/swing/ORUIManager.java b/rails/ui/swing/ORUIManager.java index 2252757..f3b6049 100644 --- a/rails/ui/swing/ORUIManager.java +++ b/rails/ui/swing/ORUIManager.java @@ -963,12 +963,14 @@ public class ORUIManager implements DialogOwner { if (stopsToQuery.size() == 2) { Collections.sort(stopsToQuery, new Comparator<Stop>() { public int compare (Stop s1, Stop s2) { - // Home stops on this hex go first. - boolean home1 = ((BaseToken)s1.getTokens().get(0)).getCompany().getHomeHexes().contains(hex); - boolean home2 = ((BaseToken)s2.getTokens().get(0)).getCompany().getHomeHexes().contains(hex); - if (home1 && !home2) { + List<TokenI> tokens; + boolean stop1IsHome = !((tokens = s1.getTokens()).isEmpty()) + && ((BaseToken)tokens.get(0)).getCompany().getHomeHexes().contains(hex); + boolean stop2IsHome = !((tokens = s2.getTokens()).isEmpty()) + && ((BaseToken)tokens.get(0)).getCompany().getHomeHexes().contains(hex); + if (stop1IsHome && !stop2IsHome) { return -1; - } else if (home2 && !home1) { + } else if (stop2IsHome && !stop1IsHome) { return 1; } else { return 0; // Doesn't matter |