Example usage for java.beans EventHandler create

List of usage examples for java.beans EventHandler create

Introduction

In this page you can find the example usage for java.beans EventHandler create.

Prototype

public static <T> T create(Class<T> listenerInterface, Object target, String action) 

Source Link

Document

Creates an implementation of listenerInterface in which all of the methods in the listener interface apply the handler's action to the target .

Usage

From source file:MainClass.java

public MainClass() {
    JButton launchButton = new JButton("Launch!");
    getContentPane().add(launchButton, "South");
    getContentPane().add(label, "Center");
    launchButton// ww w .  j a  va2 s  . c om
            .addActionListener((ActionListener) EventHandler.create(ActionListener.class, this, "actionName"));
}

From source file:PersistentFrameTest.java

 public void init()
{
   frame = new JFrame();
   frame.setLayout(new FlowLayout());
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setTitle("PersistentFrameTest");
   frame.setSize(400, 200);//  w w  w  . java2s  .  co m

   JButton loadButton = new JButton("Load");
   frame.add(loadButton);
   loadButton.addActionListener(EventHandler.create(ActionListener.class, this, "load"));

   JButton saveButton = new JButton("Save");
   frame.add(saveButton);
   saveButton.addActionListener(EventHandler.create(ActionListener.class, this, "save"));
     
   frame.setVisible(true);
}

From source file:org.orbisgis.chart.ChartPanelView.java

@Activate
public void init(Map<String, Object> attributes) {
    dockingPanelParameters.setName(EDITOR_NAME);
    dockingPanelParameters.setTitle(I18N.tr("Chart"));
    dockingPanelParameters.setTitleIcon(ChartIcon.getIcon("icon"));
    dockingPanelParameters.setDefaultDockingLocation(
            new DockingLocation(DockingLocation.Location.STACKED_ON, ChartEditorFactory.class.getSimpleName()));

    ActionCommands dockingActions = new ActionCommands();
    dockingPanelParameters.setDockActions(dockingActions.getActions());
    dockingActions.addPropertyChangeListener(new ActionDockingListener(dockingPanelParameters));
    dockingActions.addAction(new DefaultAction("ACTION_REFRESH", I18N.tr("Refresh"),
            I18N.tr("Refresh the chart."), ChartIcon.getIcon("refresh"),
            EventHandler.create(ActionListener.class, this, "onRefreshChart"), null));
    setEditableElement((ChartElement) attributes.get("editableElement"));
}

From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java

@Override
public void execute(ProgressMonitor pm) throws SQLException {
    try (Connection connection = dataSource.getConnection()) {
        isH2 = JDBCUtilities.isH2DataBase(connection.getMetaData());
        // Cache Columncount here
        cachedColumnCount = -1;//from w ww. jav  a 2  s.  c  o  m
        // Cache Rowcount here
        cachedRowCount = -1;
        getRowCount(pm);
    }
    if (resultSetHolder.getStatus() == ResultSetHolder.STATUS.NEVER_STARTED) {
        resultSetHolder.setParameters(parameters);
        if (!pk_name.isEmpty()) {
            // Always use PK to fetch rows
            resultSetHolder.setCommand(getCommand() + " LIMIT 0");
        } else {
            resultSetHolder.setCommand(getCommand());
            PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, resultSetHolder,
                    "cancel");
            pm.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener);
            try (Resource resource = resultSetHolder.getResource()) {
            } finally {
                pm.removePropertyChangeListener(listener);
            }
        }
    } else {
        // Clear cache of all rows
        rowFetchFirstPk = new ArrayList<>(Arrays.asList(new Long[] { null }));
        moveCursorTo(Math.min(getRowCount(), rowId));
        refreshRow();
    }
}

From source file:org.orbisgis.corejdbc.internal.ReadRowSetImpl.java

public long getRowCount(ProgressMonitor pm) throws SQLException {
    if (cachedRowCount == -1) {
        try (Connection connection = getConnection();
                PreparedStatement st = createPreparedStatement(connection, "COUNT(*) CPT", "")) {
            PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, st, "cancel");
            pm.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener);
            try (ResultSet rs = st.executeQuery()) {
                if (rs.next()) {
                    cachedRowCount = rs.getLong(1);
                }//from w w w. jav a  2s  .c o m
            } finally {
                pm.removePropertyChangeListener(listener);
            }
        }
    }
    return cachedRowCount;
}

From source file:org.orbisgis.corejdbc.ReadTable.java

public static Collection<Integer> getSortedColumnRowIndex(Connection connection, ReadRowSet originalOrder,
        String table, String originalColumnName, boolean ascending, ProgressMonitor progressMonitor)
        throws SQLException {
    String quoteIdentifier = TableLocation.quoteIdentifier(originalColumnName);
    TableLocation tableLocation = TableLocation.parse(table);
    Collection<Integer> columnValues;
    try (Statement st = connection.createStatement()) {
        int rowCount = 0;
        try (ResultSet rs = st.executeQuery("SELECT COUNT(*) cpt from " + tableLocation.toString())) {
            if (rs.next()) {
                rowCount = rs.getInt(1);
            }//ww  w  . ja va2 s .  c o m
        }
        columnValues = new ArrayList<>(rowCount);
        PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, st, "cancel");
        progressMonitor.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener);
        try {
            int pkIndex = JDBCUtilities.getIntegerPrimaryKey(connection, tableLocation.toString());
            if (pkIndex > 0) {
                ProgressMonitor jobProgress = progressMonitor.startTask(2);
                // Do not cache values
                // Use SQL sort
                DatabaseMetaData meta = connection.getMetaData();
                String pkFieldName = TableLocation
                        .quoteIdentifier(JDBCUtilities.getFieldName(meta, table, pkIndex));
                String desc = "";
                if (!ascending) {
                    desc = " DESC";
                }
                // Create a map of Row Id to Pk Value
                ProgressMonitor cacheProgress = jobProgress.startTask(I18N.tr("Cache primary key values"),
                        rowCount);
                Map<Long, Integer> pkValueToRowId = new HashMap<>(rowCount);
                int rowId = 0;
                Lock lock = originalOrder.getReadLock();
                lock.tryLock();
                try {
                    originalOrder.beforeFirst();
                    while (originalOrder.next()) {
                        rowId++;
                        pkValueToRowId.put(originalOrder.getPk(), rowId);
                        cacheProgress.endTask();
                    }
                } finally {
                    lock.unlock();
                }
                // Read ordered pk values
                ProgressMonitor sortProgress = jobProgress.startTask(I18N.tr("Read sorted keys"), rowCount);
                try (ResultSet rs = st.executeQuery(
                        "select " + pkFieldName + " from " + table + " ORDER BY " + quoteIdentifier + desc)) {
                    while (rs.next()) {
                        columnValues.add(pkValueToRowId.get(rs.getLong(1)));
                        sortProgress.endTask();
                    }
                }
            } else {
                ProgressMonitor jobProgress = progressMonitor.startTask(2);
                //Cache values
                ProgressMonitor cacheProgress = jobProgress.startTask(I18N.tr("Cache table values"), rowCount);
                Comparable[] cache = new Comparable[rowCount];
                Lock lock = originalOrder.getReadLock();
                lock.tryLock();
                try {
                    originalOrder.beforeFirst();
                    int i = 0;
                    final int fieldIndex = originalOrder.findColumn(originalColumnName);
                    long time1 = 0, time2 = 0, time3 = 0, time4 = 0, time5 = 0;
                    time5 -= System.currentTimeMillis();
                    while (originalOrder.next()) {
                        time5 += System.currentTimeMillis();
                        time1 -= System.currentTimeMillis();
                        Object obj = originalOrder.getObject(fieldIndex);
                        time1 += System.currentTimeMillis();
                        time2 -= System.currentTimeMillis();
                        if (obj != null && !(obj instanceof Comparable)) {
                            throw new SQLException(I18N.tr("Could only sort comparable database object type"));
                        }
                        time2 += System.currentTimeMillis();
                        time3 -= System.currentTimeMillis();
                        cache[i++] = (Comparable) obj;
                        time3 += System.currentTimeMillis();
                        time4 -= System.currentTimeMillis();
                        cacheProgress.endTask();
                        time4 += System.currentTimeMillis();
                        time5 -= System.currentTimeMillis();
                    }
                    time5 += System.currentTimeMillis();
                    System.out.println("time 1:" + time1 + ";" + "time 2:" + time2 + ";" + "time 3:" + time3
                            + ";" + "time 4:" + time4 + ";" + "time 5:" + time5 + ";");
                } finally {
                    lock.unlock();
                }
                ProgressMonitor sortProgress = jobProgress.startTask(I18N.tr("Sort table values"), rowCount);
                Comparator<Integer> comparator = new SortValueCachedComparator(cache);
                if (!ascending) {
                    comparator = Collections.reverseOrder(comparator);
                }
                columnValues = new TreeSet<>(comparator);
                for (int i = 1; i <= rowCount; i++) {
                    columnValues.add(i);
                    sortProgress.endTask();
                }
            }
        } finally {
            progressMonitor.removePropertyChangeListener(listener);
        }
        return columnValues;
    }
}

From source file:org.orbisgis.corejdbc.ReadTable.java

/**
 * Compute numeric stats of the specified table column.
 * @param connection Available connection
 * @param tableName Table name/* w  ww  .  j  av  a 2  s  . com*/
 * @param columnName Column name
 * @param pm Progress monitor
 * @return An array of attributes {@link STATS}
 * @throws SQLException
 */
public static String[] computeStatsSQL(Connection connection, String tableName, String columnName,
        ProgressMonitor pm) throws SQLException {
    String[] stats = new String[STATS.values().length];
    StringBuilder sb = new StringBuilder();
    for (STATS func : STATS.values()) {
        if (sb.length() != 0) {
            sb.append(", ");
        }
        sb.append(func.name());
        sb.append("(");
        sb.append(columnName);
        sb.append("::double precision) ");
        sb.append(func.name());
    }
    try (Statement st = connection.createStatement()) {

        // Cancel select
        PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, st, "cancel");
        pm.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener);
        try (ResultSet rs = st.executeQuery(String.format("SELECT %s FROM %s", sb.toString(), tableName))) {
            if (rs.next()) {
                for (STATS func : STATS.values()) {
                    stats[func.ordinal()] = rs.getString(func.name());
                }
            }
        } finally {
            pm.removePropertyChangeListener(listener);
        }
    }
    return stats;
}

From source file:org.orbisgis.corejdbc.ReadTable.java

/**
 * Compute numeric stats of the specified table column using a limited input rows. Stats are not done in the sql side.
 * @param connection Available connection
 * @param tableName Table name/*from  ww w.  j a v a 2 s .  com*/
 * @param columnName Column name
 * @param rowNum Row id
 * @param pm Progress monitor
 * @return An array of attributes {@link STATS}
 * @throws SQLException
 */
public static String[] computeStatsLocal(Connection connection, String tableName, String columnName,
        SortedSet<Integer> rowNum, ProgressMonitor pm) throws SQLException {
    String[] res = new String[STATS.values().length];
    SummaryStatistics stats = new SummaryStatistics();
    try (Statement st = connection.createStatement()) {
        // Cancel select
        PropertyChangeListener listener = EventHandler.create(PropertyChangeListener.class, st, "cancel");
        pm.addPropertyChangeListener(ProgressMonitor.PROP_CANCEL, listener);
        try (ResultSet rs = st.executeQuery(String.format("SELECT %s FROM %s", columnName, tableName))) {
            ProgressMonitor fetchProgress = pm.startTask(rowNum.size());
            while (rs.next() && !pm.isCancelled()) {
                if (rowNum.contains(rs.getRow())) {
                    stats.addValue(rs.getDouble(columnName));
                    fetchProgress.endTask();
                }
            }
        } finally {
            pm.removePropertyChangeListener(listener);
        }
    }
    res[STATS.SUM.ordinal()] = Double.toString(stats.getSum());
    res[STATS.AVG.ordinal()] = Double.toString(stats.getMean());
    res[STATS.COUNT.ordinal()] = Long.toString(stats.getN());
    res[STATS.MIN.ordinal()] = Double.toString(stats.getMin());
    res[STATS.MAX.ordinal()] = Double.toString(stats.getMax());
    res[STATS.STDDEV_SAMP.ordinal()] = Double.toString(stats.getStandardDeviation());
    return res;
}

From source file:org.orbisgis.groovy.GroovyConsolePanel.java

/**
 * The main panel to write and execute a groovy script.
 *
 * @return/*from  www. j a  v  a  2s  . c  om*/
 */
private RTextScrollPane getCenterPanel() {
    if (centerPanel == null) {
        initActions();
        LanguageSupportFactory lsf = LanguageSupportFactory.get();
        gls = (GroovyLanguageSupport) lsf.getSupportFor(SyntaxConstants.SYNTAX_STYLE_GROOVY);
        scriptPanel = new RSyntaxTextArea();
        scriptPanel.setLineWrap(true);
        lsf.register(scriptPanel);
        scriptPanel.setSyntaxEditingStyle(RSyntaxTextArea.SYNTAX_STYLE_GROOVY);
        scriptPanel
                .addCaretListener(EventHandler.create(CaretListener.class, this, "onScriptPanelCaretUpdate"));
        scriptPanel.getDocument().addDocumentListener(
                EventHandler.create(DocumentListener.class, this, "onUserSelectionChange"));
        scriptPanel.clearParsers();
        scriptPanel.setTabsEmulated(true);
        actions.setAccelerators(scriptPanel);
        // Actions will be set on the scriptPanel PopupMenu
        scriptPanel.getPopupMenu().addSeparator();
        actions.registerContainer(scriptPanel.getPopupMenu());
        centerPanel = new RTextScrollPane(scriptPanel);
        onUserSelectionChange();

    }
    return centerPanel;
}

From source file:org.orbisgis.groovy.GroovyConsolePanel.java

/**
 * Create actions instances/*from   w w w . j a v  a 2  s.c  om*/
 *
 * Each action is put in the Popup menu and the tool bar Their shortcuts are
 * registered also in the editor
 */
private void initActions() {
    //Execute action
    executeAction = new DefaultAction(GroovyConsoleActions.A_EXECUTE, I18N.tr("Execute"),
            I18N.tr("Execute the groovy script"), GroovyIcon.getIcon("execute"),
            EventHandler.create(ActionListener.class, this, "onExecute"),
            KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.CTRL_DOWN_MASK)).setLogicalGroup("custom");
    actions.addAction(executeAction);

    //Execute Selected SQL
    executeSelectedAction = new DefaultAction(GroovyConsoleActions.A_EXECUTE_SELECTION,
            I18N.tr("Execute selected"), I18N.tr("Run selected code"), GroovyIcon.getIcon("execute_selection"),
            EventHandler.create(ActionListener.class, this, "onExecuteSelected"),
            KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.ALT_DOWN_MASK)).setLogicalGroup("custom")
                    .setAfter(GroovyConsoleActions.A_EXECUTE);
    actions.addAction(executeSelectedAction);

    //Clear action
    clearAction = new DefaultAction(GroovyConsoleActions.A_CLEAR, I18N.tr("Clear"),
            I18N.tr("Erase the content of the editor"), GroovyIcon.getIcon("erase"),
            EventHandler.create(ActionListener.class, this, "onClear"), null);
    actions.addAction(clearAction);

    //Open action
    actions.addAction(new DefaultAction(GroovyConsoleActions.A_OPEN, I18N.tr("Open"),
            I18N.tr("Load a file in this editor"), GroovyIcon.getIcon("open"),
            EventHandler.create(ActionListener.class, this, "onOpenFile"),
            KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK)));
    //Save
    saveAction = new DefaultAction(GroovyConsoleActions.A_SAVE, I18N.tr("Save"),
            I18N.tr("Save the editor content into a file"), GroovyIcon.getIcon("save"),
            EventHandler.create(ActionListener.class, this, "onSaveFile"),
            KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));
    actions.addAction(saveAction);
    // Save As
    saveAsAction = new DefaultAction(GroovyConsoleActions.A_SAVE, I18N.tr("Save As"),
            I18N.tr("Save the editor content into a new file"), GroovyIcon.getIcon("page_white_save"),
            EventHandler.create(ActionListener.class, this, "onSaveAsNewFile"),
            KeyStroke.getKeyStroke("ctrl maj s"));
    actions.addAction(saveAsAction);
    //Find action
    findAction = new DefaultAction(GroovyConsoleActions.A_SEARCH, I18N.tr("Search.."),
            I18N.tr("Search text in the document"), GroovyIcon.getIcon("find"),
            EventHandler.create(ActionListener.class, this, "openFindReplaceDialog"),
            KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK))
                    .addStroke(KeyStroke.getKeyStroke(KeyEvent.VK_H, InputEvent.CTRL_DOWN_MASK));
    actions.addAction(findAction);

    // Comment/Uncomment
    commentAction = new DefaultAction(GroovyConsoleActions.A_COMMENT, I18N.tr("(Un)comment"),
            I18N.tr("(Un)comment the selected text"), null,
            EventHandler.create(ActionListener.class, this, "onComment"), KeyStroke.getKeyStroke("alt C"))
                    .setLogicalGroup("format");
    actions.addAction(commentAction);

    // Block Comment/Uncomment
    blockCommentAction = new DefaultAction(GroovyConsoleActions.A_BLOCKCOMMENT, I18N.tr("Block (un)comment"),
            I18N.tr("Block (un)comment the selected text."), null,
            EventHandler.create(ActionListener.class, this, "onBlockComment"),
            KeyStroke.getKeyStroke("alt shift C")).setLogicalGroup("format");
    actions.addAction(blockCommentAction);
}