Search in sources :

Example 36 with ComponentAdapter

use of java.awt.event.ComponentAdapter in project Spark by igniterealtime.

the class PreferenceDialog method invoke.

public void invoke(JFrame parentFrame, PreferencesPanel contentPane) {
    this.prefPanel = contentPane;
    // Construct main panel w/ layout.
    final JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BorderLayout());
    // Construct Dialog
    preferenceDialog = new JDialog(parentFrame, Res.getString("title.preferences"), false);
    preferenceDialog.setMinimumSize(new Dimension(600, 600));
    JButton btn_apply = new JButton(Res.getString("apply"));
    JButton btn_save = new JButton(Res.getString("save"));
    JButton btn_close = new JButton(Res.getString("close"));
    btn_close.addActionListener(e -> {
        preferenceDialog.setVisible(false);
        preferenceDialog.dispose();
    });
    btn_save.addActionListener(e -> {
        boolean okToClose = prefPanel.closing();
        if (okToClose) {
            preferenceDialog.setVisible(false);
            preferenceDialog.dispose();
        } else {
            pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
        }
    });
    btn_apply.addActionListener(e -> {
        boolean okToClose = prefPanel.closing();
        if (!okToClose) {
            pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
        }
    });
    Object[] options = { btn_apply, btn_save, btn_close };
    pane = new JOptionPane(contentPane, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);
    mainPanel.add(pane, BorderLayout.CENTER);
    preferenceDialog.setContentPane(mainPanel);
    preferenceDialog.pack();
    final Rectangle preferencesBounds = LayoutSettingsManager.getLayoutSettings().getPreferencesBounds();
    if (preferencesBounds == null || preferencesBounds.width <= 0 || preferencesBounds.height <= 0) {
        // Use default settings.
        preferenceDialog.setSize(750, 550);
        preferenceDialog.setLocationRelativeTo(SparkManager.getMainWindow());
    } else {
        preferenceDialog.setBounds(preferencesBounds);
    }
    pane.addPropertyChangeListener(this);
    preferenceDialog.setVisible(true);
    preferenceDialog.toFront();
    preferenceDialog.addComponentListener(new ComponentAdapter() {

        @Override
        public void componentResized(ComponentEvent e) {
            LayoutSettingsManager.getLayoutSettings().setPreferencesBounds(preferenceDialog.getBounds());
        }

        @Override
        public void componentMoved(ComponentEvent e) {
            LayoutSettingsManager.getLayoutSettings().setPreferencesBounds(preferenceDialog.getBounds());
        }
    });
}
Also used : ComponentEvent(java.awt.event.ComponentEvent) ComponentAdapter(java.awt.event.ComponentAdapter)

Example 37 with ComponentAdapter

use of java.awt.event.ComponentAdapter in project MtgDesktopCompanion by nicho92.

the class CollectionPanelGUI method initGUI.

public void initGUI() throws IOException, SQLException, ClassNotFoundException {
    logger.info("init collection GUI");
    MagicEditionsTableModel model;
    JProgressBar progressBar;
    JTabbedPane tabbedPane;
    TypeRepartitionPanel typeRepartitionPanel;
    ManaRepartitionPanel manaRepartitionPanel;
    RarityRepartitionPanel rarityRepartitionPanel;
    MagicCardDetailPanel magicCardDetailPanel;
    CardStockPanel statsPanel;
    JLabel lblTotal;
    // //////INIT COMPONENTS
    JPanel panneauHaut = new JPanel();
    JButton btnAdd = new JButton(MTGConstants.ICON_NEW);
    JButton btnRefresh = new JButton(MTGConstants.ICON_REFRESH);
    JButton btnRemove = new JButton(MTGConstants.ICON_DELETE);
    JButton btnAddAllSet = new JButton(MTGConstants.ICON_CHECK);
    JButton btnExport = new JButton(MTGConstants.ICON_EXPORT);
    JButton btnMassCollection = new JButton(MTGConstants.ICON_IMPORT);
    JButton btnExportPriceCatalog = new JButton(MTGConstants.ICON_EURO);
    JButton btnGenerateWebSite = new JButton(MTGConstants.ICON_WEBSITE);
    JScrollPane scrollPaneCollections = new JScrollPane();
    JScrollPane scrollPrices = new JScrollPane();
    JSplitPane splitListPanel = new JSplitPane();
    JSplitPane splitPane = new JSplitPane();
    JPanel panneauGauche = new JPanel();
    JScrollPane scrollPane = new JScrollPane();
    JPanel panelTotal = new JPanel();
    JPanel panneauDroite = new JPanel();
    MagicCollectionTableCellRenderer render = new MagicCollectionTableCellRenderer();
    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    progressBar = new JProgressBar();
    lblTotal = new JLabel();
    magicEditionDetailPanel = new MagicEditionDetailPanel(true, false);
    magicCardDetailPanel = new MagicCardDetailPanel();
    typeRepartitionPanel = new TypeRepartitionPanel();
    manaRepartitionPanel = new ManaRepartitionPanel();
    rarityRepartitionPanel = new RarityRepartitionPanel();
    statsPanel = new CardStockPanel();
    historyPricesPanel = new HistoryPricesPanel();
    jsonPanel = new JSONPanel();
    tree = new LazyLoadingTree();
    tableEditions = new JXTable();
    // //////MODELS
    model = new MagicEditionsTableModel();
    DefaultRowSorter sorterEditions = new TableRowSorter<DefaultTableModel>(model);
    modelPrices = new CardsPriceTableModel();
    tablePrices = new JXTable(modelPrices);
    model.init(provider.loadEditions());
    tableEditions.setModel(model);
    new TableFilterHeader(tableEditions, AutoChoices.ENABLED);
    // ///////CONFIGURE COMPONENTS
    splitListPanel.setDividerLocation(0.5);
    splitListPanel.setResizeWeight(0.5);
    progressBar.setVisible(false);
    btnRemove.setEnabled(true);
    btnExport.setEnabled(false);
    btnExportPriceCatalog.setEnabled(false);
    splitPane.setResizeWeight(0.5);
    splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
    scrollPaneCollections.setMinimumSize(new Dimension(0, 0));
    tree.setCellRenderer(new MagicCardsTreeCellRenderer());
    tablePrices.setColumnControlVisible(true);
    magicCardDetailPanel.setPreferredSize(new Dimension(0, 0));
    magicCardDetailPanel.enableThumbnail(true);
    tableEditions.setDefaultRenderer(Object.class, render);
    tableEditions.setDefaultRenderer(String.class, render);
    tableEditions.setDefaultRenderer(Integer.class, render);
    tableEditions.setDefaultRenderer(double.class, render);
    tableEditions.setRowHeight(25);
    tableEditions.setRowSorter(sorterEditions);
    // ///////LAYOUT
    setLayout(new BorderLayout(0, 0));
    panneauDroite.setLayout(new BorderLayout());
    panneauGauche.setLayout(new BorderLayout(0, 0));
    // ///////ADD PANELS
    add(panneauHaut, BorderLayout.NORTH);
    panneauHaut.add(btnAdd);
    panneauHaut.add(btnRefresh);
    panneauHaut.add(btnRemove);
    panneauHaut.add(btnAddAllSet);
    panneauHaut.add(btnMassCollection);
    panneauHaut.add(btnExport);
    panneauHaut.add(btnExportPriceCatalog);
    panneauHaut.add(btnGenerateWebSite);
    panneauHaut.add(progressBar);
    add(splitListPanel, BorderLayout.CENTER);
    splitListPanel.setRightComponent(panneauDroite);
    panneauDroite.add(splitPane, BorderLayout.CENTER);
    splitPane.setLeftComponent(scrollPaneCollections);
    scrollPaneCollections.setViewportView(tree);
    splitPane.setRightComponent(tabbedPane);
    scrollPrices.setViewportView(tablePrices);
    splitListPanel.setLeftComponent(panneauGauche);
    panneauGauche.add(scrollPane);
    scrollPane.setViewportView(tableEditions);
    panneauGauche.add(panelTotal, BorderLayout.SOUTH);
    panelTotal.add(lblTotal);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("DETAILS"), null, magicCardDetailPanel, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("CARD_EDITIONS"), null, magicEditionDetailPanel, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("PRICES"), null, scrollPrices, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("CARD_TYPES"), null, typeRepartitionPanel, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("CARD_MANA"), null, manaRepartitionPanel, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("CARD_RARITY"), null, rarityRepartitionPanel, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("STOCK_MODULE"), null, statsPanel, null);
    tabbedPane.addTab(MTGControler.getInstance().getLangService().getCapitalize("PRICE_VARIATIONS"), null, historyPricesPanel, null);
    if (MTGControler.getInstance().get("debug-json-panel").equalsIgnoreCase("true"))
        tabbedPane.addTab("Json", null, jsonPanel, null);
    // ///////Labels
    lblTotal.setText("Total : " + model.getCountDefaultLibrary() + "/" + model.getCountTotal());
    btnAdd.setToolTipText(MTGControler.getInstance().getLangService().get("COLLECTION_ADD"));
    btnRefresh.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("COLLECTION_REFRESH"));
    btnRemove.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("ITEM_SELECTED_REMOVE"));
    btnAddAllSet.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("COLLECTION_SET_FULL"));
    btnExport.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("EXPORT_AS"));
    btnMassCollection.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("COLLECTION_IMPORT"));
    btnExportPriceCatalog.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("COLLECTION_EXPORT_PRICES"));
    btnGenerateWebSite.setToolTipText(MTGControler.getInstance().getLangService().getCapitalize("GENERATE_WEBSITE"));
    List<SortKey> keys = new ArrayList<>();
    // column index 2
    SortKey sortKey = new SortKey(3, SortOrder.DESCENDING);
    keys.add(sortKey);
    sorterEditions.setSortKeys(keys);
    tableEditions.packAll();
    initPopupCollection();
    tableEditions.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent arg0) {
            int row = tableEditions.getSelectedRow();
            MagicEdition ed = (MagicEdition) tableEditions.getValueAt(row, 1);
            magicEditionDetailPanel.setMagicEdition(ed);
            historyPricesPanel.init(null, ed, ed.getSet());
            jsonPanel.show(ed);
        }
    });
    btnAdd.addActionListener(e -> {
        String name = JOptionPane.showInputDialog(MTGControler.getInstance().getLangService().getCapitalize("NAME") + " ?");
        MagicCollection collectionAdd = new MagicCollection();
        collectionAdd.setName(name);
        try {
            dao.saveCollection(collectionAdd);
            ((LazyLoadingTree.MyNode) getJTree().getModel().getRoot()).add(new DefaultMutableTreeNode(collectionAdd));
            getJTree().refresh();
            initPopupCollection();
        } catch (Exception ex) {
            logger.error(ex);
            JOptionPane.showMessageDialog(null, ex, MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
        }
    });
    btnRefresh.addActionListener(e -> ThreadManager.getInstance().execute(() -> {
        progressBar.setVisible(true);
        tree.refresh();
        try {
            model.calculate();
            lblTotal.setText("Total : " + model.getCountDefaultLibrary() + "/" + model.getCountTotal());
        } catch (Exception ex) {
            logger.error(ex);
        }
        model.fireTableDataChanged();
        progressBar.setVisible(false);
    }, "update Tree"));
    btnExport.addActionListener(ae -> {
        JPopupMenu menu = new JPopupMenu();
        for (final MTGCardsExport exp : MTGControler.getInstance().getEnabledDeckExports()) {
            JMenuItem it = new JMenuItem();
            it.setIcon(exp.getIcon());
            it.setText(exp.getName());
            it.addActionListener(arg0 -> ThreadManager.getInstance().execute(() -> {
                try {
                    DefaultMutableTreeNode curr = (DefaultMutableTreeNode) path.getLastPathComponent();
                    JFileChooser jf = new JFileChooser();
                    MagicCollection mc = null;
                    MagicEdition ed = null;
                    if (curr.getUserObject() instanceof MagicEdition) {
                        ed = (MagicEdition) curr.getUserObject();
                        mc = (MagicCollection) ((DefaultMutableTreeNode) curr.getParent()).getUserObject();
                    } else {
                        mc = (MagicCollection) curr.getUserObject();
                    }
                    jf.setSelectedFile(new File(mc.getName() + exp.getFileExtension()));
                    int result = jf.showSaveDialog(null);
                    File f = jf.getSelectedFile();
                    exp.addObserver((Observable o, Object arg) -> progressBar.setValue((int) arg));
                    if (result == JFileChooser.APPROVE_OPTION) {
                        progressBar.setVisible(true);
                        if (ed == null)
                            exp.export(dao.listCardsFromCollection(mc), f);
                        else
                            exp.export(dao.listCardsFromCollection(mc, ed), f);
                        progressBar.setVisible(false);
                        JOptionPane.showMessageDialog(null, MTGControler.getInstance().getLangService().combine("EXPORT", "FINISHED"), MTGControler.getInstance().getLangService().getCapitalize("FINISHED"), JOptionPane.INFORMATION_MESSAGE);
                    }
                } catch (Exception e) {
                    logger.error(e);
                    progressBar.setVisible(false);
                    JOptionPane.showMessageDialog(null, e, MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
                }
            }, "export collection with " + exp));
            menu.add(it);
        }
        Component b = (Component) ae.getSource();
        Point p = b.getLocationOnScreen();
        menu.show(b, 0, 0);
        menu.setLocation(p.x, p.y + b.getHeight());
    });
    splitPane.addComponentListener(new ComponentAdapter() {

        @Override
        public void componentShown(ComponentEvent componentEvent) {
            splitPane.setDividerLocation(.5);
            removeComponentListener(this);
        }
    });
    tablePrices.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent ev) {
            if (ev.getClickCount() == 2 && !ev.isConsumed()) {
                ev.consume();
                try {
                    String url = tablePrices.getValueAt(tablePrices.getSelectedRow(), CardsPriceTableModel.ROW_URL).toString();
                    Desktop.getDesktop().browse(new URI(url));
                } catch (Exception e) {
                    logger.error(e);
                }
            }
        }
    });
    tree.addTreeSelectionListener(tse -> {
        path = tse.getPath();
        final DefaultMutableTreeNode curr = (DefaultMutableTreeNode) path.getLastPathComponent();
        if (curr.getUserObject() instanceof String) {
            btnExport.setEnabled(false);
            btnExportPriceCatalog.setEnabled(false);
            statsPanel.enabledAdd(false);
        }
        if (curr.getUserObject() instanceof MagicCollection) {
            btnExport.setEnabled(true);
            btnExportPriceCatalog.setEnabled(true);
            selectedcol = (MagicCollection) curr.getUserObject();
            statsPanel.enabledAdd(false);
            btnExport.setEnabled(true);
            btnExportPriceCatalog.setEnabled(true);
        }
        if (curr.getUserObject() instanceof MagicEdition) {
            magicEditionDetailPanel.setMagicEdition((MagicEdition) curr.getUserObject());
            btnExport.setEnabled(true);
            btnExportPriceCatalog.setEnabled(false);
            statsPanel.enabledAdd(false);
            ThreadManager.getInstance().execute(() -> {
                try {
                    MagicCollection collec = (MagicCollection) ((DefaultMutableTreeNode) curr.getParent()).getUserObject();
                    List<MagicCard> list = dao.listCardsFromCollection(collec, (MagicEdition) curr.getUserObject());
                    rarityRepartitionPanel.init(list);
                    typeRepartitionPanel.init(list);
                    manaRepartitionPanel.init(list);
                    historyPricesPanel.init(null, (MagicEdition) curr.getUserObject(), curr.getUserObject().toString());
                    jsonPanel.show(curr.getUserObject());
                } catch (Exception e) {
                    logger.error(e);
                }
            }, "Refresh Collection");
        }
        if (curr.getUserObject() instanceof MagicCard) {
            final MagicCard card = (MagicCard) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
            btnExport.setEnabled(false);
            btnExportPriceCatalog.setEnabled(false);
            magicCardDetailPanel.setMagicCard((MagicCard) curr.getUserObject());
            magicEditionDetailPanel.setMagicEdition(card.getEditions().get(0));
            magicCardDetailPanel.enableThumbnail(true);
            jsonPanel.show(curr.getUserObject());
            ThreadManager.getInstance().execute(() -> {
                statsPanel.initMagicCardStock(card, (MagicCollection) ((DefaultMutableTreeNode) curr.getParent().getParent()).getUserObject());
                statsPanel.enabledAdd(true);
            }, "Update Collection");
            if (tabbedPane.getSelectedIndex() == 2) {
                loadPrices(card);
            }
            ThreadManager.getInstance().execute(() -> {
                try {
                    historyPricesPanel.init(card, null, card.getName());
                } catch (Exception e) {
                    logger.error(e);
                }
            }, "update history");
        }
    });
    tabbedPane.addChangeListener(e -> {
        if ((tabbedPane.getSelectedIndex() == 2) && ((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()).getUserObject() instanceof MagicCard)
            loadPrices((MagicCard) ((DefaultMutableTreeNode) tree.getLastSelectedPathComponent()).getUserObject());
    });
    tree.addMouseListener(new MouseAdapter() {

        @Override
        public void mouseClicked(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                int row = tree.getClosestRowForLocation(e.getX(), e.getY());
                tree.setSelectionRow(row);
                final DefaultMutableTreeNode node = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
                if (node.getUserObject() instanceof MagicEdition) {
                    popupMenuEdition.show(e.getComponent(), e.getX(), e.getY());
                }
                if (node.getUserObject() instanceof MagicCard) {
                    popupMenuCards.show(e.getComponent(), e.getX(), e.getY());
                }
                if (node.getUserObject() instanceof MagicCollection) {
                    JPopupMenu p = new JPopupMenu();
                    JMenuItem it = new JMenuItem("Mass movement");
                    p.add(it);
                    it.addActionListener(ae -> {
                        MassMoverDialog d = new MassMoverDialog((MagicCollection) node.getUserObject(), null);
                        d.setVisible(true);
                        logger.debug("closing mass import with change =" + d.hasChange());
                    });
                    p.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        }
    });
    btnMassCollection.addActionListener(ae -> {
        MassCollectionImporterDialog diag = new MassCollectionImporterDialog();
        diag.setVisible(true);
        try {
            model.calculate();
        } catch (Exception e) {
            logger.error(e);
        }
        model.fireTableDataChanged();
    });
    btnExportPriceCatalog.addActionListener(ae -> ThreadManager.getInstance().execute(() -> {
        try {
            PriceCatalogExportDialog diag = new PriceCatalogExportDialog(selectedcol);
            diag.setVisible(true);
            if (diag.value()) {
                progressBar.setVisible(true);
                progressBar.setStringPainted(true);
                progressBar.setMinimum(0);
                progressBar.setMaximum(dao.getCardsCount(selectedcol, null));
                CSVExport exp = new CSVExport();
                exp.addObserver((Observable o, Object arg) -> progressBar.setValue((int) arg));
                exp.exportPriceCatalog(dao.listCardsFromCollection(selectedcol), diag.getDest(), diag.getPriceProviders());
                JOptionPane.showMessageDialog(null, MTGControler.getInstance().getLangService().combine("EXPORT", "FINISHED"));
                progressBar.setVisible(false);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }, "btnExportPriceCatalog export Prices"));
    btnGenerateWebSite.addActionListener(ae -> ThreadManager.getInstance().execute(() -> {
        try {
            WebSiteGeneratorDialog diag = new WebSiteGeneratorDialog(dao.getCollections());
            diag.setVisible(true);
            if (diag.value()) {
                progressBar.setVisible(true);
                progressBar.setStringPainted(true);
                progressBar.setMinimum(0);
                int max = 0;
                for (MagicCollection col : diag.getSelectedCollections()) max += dao.getCardsCount(col, null);
                progressBar.setMaximum(max);
                progressBar.setValue(0);
                MagicWebSiteGenerator gen = new MagicWebSiteGenerator(diag.getTemplate(), diag.getDest().getAbsolutePath());
                gen.addObserver((Observable o, Object arg) -> progressBar.setValue((int) arg));
                gen.generate(diag.getSelectedCollections(), diag.getPriceProviders());
                int res = JOptionPane.showConfirmDialog(null, MTGControler.getInstance().getLangService().getCapitalize("WEBSITE_CONFIRMATION_VIEW"));
                if (res == JOptionPane.YES_OPTION) {
                    Path p = Paths.get(diag.getDest().getAbsolutePath() + "/index.htm");
                    Desktop.getDesktop().browse(p.toUri());
                }
                progressBar.setVisible(false);
            }
        } catch (Exception e) {
            logger.error("error generating website", e);
            progressBar.setVisible(false);
            JOptionPane.showMessageDialog(null, e, MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
        }
    }, "btnGenerateWebSite generate website"));
    btnAddAllSet.addActionListener(evt -> {
        MagicEdition ed = (MagicEdition) tableEditions.getValueAt(tableEditions.getSelectedRow(), 1);
        int res = JOptionPane.showConfirmDialog(null, MTGControler.getInstance().getLangService().getCapitalize("CONFIRM_COLLECTION_ITEM_ADDITION", ed, MTGControler.getInstance().get("default-library")));
        if (res == JOptionPane.YES_OPTION)
            try {
                List<MagicCard> list = provider.searchCardByCriteria("set", ed.getId(), null, false);
                logger.debug("save " + list.size() + " cards from " + ed.getId());
                for (MagicCard mc : list) {
                    MagicCollection col = new MagicCollection();
                    col.setName(MTGControler.getInstance().get("default-library"));
                    dao.saveCard(mc, col);
                }
                model.calculate();
                model.fireTableDataChanged();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
                logger.error(e);
            }
    });
    btnRemove.addActionListener(evt -> {
        MagicCollection col = (MagicCollection) ((DefaultMutableTreeNode) path.getPathComponent(1)).getUserObject();
        int res = 0;
        DefaultMutableTreeNode curr = (DefaultMutableTreeNode) path.getLastPathComponent();
        if (curr.getUserObject() instanceof MagicCard) {
            MagicCard card = (MagicCard) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject();
            try {
                res = JOptionPane.showConfirmDialog(null, MTGControler.getInstance().getLangService().getCapitalize("CONFIRM_COLLECTION_ITEM_DELETE", card, col));
                if (res == JOptionPane.YES_OPTION) {
                    dao.removeCard(card, col);
                    curr.removeFromParent();
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
            }
        }
        if (curr.getUserObject() instanceof MagicEdition) {
            MagicEdition me = (MagicEdition) ((DefaultMutableTreeNode) path.getPathComponent(2)).getUserObject();
            try {
                res = JOptionPane.showConfirmDialog(null, MTGControler.getInstance().getLangService().getCapitalize("CONFIRM_COLLECTION_ITEM_DELETE", me, col));
                if (res == JOptionPane.YES_OPTION) {
                    dao.removeEdition(me, col);
                    curr.removeFromParent();
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
            }
        }
        if (curr.getUserObject() instanceof MagicCollection) {
            try {
                res = JOptionPane.showConfirmDialog(null, MTGControler.getInstance().getLangService().getCapitalize("CONFIRM_COLLECTION_DELETE", col, dao.getCardsCount(col, null)));
                if (res == JOptionPane.YES_OPTION) {
                    dao.removeCollection(col);
                    curr.removeFromParent();
                }
            } catch (SQLException e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
            }
        }
        if (res == JOptionPane.YES_OPTION) {
            try {
                model.calculate();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e.getMessage(), MTGControler.getInstance().getLangService().getError(), JOptionPane.ERROR_MESSAGE);
            }
            tree.refresh();
        }
    });
}
Also used : MagicCollection(org.magic.api.beans.MagicCollection) Point(java.awt.Point) MTGDao(org.magic.api.interfaces.MTGDao) RarityRepartitionPanel(org.magic.gui.components.charts.RarityRepartitionPanel) Logger(org.apache.log4j.Logger) TableFilterHeader(net.coderazzi.filters.gui.TableFilterHeader) MouseAdapter(java.awt.event.MouseAdapter) URI(java.net.URI) JFileChooser(javax.swing.JFileChooser) PriceCatalogExportDialog(org.magic.gui.components.dialog.PriceCatalogExportDialog) WebSiteGeneratorDialog(org.magic.gui.components.dialog.WebSiteGeneratorDialog) BorderLayout(java.awt.BorderLayout) Path(java.nio.file.Path) CSVExport(org.magic.api.exports.impl.CSVExport) MTGCardsProvider(org.magic.api.interfaces.MTGCardsProvider) TypeRepartitionPanel(org.magic.gui.components.charts.TypeRepartitionPanel) DefaultTableModel(javax.swing.table.DefaultTableModel) TreePath(javax.swing.tree.TreePath) MagicCardsTreeCellRenderer(org.magic.gui.renderer.MagicCardsTreeCellRenderer) JMenu(javax.swing.JMenu) ComponentEvent(java.awt.event.ComponentEvent) Component(java.awt.Component) TableRowSorter(javax.swing.table.TableRowSorter) JXTable(org.jdesktop.swingx.JXTable) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) CardsPriceTableModel(org.magic.gui.models.CardsPriceTableModel) HistoryPricesPanel(org.magic.gui.components.charts.HistoryPricesPanel) Dimension(java.awt.Dimension) List(java.util.List) MagicEdition(org.magic.api.beans.MagicEdition) MagicCard(org.magic.api.beans.MagicCard) MagicCardDetailPanel(org.magic.gui.components.MagicCardDetailPanel) JPanel(javax.swing.JPanel) DefaultRowSorter(javax.swing.DefaultRowSorter) JSplitPane(javax.swing.JSplitPane) MassCollectionImporterDialog(org.magic.gui.components.dialog.MassCollectionImporterDialog) Observable(org.utils.patterns.observer.Observable) MTGControler(org.magic.services.MTGControler) SortKey(javax.swing.RowSorter.SortKey) CardStockPanel(org.magic.gui.components.CardStockPanel) MagicEditionDetailPanel(org.magic.gui.components.MagicEditionDetailPanel) ArrayList(java.util.ArrayList) SQLException(java.sql.SQLException) SwingUtilities(javax.swing.SwingUtilities) JMenuItem(javax.swing.JMenuItem) JTabbedPane(javax.swing.JTabbedPane) JProgressBar(javax.swing.JProgressBar) JSONPanel(org.magic.gui.components.JSONPanel) MagicCollectionTableCellRenderer(org.magic.gui.renderer.MagicCollectionTableCellRenderer) ManaRepartitionPanel(org.magic.gui.components.charts.ManaRepartitionPanel) Desktop(java.awt.Desktop) LazyLoadingTree(org.magic.gui.components.LazyLoadingTree) MTGLogger(org.magic.services.MTGLogger) JButton(javax.swing.JButton) JPopupMenu(javax.swing.JPopupMenu) MTGCardsExport(org.magic.api.interfaces.MTGCardsExport) IOException(java.io.IOException) JOptionPane(javax.swing.JOptionPane) CardSearchPanel(org.magic.gui.components.CardSearchPanel) MouseEvent(java.awt.event.MouseEvent) File(java.io.File) ComponentAdapter(java.awt.event.ComponentAdapter) JScrollPane(javax.swing.JScrollPane) SortOrder(javax.swing.SortOrder) MagicWebSiteGenerator(org.magic.services.MagicWebSiteGenerator) Paths(java.nio.file.Paths) JLabel(javax.swing.JLabel) ThreadManager(org.magic.services.ThreadManager) AutoChoices(net.coderazzi.filters.gui.AutoChoices) MagicEditionsTableModel(org.magic.gui.models.MagicEditionsTableModel) MassMoverDialog(org.magic.gui.components.dialog.MassMoverDialog) MTGConstants(org.magic.services.MTGConstants) JPanel(javax.swing.JPanel) ArrayList(java.util.ArrayList) MagicEdition(org.magic.api.beans.MagicEdition) CardsPriceTableModel(org.magic.gui.models.CardsPriceTableModel) WebSiteGeneratorDialog(org.magic.gui.components.dialog.WebSiteGeneratorDialog) MassMoverDialog(org.magic.gui.components.dialog.MassMoverDialog) BorderLayout(java.awt.BorderLayout) CardStockPanel(org.magic.gui.components.CardStockPanel) PriceCatalogExportDialog(org.magic.gui.components.dialog.PriceCatalogExportDialog) List(java.util.List) ArrayList(java.util.ArrayList) MagicCollection(org.magic.api.beans.MagicCollection) MassCollectionImporterDialog(org.magic.gui.components.dialog.MassCollectionImporterDialog) JXTable(org.jdesktop.swingx.JXTable) MagicCardDetailPanel(org.magic.gui.components.MagicCardDetailPanel) ManaRepartitionPanel(org.magic.gui.components.charts.ManaRepartitionPanel) JFileChooser(javax.swing.JFileChooser) ComponentEvent(java.awt.event.ComponentEvent) JSplitPane(javax.swing.JSplitPane) File(java.io.File) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) SQLException(java.sql.SQLException) JTabbedPane(javax.swing.JTabbedPane) MTGCardsExport(org.magic.api.interfaces.MTGCardsExport) JProgressBar(javax.swing.JProgressBar) JButton(javax.swing.JButton) MagicEditionDetailPanel(org.magic.gui.components.MagicEditionDetailPanel) SortKey(javax.swing.RowSorter.SortKey) URI(java.net.URI) HistoryPricesPanel(org.magic.gui.components.charts.HistoryPricesPanel) JMenuItem(javax.swing.JMenuItem) Component(java.awt.Component) TableRowSorter(javax.swing.table.TableRowSorter) ComponentAdapter(java.awt.event.ComponentAdapter) JScrollPane(javax.swing.JScrollPane) Path(java.nio.file.Path) TreePath(javax.swing.tree.TreePath) MouseEvent(java.awt.event.MouseEvent) MagicCollectionTableCellRenderer(org.magic.gui.renderer.MagicCollectionTableCellRenderer) MouseAdapter(java.awt.event.MouseAdapter) JLabel(javax.swing.JLabel) RarityRepartitionPanel(org.magic.gui.components.charts.RarityRepartitionPanel) LazyLoadingTree(org.magic.gui.components.LazyLoadingTree) DefaultRowSorter(javax.swing.DefaultRowSorter) CSVExport(org.magic.api.exports.impl.CSVExport) TableFilterHeader(net.coderazzi.filters.gui.TableFilterHeader) Dimension(java.awt.Dimension) MagicCardsTreeCellRenderer(org.magic.gui.renderer.MagicCardsTreeCellRenderer) Point(java.awt.Point) MagicEditionsTableModel(org.magic.gui.models.MagicEditionsTableModel) TypeRepartitionPanel(org.magic.gui.components.charts.TypeRepartitionPanel) SQLException(java.sql.SQLException) IOException(java.io.IOException) JPopupMenu(javax.swing.JPopupMenu) Observable(org.utils.patterns.observer.Observable) Point(java.awt.Point) MagicCard(org.magic.api.beans.MagicCard) MagicWebSiteGenerator(org.magic.services.MagicWebSiteGenerator) JSONPanel(org.magic.gui.components.JSONPanel)

Example 38 with ComponentAdapter

use of java.awt.event.ComponentAdapter in project tetrad by cmu-phil.

the class SessionEditorNode method addListeners.

private void addListeners(final SessionEditorNode sessionEditorNode, final SessionNodeWrapper modelNode) {
    // Add a mouse listener for popups.
    sessionEditorNode.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            if (SwingUtilities.isRightMouseButton(e)) {
                ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
                toolTipManager.setInitialDelay(750);
                sessionEditorNode.getPopup().show(sessionEditorNode, e.getX(), e.getY());
            }
            e.consume();
        }
    });
    // sessionEditorNode.addMouseMotionListener(new MouseMotionAdapter() {
    // public void mouseMoved(MouseEvent e) {
    // Point p = e.getPoint();
    // if (p.getX() > 40 && p.getY() > 40) {
    // ToolTipManager toolTipManager =
    // ToolTipManager.sharedInstance();
    // toolTipManager.setInitialDelay(750);
    // JPopupMenu popup = sessionEditorNode.getPopup();
    // 
    // if (!popup.isShowing()) {
    // popup.show(sessionEditorNode, e.getX(), e.getY());
    // }
    // }
    // }
    // });
    sessionEditorNode.addComponentListener(new ComponentAdapter() {

        @Override
        public void componentMoved(ComponentEvent e) {
            sessionEditorNode.getSimulationStudy().getSession().setSessionChanged(true);
        }
    });
    SessionNode sessionNode = modelNode.getSessionNode();
    sessionNode.addSessionListener(new SessionAdapter() {

        @Override
        public void modelCreated(SessionEvent sessionEvent) {
            sessionEditorNode.adjustToModel();
            // 5/18/02
            if (sessionEditorNode.spawnedEditor() != null) {
                EditorWindow editorWindow = sessionEditorNode.spawnedEditor();
                editorWindow.closeDialog();
            }
        }

        @Override
        public void modelDestroyed(SessionEvent sessionEvent) {
            sessionEditorNode.adjustToModel();
            // the getModel editor window is closed. jdramsey 5/18/02
            if (sessionEditorNode.spawnedEditor() != null) {
                EditorWindow editorWindow = sessionEditorNode.spawnedEditor();
                editorWindow.closeDialog();
            }
        }

        @Override
        public void modelUnclear(SessionEvent sessionEvent) {
            try {
                if (simulationStudy == null) {
                    boolean created = sessionEditorNode.createModel(false);
                    if (!created) {
                        return;
                    }
                    sessionEditorNode.adjustToModel();
                }
            } catch (Exception e) {
                String message = e.getMessage();
                message = "I could not make a model for this box, sorry. Maybe the \n" + "parents aren't right or have not been constructed yet.";
                e.printStackTrace();
                // throw new IllegalArgumentException("I could not make a model for this box, sorry. Maybe the \n" +
                // "parents aren't right or have not been constructed yet.");
                JOptionPane.showMessageDialog(sessionEditorNode, message);
            }
        }
    });
}
Also used : ToolTipManager(javax.swing.ToolTipManager) SessionEvent(edu.cmu.tetrad.session.SessionEvent) MouseEvent(java.awt.event.MouseEvent) MouseAdapter(java.awt.event.MouseAdapter) SessionNode(edu.cmu.tetrad.session.SessionNode) ComponentEvent(java.awt.event.ComponentEvent) SessionAdapter(edu.cmu.tetrad.session.SessionAdapter) ComponentAdapter(java.awt.event.ComponentAdapter) CouldNotCreateModelException(edu.cmu.tetrad.session.CouldNotCreateModelException) EditorWindow(edu.cmu.tetradapp.editor.EditorWindow)

Example 39 with ComponentAdapter

use of java.awt.event.ComponentAdapter in project grafikon by jub77.

the class GuiContextImpl method registerWindow.

@Override
public void registerWindow(String key, Window window, GuiContextDataListener listener) {
    window.addWindowListener(new WindowAdapter() {

        @Override
        public void windowClosed(WindowEvent e) {
            putToDataMap(key, window, listener);
        }
    });
    window.addComponentListener(new ComponentAdapter() {

        @Override
        public void componentHidden(ComponentEvent e) {
            putToDataMap(key, window, listener);
        }
    });
    if (dataMap.containsKey(key)) {
        dataMap.get(key).applyTo(window);
    }
    if (listener != null) {
        Map<String, String> map = null;
        if (preferencesMap.containsKey(key)) {
            map = preferencesMap.get(key);
        } else {
            map = new HashMap<>();
            preferences.getSection(key).copyToMap(map);
        }
        if (map == null) {
            map = Collections.emptyMap();
        }
        listener.init(map);
    }
}
Also used : WindowEvent(java.awt.event.WindowEvent) WindowAdapter(java.awt.event.WindowAdapter) ComponentEvent(java.awt.event.ComponentEvent) ComponentAdapter(java.awt.event.ComponentAdapter)

Example 40 with ComponentAdapter

use of java.awt.event.ComponentAdapter in project gate-core by GateNLP.

the class MainFrame method initListeners.

protected void initListeners() {
    Gate.getCreoleRegister().addCreoleListener(this);
    Gate.getCreoleRegister().addPluginListener(this);
    resourcesTree.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent e) {
            if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                // shows in the central tabbed pane, the selected resources
                // in the resource tree when the Enter key is pressed
                (new ShowSelectedResourcesAction()).actionPerformed(null);
            } else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                // close selected resources from GATE
                (new CloseSelectedResourcesAction()).actionPerformed(null);
            } else if (e.getKeyCode() == KeyEvent.VK_DELETE && e.getModifiers() == InputEvent.SHIFT_DOWN_MASK) {
                // close recursively selected resources from GATE
                (new CloseRecursivelySelectedResourcesAction()).actionPerformed(null);
            }
        }
    });
    resourcesTree.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            TreePath path = resourcesTree.getClosestPathForLocation(e.getX(), e.getY());
            if (e.isPopupTrigger() && !resourcesTree.isPathSelected(path)) {
                // if right click outside the selection then reset selection
                resourcesTree.getSelectionModel().setSelectionPath(path);
            }
            processMouseEvent(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            // where inside the tree?
            int x = e.getX();
            int y = e.getY();
            TreePath path = resourcesTree.getClosestPathForLocation(x, y);
            JPopupMenu popup = null;
            Handle handle = null;
            if (path != null) {
                Object value = path.getLastPathComponent();
                if (value == resourcesTreeRoot) {
                // no default item for this menu
                } else if (value == applicationsRoot) {
                    appsPopup = new XJPopupMenu();
                    LiveMenu appsMenu = new LiveMenu(LiveMenu.APP);
                    appsMenu.setText("Create New Application");
                    appsMenu.setIcon(MainFrame.getIcon("applications"));
                    appsPopup.add(appsMenu);
                    appsPopup.add(new ReadyMadeMenu());
                    appsPopup.add(new XJMenuItem(new LoadResourceFromFileAction(), MainFrame.this));
                    RecentAppsMenu recentApps = new RecentAppsMenu();
                    if (recentApps.getMenuComponentCount() > 0)
                        appsPopup.add(recentApps);
                    popup = appsPopup;
                } else if (value == languageResourcesRoot) {
                    popup = lrsPopup;
                } else if (value == processingResourcesRoot) {
                    popup = prsPopup;
                } else if (value == datastoresRoot) {
                    popup = dssPopup;
                } else {
                    value = ((DefaultMutableTreeNode) value).getUserObject();
                    if (value instanceof Handle) {
                        handle = (Handle) value;
                        fileChooser.setResource(handle.getTarget().getClass().getName());
                        if (e.isPopupTrigger()) {
                            popup = handle.getPopup();
                        }
                    }
                }
            }
            // popup menu
            if (e.isPopupTrigger()) {
                if (resourcesTree.getSelectionCount() > 1) {
                    // multiple selection in tree
                    popup = new XJPopupMenu();
                    // add a close all action
                    popup.add(new XJMenuItem(new CloseSelectedResourcesAction(), MainFrame.this));
                    // add a close recursively all action
                    TreePath[] selectedPaths = resourcesTree.getSelectionPaths();
                    for (TreePath selectedPath : selectedPaths) {
                        Object userObject = ((DefaultMutableTreeNode) selectedPath.getLastPathComponent()).getUserObject();
                        if (userObject instanceof NameBearerHandle && ((NameBearerHandle) userObject).getTarget() instanceof Controller) {
                            // there is at least one application
                            popup.add(new XJMenuItem(new CloseRecursivelySelectedResourcesAction(), MainFrame.this));
                            break;
                        }
                    }
                    // add a show all action
                    selectedPaths = resourcesTree.getSelectionPaths();
                    for (TreePath selectedPath : selectedPaths) {
                        Object userObject = ((DefaultMutableTreeNode) selectedPath.getLastPathComponent()).getUserObject();
                        if (userObject instanceof Handle && (!((Handle) userObject).viewsBuilt() || (mainTabbedPane.indexOfComponent(((Handle) userObject).getLargeView()) == -1))) {
                            // there is at least one resource not shown
                            popup.add(new XJMenuItem(new ShowSelectedResourcesAction(), MainFrame.this));
                            break;
                        }
                    }
                    // add a hide all action
                    selectedPaths = resourcesTree.getSelectionPaths();
                    for (TreePath selectedPath : selectedPaths) {
                        Object userObject = ((DefaultMutableTreeNode) selectedPath.getLastPathComponent()).getUserObject();
                        if (userObject instanceof Handle && ((Handle) userObject).viewsBuilt() && ((Handle) userObject).getLargeView() != null && (mainTabbedPane.indexOfComponent(((Handle) userObject).getLargeView()) != -1)) {
                            // there is at least one resource shown
                            popup.add(new XJMenuItem(new CloseViewsForSelectedResourcesAction(), MainFrame.this));
                            break;
                        }
                    }
                    popup.show(resourcesTree, e.getX(), e.getY());
                } else if (popup != null) {
                    if (handle != null) {
                        // add a close action
                        if (handle instanceof NameBearerHandle) {
                            popup.insert(new XJMenuItem(((NameBearerHandle) handle).getCloseAction(), MainFrame.this), 0);
                        }
                        // if application then add a close recursively action
                        if (handle instanceof NameBearerHandle && handle.getTarget() instanceof Controller) {
                            popup.insert(new XJMenuItem(((NameBearerHandle) handle).getCloseRecursivelyAction(), MainFrame.this), 1);
                        }
                        // add a show/hide action
                        if (handle.viewsBuilt() && handle.getLargeView() != null && (mainTabbedPane.indexOfComponent(handle.getLargeView()) != -1)) {
                            popup.insert(new XJMenuItem(new CloseViewAction(handle), MainFrame.this), 2);
                        } else {
                            popup.insert(new XJMenuItem(new ShowResourceAction(handle), MainFrame.this), 2);
                        }
                        // add a rename action
                        popup.insert(new XJMenuItem(new RenameResourceAction(path), MainFrame.this), 3);
                        // add a help action
                        if (handle instanceof NameBearerHandle) {
                            popup.insert(new XJMenuItem(new HelpOnItemTreeAction((NameBearerHandle) handle), MainFrame.this), 4);
                        }
                    }
                    popup.show(resourcesTree, e.getX(), e.getY());
                }
            } else if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() == 2 && handle != null) {
                // double click - show the resource
                select(handle);
            }
        }
    });
    resourcesTree.addTreeSelectionListener(new TreeSelectionListener() {

        @Override
        public void valueChanged(TreeSelectionEvent e) {
            if (!Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".treeselectview")) {
                return;
            }
            // the resource tree selection
            if (resourcesTree.getSelectionPaths() != null && resourcesTree.getSelectionPaths().length == 1) {
                Object value = e.getPath().getLastPathComponent();
                Object object = ((DefaultMutableTreeNode) value).getUserObject();
                if (object instanceof Handle && ((Handle) object).viewsBuilt() && (mainTabbedPane.indexOfComponent(((Handle) object).getLargeView()) != -1)) {
                    select((Handle) object);
                }
            }
        }
    });
    // define keystrokes action bindings at the level of the main window
    InputMap inputMap = ((JComponent) this.getContentPane()).getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(KeyStroke.getKeyStroke("control F4"), "Close resource");
    inputMap.put(KeyStroke.getKeyStroke("shift F4"), "Close recursively");
    inputMap.put(KeyStroke.getKeyStroke("control H"), "Hide");
    inputMap.put(KeyStroke.getKeyStroke("control shift H"), "Hide all");
    inputMap.put(KeyStroke.getKeyStroke("control S"), "Save As XML");
    // TODO: remove when Swing will take care of the context menu key
    if (inputMap.get(KeyStroke.getKeyStroke("CONTEXT_MENU")) == null) {
        inputMap.put(KeyStroke.getKeyStroke("CONTEXT_MENU"), "Show context menu");
    }
    ActionMap actionMap = ((JComponent) instance.getContentPane()).getActionMap();
    actionMap.put("Show context menu", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
            // get the current focused component
            Component focusedComponent = focusManager.getFocusOwner();
            if (focusedComponent != null) {
                Point menuLocation = null;
                Rectangle selectionRectangle = null;
                if (focusedComponent instanceof JTable && ((JTable) focusedComponent).getSelectedRowCount() > 0) {
                    // selection in a JTable
                    JTable table = (JTable) focusedComponent;
                    selectionRectangle = table.getCellRect(table.getSelectionModel().getLeadSelectionIndex(), table.convertColumnIndexToView(table.getSelectedColumn()), false);
                } else if (focusedComponent instanceof JTree && ((JTree) focusedComponent).getSelectionCount() > 0) {
                    // selection in a JTree
                    JTree tree = (JTree) focusedComponent;
                    selectionRectangle = tree.getRowBounds(tree.getSelectionModel().getLeadSelectionRow());
                } else {
                    // for other component set the menu location at the top left corner
                    menuLocation = new Point(focusedComponent.getX() - 1, focusedComponent.getY() - 1);
                }
                if (menuLocation == null) {
                    // menu location at the bottom left of the JTable or JTree
                    menuLocation = new Point(new Double(selectionRectangle.getMinX() + 1).intValue(), new Double(selectionRectangle.getMaxY() - 1).intValue());
                }
                // generate a right/button 3/popup menu mouse click
                focusedComponent.dispatchEvent(new MouseEvent(focusedComponent, MouseEvent.MOUSE_PRESSED, e.getWhen(), MouseEvent.BUTTON3_DOWN_MASK, menuLocation.x, menuLocation.y, 1, true, MouseEvent.BUTTON3));
            }
        }
    });
    mainTabbedPane.getModel().addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            // find the handle in the resources tree for the main view
            JComponent largeView = (JComponent) mainTabbedPane.getSelectedComponent();
            Enumeration<?> nodesEnum = resourcesTreeRoot.preorderEnumeration();
            boolean done = false;
            DefaultMutableTreeNode node = resourcesTreeRoot;
            while (!done && nodesEnum.hasMoreElements()) {
                node = (DefaultMutableTreeNode) nodesEnum.nextElement();
                done = node.getUserObject() instanceof Handle && ((Handle) node.getUserObject()).viewsBuilt() && ((Handle) node.getUserObject()).getLargeView() == largeView;
            }
            ActionMap actionMap = ((JComponent) instance.getContentPane()).getActionMap();
            if (done) {
                Handle handle = (Handle) node.getUserObject();
                if (Gate.getUserConfig().getBoolean(MainFrame.class.getName() + ".viewselecttree")) {
                    // synchronise the selection in the tabbed pane with
                    // the one in the resources tree
                    TreePath nodePath = new TreePath(node.getPath());
                    resourcesTree.setSelectionPath(nodePath);
                    resourcesTree.scrollPathToVisible(nodePath);
                }
                lowerScroll.getViewport().setView(handle.getSmallView());
                // redefine MainFrame actionMaps for the selected tab
                JComponent resource = (JComponent) mainTabbedPane.getSelectedComponent();
                actionMap.put("Close resource", resource.getActionMap().get("Close resource"));
                actionMap.put("Close recursively", resource.getActionMap().get("Close recursively"));
                actionMap.put("Hide", new CloseViewAction(handle));
                actionMap.put("Hide all", new HideAllAction());
                actionMap.put("Save As XML", resource.getActionMap().get("Save As XML"));
            } else {
                // the selected item is not a resource (maybe the log area?)
                lowerScroll.getViewport().setView(null);
                // disabled actions on the selected tabbed pane
                actionMap.put("Close resource", null);
                actionMap.put("Close recursively", null);
                actionMap.put("Hide", null);
                actionMap.put("Hide all", null);
                actionMap.put("Save As XML", null);
            }
        }
    });
    mainTabbedPane.addMouseListener(new MouseAdapter() {

        @Override
        public void mousePressed(MouseEvent e) {
            processMouseEvent(e);
        }

        @Override
        public void mouseReleased(MouseEvent e) {
            processMouseEvent(e);
        }

        protected void processMouseEvent(MouseEvent e) {
            if (e.isPopupTrigger()) {
                int index = mainTabbedPane.getIndexAt(e.getPoint());
                if (index != -1) {
                    JComponent view = (JComponent) mainTabbedPane.getComponentAt(index);
                    Enumeration<?> nodesEnum = resourcesTreeRoot.preorderEnumeration();
                    boolean done = false;
                    DefaultMutableTreeNode node = resourcesTreeRoot;
                    while (!done && nodesEnum.hasMoreElements()) {
                        node = (DefaultMutableTreeNode) nodesEnum.nextElement();
                        done = node.getUserObject() instanceof Handle && ((Handle) node.getUserObject()).viewsBuilt() && ((Handle) node.getUserObject()).getLargeView() == view;
                    }
                    if (done) {
                        Handle handle = (Handle) node.getUserObject();
                        JPopupMenu popup = handle.getPopup();
                        // add a hide action
                        CloseViewAction cva = new CloseViewAction(handle);
                        XJMenuItem menuItem = new XJMenuItem(cva, MainFrame.this);
                        popup.insert(menuItem, 0);
                        // add a hide all action
                        if (mainTabbedPane.getTabCount() > 2) {
                            HideAllAction haa = new HideAllAction();
                            menuItem = new XJMenuItem(haa, MainFrame.this);
                            popup.insert(menuItem, 1);
                        }
                        popup.show(mainTabbedPane, e.getX(), e.getY());
                    }
                }
            }
        }
    });
    addComponentListener(new ComponentAdapter() {

        @Override
        public void componentShown(ComponentEvent e) {
            leftSplit.setDividerLocation(0.7);
        }

        @Override
        public void componentResized(ComponentEvent e) {
            // resize proportionally the status bar elements
            int width = MainFrame.this.getWidth();
            statusBar.setPreferredSize(new Dimension(width * 65 / 100, statusBar.getPreferredSize().height));
            progressBar.setPreferredSize(new Dimension(width * 20 / 100, progressBar.getPreferredSize().height));
            progressBar.setMinimumSize(new Dimension(80, 0));
            globalProgressBar.setPreferredSize(new Dimension(width * 10 / 100, globalProgressBar.getPreferredSize().height));
            globalProgressBar.setMinimumSize(new Dimension(80, 0));
        }
    });
    // blink the messages tab when new information is displayed
    logArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

        @Override
        public void insertUpdate(javax.swing.event.DocumentEvent e) {
            changeOccured();
        }

        @Override
        public void removeUpdate(javax.swing.event.DocumentEvent e) {
            changeOccured();
        }

        @Override
        public void changedUpdate(javax.swing.event.DocumentEvent e) {
        }

        protected void changeOccured() {
            logHighlighter.highlight();
        }
    });
    logArea.addPropertyChangeListener("document", new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            // add the document listener
            logArea.getDocument().addDocumentListener(new javax.swing.event.DocumentListener() {

                @Override
                public void insertUpdate(javax.swing.event.DocumentEvent e) {
                    changeOccured();
                }

                @Override
                public void removeUpdate(javax.swing.event.DocumentEvent e) {
                    changeOccured();
                }

                @Override
                public void changedUpdate(javax.swing.event.DocumentEvent e) {
                    changeOccured();
                }

                protected void changeOccured() {
                    logHighlighter.highlight();
                }
            });
        }
    });
    Gate.getListeners().put("gate.event.StatusListener", MainFrame.this);
    Gate.getListeners().put("gate.event.ProgressListener", MainFrame.this);
    if (Gate.runningOnMac()) {
        // mac-specific initialisation
        initMacListeners();
    }
}
Also used : ActionEvent(java.awt.event.ActionEvent) KeyAdapter(java.awt.event.KeyAdapter) Rectangle(java.awt.Rectangle) AbstractAction(javax.swing.AbstractAction) PropertyChangeEvent(java.beans.PropertyChangeEvent) JTree(javax.swing.JTree) JTable(javax.swing.JTable) InputMap(javax.swing.InputMap) ComponentEvent(java.awt.event.ComponentEvent) DefaultMutableTreeNode(javax.swing.tree.DefaultMutableTreeNode) PropertyChangeListener(java.beans.PropertyChangeListener) TreeSelectionListener(javax.swing.event.TreeSelectionListener) KeyEvent(java.awt.event.KeyEvent) MenuKeyEvent(javax.swing.event.MenuKeyEvent) XJPopupMenu(gate.swing.XJPopupMenu) KeyboardFocusManager(java.awt.KeyboardFocusManager) ChangeListener(javax.swing.event.ChangeListener) PropertyChangeListener(java.beans.PropertyChangeListener) Component(java.awt.Component) JComponent(javax.swing.JComponent) ComponentAdapter(java.awt.event.ComponentAdapter) MouseEvent(java.awt.event.MouseEvent) Enumeration(java.util.Enumeration) ActionMap(javax.swing.ActionMap) MouseAdapter(java.awt.event.MouseAdapter) JComponent(javax.swing.JComponent) Point(java.awt.Point) Dimension(java.awt.Dimension) Controller(gate.Controller) ConditionalSerialAnalyserController(gate.creole.ConditionalSerialAnalyserController) PackagedController(gate.creole.PackagedController) XJPopupMenu(gate.swing.XJPopupMenu) JPopupMenu(javax.swing.JPopupMenu) TreePath(javax.swing.tree.TreePath) ChangeEvent(javax.swing.event.ChangeEvent) PropertyChangeEvent(java.beans.PropertyChangeEvent) XJMenuItem(gate.swing.XJMenuItem) TreeSelectionEvent(javax.swing.event.TreeSelectionEvent)

Aggregations

ComponentAdapter (java.awt.event.ComponentAdapter)96 ComponentEvent (java.awt.event.ComponentEvent)96 Dimension (java.awt.Dimension)17 ActionEvent (java.awt.event.ActionEvent)17 JPanel (javax.swing.JPanel)17 JButton (javax.swing.JButton)15 Component (java.awt.Component)14 MouseEvent (java.awt.event.MouseEvent)14 JLabel (javax.swing.JLabel)13 JScrollPane (javax.swing.JScrollPane)13 BorderLayout (java.awt.BorderLayout)12 WindowAdapter (java.awt.event.WindowAdapter)12 WindowEvent (java.awt.event.WindowEvent)12 MouseAdapter (java.awt.event.MouseAdapter)11 Point (java.awt.Point)10 ActionListener (java.awt.event.ActionListener)10 AbstractAction (javax.swing.AbstractAction)8 BoxLayout (javax.swing.BoxLayout)8 JComponent (javax.swing.JComponent)8 JTable (javax.swing.JTable)8