Example usage for java.awt Rectangle contains

List of usage examples for java.awt Rectangle contains

Introduction

In this page you can find the example usage for java.awt Rectangle contains.

Prototype

public boolean contains(Rectangle r) 

Source Link

Document

Checks whether or not this Rectangle entirely contains the specified Rectangle .

Usage

From source file:com.igormaznitsa.sciareto.ui.editors.MMDEditor.java

@Override
public void onEnsureVisibilityOfTopic(@Nonnull final MindMapPanel source, @Nullable final Topic topic) {
    SwingUtilities.invokeLater(new Runnable() {

        @Override/*from  w w w. j  av a 2s  .  co m*/
        public void run() {
            if (topic == null) {
                return;
            }

            final AbstractElement element = (AbstractElement) topic.getPayload();
            if (element == null) {
                return;
            }

            final Rectangle2D orig = element.getBounds();
            final int GAP = 30;

            final Rectangle bounds = orig.getBounds();
            bounds.setLocation(Math.max(0, bounds.x - GAP), Math.max(0, bounds.y - GAP));
            bounds.setSize(bounds.width + GAP * 2, bounds.height + GAP * 2);

            final JViewport viewport = getViewport();
            final Rectangle visible = viewport.getViewRect();

            if (visible.contains(bounds)) {
                return;
            }

            bounds.setLocation(bounds.x - visible.x, bounds.y - visible.y);

            viewport.scrollRectToVisible(bounds);
        }

    });
}

From source file:org.openmicroscopy.shoola.agents.dataBrowser.browser.BrowserModel.java

/**
 * Implemented as specified by the {@link Browser} interface.
 * @see Browser#scrollToNode(ImageDisplay)
 *//* www . j a va2  s  .  c  o  m*/
public void scrollToNode(ImageDisplay node) {
    if (node == null)
        return;
    JScrollPane pane = rootDisplay.getDeskDecorator();
    Rectangle bounds = node.getBounds();
    Rectangle viewRect = pane.getViewport().getViewRect();
    if (viewRect.contains(bounds))
        return;
    JScrollBar hBar = pane.getHorizontalScrollBar();
    if (hBar.isVisible()) {
        int x = bounds.x;
        int max = hBar.getMaximum();
        if (x > max)
            x = max;
        hBar.setValue(x);
    }
    JScrollBar vBar = pane.getVerticalScrollBar();
    if (vBar.isVisible()) {
        int y = bounds.y;
        int max = vBar.getMaximum();
        if (y > max)
            y = max;
        vBar.setValue(y);
    }
}

From source file:com.projity.pm.graphic.spreadsheet.common.CommonSpreadSheet.java

public boolean editCellAt(int row, int column, EventObject e) {
    boolean b = super.editCellAt(row, column, e);
    if (b && editorComp != null) {
        //          System.out.println("editing cell at " + row + " " + column);
        Component comp;/*  www  .ja v  a2 s  .c o  m*/
        boolean nameCell = false;
        if (editorComp instanceof NameCellComponent) {
            nameCell = true;
            NameCellComponent nameCellComp = (NameCellComponent) editorComp;
            comp = nameCellComp.getTextComponent();
        } else
            comp = editorComp;

        if (comp instanceof KeyboardFocusable)
            ((KeyboardFocusable) comp).selectAll(e == null);

        else if (comp instanceof ChangeAwareTextField) {
            ChangeAwareTextField text = ((ChangeAwareTextField) comp);
            if (e == null) {
                text.selectAll();
            } else if (e instanceof MouseEvent) {
                if (nameCell) {
                    MouseEvent me = (MouseEvent) e;
                    Rectangle bounds = text.getBounds(null);
                    Rectangle cell = getCellRect(row, column, false);
                    bounds.setFrame(cell.getX() + bounds.getX(), cell.getY() + bounds.getY(), bounds.getWidth(),
                            bounds.getHeight());
                    if (bounds.contains(me.getPoint())) {
                        text.selectAllOnNextCaretUpdate(); //to avoid diselection when the cell is clicked
                    } else { //because if it's outside there's no caret update
                        text.requestFocus();
                        text.selectAll();
                    }
                } else
                    text.selectAllOnNextCaretUpdate(); //to avoid diselection when the cell is clicked
            }
            text.resetChange();
        }
    }
    return b;
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Perform a selection query that retrieves all points in the given range.
 * The range is specified in the two-dimensional array positions. 
 * @param in/*from ww  w  . ja v a2s .  co  m*/
 * @param query_mbr
 * @return
 * @throws IOException
 */
public static Node aggregateQuery(FSDataInputStream in, Rectangle query_mbr) throws IOException {
    long treeStartPosition = in.getPos();
    Node result = new Node();
    int numOfSelectedRecords = 0;
    int resolution = in.readInt();
    short fillValue = in.readShort();
    int cardinality = in.readInt();
    final Vector<Integer> selectedNodesPos = new Vector<Integer>();
    final Vector<Integer> selectedStarts = new Vector<Integer>();
    final Vector<Integer> selectedEnds = new Vector<Integer>();
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    // Nodes to be searched. Contains node positions in the array of nodes
    Stack<Integer> nodes_2b_searched = new Stack<Integer>();
    nodes_2b_searched.add(0); // Root node (ID=1)
    Rectangle node_mbr = new Rectangle();
    while (!nodes_2b_searched.isEmpty()) {
        int node_pos = nodes_2b_searched.pop();
        stockQuadTree.getNodeMBR(node_pos, node_mbr);
        if (query_mbr.contains(node_mbr)) {
            // Add this node to the selection list and stop this branch
            selectedNodesPos.add(node_pos);
        } else if (query_mbr.intersects(node_mbr)) {
            int first_child_id = stockQuadTree.nodesID[node_pos] * 4 + 0;
            int first_child_pos = Arrays.binarySearch(stockQuadTree.nodesID, first_child_id);
            if (first_child_pos < 0) {
                // No children. Hit a leaf node
                // Scan and add matching points only
                java.awt.Point record_coords = new Point();
                for (int record_pos = stockQuadTree.nodesStartPosition[node_pos]; record_pos < stockQuadTree.nodesEndPosition[node_pos]; record_pos++) {
                    stockQuadTree.getRecordCoords(record_pos, record_coords);
                    if (query_mbr.contains(record_coords)) {
                        // matched a record.
                        if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == record_pos) {
                            // Merge with an adjacent range
                            selectedEnds.set(selectedEnds.size() - 1, record_pos + 1);
                        } else {
                            // Add a new range of unit width
                            selectedStarts.add(record_pos);
                            selectedEnds.add(record_pos + 1);
                        }
                        numOfSelectedRecords++;
                    }
                }
            } else {
                // Non-leaf node. Add all children to the list of nodes to search
                // Add in reverse order to the stack so that results come in sorted order
                nodes_2b_searched.add(first_child_pos + 3);
                nodes_2b_searched.add(first_child_pos + 2);
                nodes_2b_searched.add(first_child_pos + 1);
                nodes_2b_searched.add(first_child_pos + 0);
            }
        }
    }
    // Result 1: Accumulate all values
    // Sort disk offsets to eliminate backward seeks
    if (!selectedStarts.isEmpty()) {
        LOG.debug("Aggregate query selected " + selectedNodesPos.size() + " nodes and " + numOfSelectedRecords
                + " records");

        final IndexedSortable sortable = new IndexedSortable() {
            @Override
            public int compare(int i, int j) {
                return selectedStarts.get(i) - selectedStarts.get(j);
            }

            @Override
            public void swap(int i, int j) {
                int temp = selectedStarts.get(i);
                selectedStarts.set(i, selectedStarts.get(j));
                selectedStarts.set(j, temp);

                temp = selectedEnds.get(i);
                selectedEnds.set(i, selectedEnds.get(j));
                selectedEnds.set(j, temp);
            }
        };
        new QuickSort().sort(sortable, 0, selectedStarts.size());

        long dataStartPosition = getValuesStartOffset(cardinality);
        Point resultCoords = new Point();
        // Return all values in the selected ranges
        for (int iRange = 0; iRange < selectedStarts.size(); iRange++) {
            int treeStart = selectedStarts.get(iRange);
            int treeEnd = selectedEnds.get(iRange);
            long startPosition = dataStartPosition + selectedStarts.get(iRange) * cardinality * 2;
            in.seek(startPosition);
            for (int treePos = treeStart; treePos < treeEnd; treePos++) {
                // Retrieve the coords for the point at treePos
                stockQuadTree.getRecordCoords(treePos, resultCoords);
                // Read all entries at current position
                for (int iValue = 0; iValue < cardinality; iValue++) {
                    short value = in.readShort();
                    if (value != fillValue)
                        result.accumulate(value);
                }
            }
        }

    }

    // Result 2: Accumulate all nodes
    if (!selectedNodesPos.isEmpty()) {
        long nodesStartPosition = treeStartPosition + getNodesStartOffset(resolution, cardinality);
        // Sort node positions to eliminate backward seeks
        IndexedSortable nodeSortable = new IndexedSortable() {
            @Override
            public int compare(int i, int j) {
                return selectedNodesPos.get(i) - selectedNodesPos.get(j);
            }

            @Override
            public void swap(int i, int j) {
                int temp = selectedNodesPos.get(i);
                selectedNodesPos.set(i, selectedNodesPos.get(j));
                selectedNodesPos.set(j, temp);
            }
        };
        new QuickSort().sort(nodeSortable, 0, selectedNodesPos.size());

        Node selectedNode = new Node();
        for (int node_pos : selectedNodesPos) {
            long nodePosition = nodesStartPosition + node_pos * NodeSize;
            in.seek(nodePosition);
            selectedNode.readFields(in);
            result.accumulate(selectedNode);
        }
    }
    return result;
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Perform a selection query that retrieves all points in the given range.
 * The range is specified in the two-dimensional array positions.
 * @param in/*  ww w.j a  va2 s . c o  m*/
 * @param query_mbr
 * @param output
 * @return number of matched records
 * @throws IOException
 */
public static int selectionQuery(FSDataInputStream in, Rectangle query_mbr, ResultCollector<PointValue> output)
        throws IOException {
    long treeStartPosition = in.getPos();
    int numOfResults = 0;
    int resolution = in.readInt();
    short fillValue = in.readShort();
    int cardinality = in.readInt();
    long[] timestamps = new long[cardinality];
    for (int i = 0; i < cardinality; i++)
        timestamps[i] = in.readLong();
    Vector<Integer> selectedStarts = new Vector<Integer>();
    Vector<Integer> selectedEnds = new Vector<Integer>();
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    // Nodes to be searched. Contains node positions in the array of nodes
    Stack<Integer> nodes_2b_searched = new Stack<Integer>();
    nodes_2b_searched.add(0); // Root node (ID=1)
    Rectangle node_mbr = new Rectangle();
    while (!nodes_2b_searched.isEmpty()) {
        int node_pos = nodes_2b_searched.pop();
        stockQuadTree.getNodeMBR(node_pos, node_mbr);
        if (query_mbr.contains(node_mbr)) {
            // Add this node to the selection list and stop this branch
            if (!selectedEnds.isEmpty()
                    && selectedEnds.lastElement() == stockQuadTree.nodesStartPosition[node_pos]) {
                // Merge with an adjacent range
                selectedEnds.set(selectedEnds.size() - 1, stockQuadTree.nodesEndPosition[node_pos]);
            } else {
                // add a new range
                selectedStarts.add(stockQuadTree.nodesStartPosition[node_pos]);
                selectedEnds.add(stockQuadTree.nodesEndPosition[node_pos]);
            }
            numOfResults += stockQuadTree.nodesEndPosition[node_pos]
                    - stockQuadTree.nodesStartPosition[node_pos];
        } else if (query_mbr.intersects(node_mbr)) {
            int first_child_id = stockQuadTree.nodesID[node_pos] * 4 + 0;
            int first_child_pos = Arrays.binarySearch(stockQuadTree.nodesID, first_child_id);
            if (first_child_pos < 0) {
                // No children. Hit a leaf node
                // Scan and add matching points only
                java.awt.Point record_coords = new Point();
                for (int record_pos = stockQuadTree.nodesStartPosition[node_pos]; record_pos < stockQuadTree.nodesEndPosition[node_pos]; record_pos++) {
                    stockQuadTree.getRecordCoords(record_pos, record_coords);
                    if (query_mbr.contains(record_coords)) {
                        // matched a record.
                        if (!selectedEnds.isEmpty() && selectedEnds.lastElement() == record_pos) {
                            // Merge with an adjacent range
                            selectedEnds.set(selectedEnds.size() - 1, record_pos + 1);
                        } else {
                            // Add a new range of unit width
                            selectedStarts.add(record_pos);
                            selectedEnds.add(record_pos + 1);
                        }
                        numOfResults++;
                    }
                }
            } else {
                // Non-leaf node. Add all children to the list of nodes to search
                // Add in reverse order to the stack so that results come in sorted order
                nodes_2b_searched.add(first_child_pos + 3);
                nodes_2b_searched.add(first_child_pos + 2);
                nodes_2b_searched.add(first_child_pos + 1);
                nodes_2b_searched.add(first_child_pos + 0);
            }
        }
    }
    if (output != null) {
        PointValue returnValue = new PointValue();
        long dataStartPosition = treeStartPosition + getValuesStartOffset(cardinality);
        // Return all values in the selected ranges
        for (int iRange = 0; iRange < selectedStarts.size(); iRange++) {
            int treeStart = selectedStarts.get(iRange);
            int treeEnd = selectedEnds.get(iRange);
            long startPosition = dataStartPosition + selectedStarts.get(iRange) * cardinality * 2;
            in.seek(startPosition);
            for (int treePos = treeStart; treePos < treeEnd; treePos++) {
                // Retrieve the coords for the point at treePos
                stockQuadTree.getRecordCoords(treePos, returnValue);
                // Read all entries at current position
                for (int iValue = 0; iValue < cardinality; iValue++) {
                    short value = in.readShort();
                    if (value != fillValue) {
                        returnValue.value = value;
                        returnValue.timestamp = timestamps[iValue];
                        output.collect(returnValue);
                    }
                }
            }
        }
    }
    return numOfResults;
}

From source file:com.sikulix.core.SX.java

private static void globalGetMonitors() {
    if (!isHeadless()) {
        genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gdevs = genv.getScreenDevices();
        nMonitors = gdevs.length;/*from   w w w .j a v a  2  s .  com*/
        if (nMonitors == 0) {
            terminate(1, "globalGetMonitors: GraphicsEnvironment has no ScreenDevices");
        }
        monitorBounds = new Rectangle[nMonitors];
        rAllMonitors = null;
        Rectangle currentBounds;
        for (int i = 0; i < nMonitors; i++) {
            currentBounds = new Rectangle(gdevs[i].getDefaultConfiguration().getBounds());
            if (null != rAllMonitors) {
                rAllMonitors = rAllMonitors.union(currentBounds);
            } else {
                rAllMonitors = currentBounds;
            }
            if (currentBounds.contains(new Point())) {
                if (mainMonitor < 0) {
                    mainMonitor = i;
                    debug("globalGetMonitors: 1#ScreenDevice %d has (0,0) --- will be primary Screen(0)", i);
                } else {
                    debug("globalGetMonitors: 2#ScreenDevice %d too contains (0,0)!", i);
                }
            }
            debug("globalGetMonitors: Monitor %d: (%d, %d) %d x %d", i, currentBounds.x, currentBounds.y,
                    currentBounds.width, currentBounds.height);
            monitorBounds[i] = currentBounds;
        }
        if (mainMonitor < 0) {
            debug("globalGetMonitors: No ScreenDevice has (0,0) --- using 0 as primary: %s", monitorBounds[0]);
            mainMonitor = 0;
        }
    } else {
        error("running in headless environment");
    }
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

public boolean isInResizeCorner(AnnotationObject selection, Point p) {
    Rectangle rect = rectangles_complete.get(selection);

    int size = 2 * theOptions.ANNOTATION_MARGIN / 3;

    Rectangle corner1 = new Rectangle(left(rect), top(rect), size, size);
    if (corner1.contains(p))
        return true;

    Rectangle corner2 = new Rectangle(right(rect) - size, top(rect), size, size);
    if (corner2.contains(p))
        return true;

    return false;
}

From source file:org.eurocarbdb.application.glycoworkbench.plugin.reporting.AnnotationReportCanvas.java

private void dragAndScroll(MouseEvent e) {
    // move view if near borders                
    Point point = e.getPoint();/*from   www . j av  a  2  s .c  om*/
    JViewport view = theScrollPane.getViewport();
    Rectangle inner = view.getViewRect();
    inner.grow(-10, -10);

    if (!inner.contains(point)) {
        Point orig = view.getViewPosition();
        if (point.x < inner.x)
            orig.x -= 10;
        else if (point.x > (inner.x + inner.width))
            orig.x += 10;
        if (point.y < inner.y)
            orig.y -= 10;
        else if (point.y > (inner.y + inner.height))
            orig.y += 10;

        int maxx = getBounds().width - view.getViewRect().width;
        int maxy = getBounds().height - view.getViewRect().height;
        if (orig.x < 0)
            orig.x = 0;
        if (orig.x > maxx)
            orig.x = maxx;
        if (orig.y < 0)
            orig.y = 0;
        if (orig.y > maxy)
            orig.y = maxy;

        view.setViewPosition(orig);
    }
}

From source file:com.intuit.tank.tools.debugger.AgentDebuggerFrame.java

/**
 * @throws HeadlessException/*from  w  w  w .  ja  va 2 s  .  com*/
 */
public AgentDebuggerFrame(final boolean isStandalone, String serviceUrl) throws HeadlessException {
    super("Intuit Tank Agent Debugger");
    workingDir = PanelBuilder.createWorkingDir(this, serviceUrl);
    setSize(new Dimension(1024, 800));
    setBounds(new Rectangle(getSize()));
    setPreferredSize(getSize());
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);
    setLayout(new BorderLayout());
    this.standalone = isStandalone;
    addWindowListener(new WindowAdapter() {
        public void windowClosed(WindowEvent e) {
            quit();
        }
    });
    errorIcon = ActionProducer.getIcon("bullet_error.png", IconSize.SMALL);
    modifiedIcon = ActionProducer.getIcon("bullet_code_change.png", IconSize.SMALL);
    skippedIcon = ActionProducer.getIcon("skip.png", IconSize.SMALL);

    this.glassPane = new InfiniteProgressPanel();
    setGlassPane(glassPane);
    debuggerActions = new ActionProducer(this, serviceUrl);
    requestResponsePanel = new RequestResponsePanel(this);
    requestResponsePanel.init();
    testPlanChooser = new JComboBox();
    testPlanChooser.addItemListener(new ItemListener() {

        @Override
        public void itemStateChanged(ItemEvent event) {
            if (event.getItem() != null) {
                HDTestPlan selected = (HDTestPlan) event.getItem();
                if (!selected.equals(currentTestPlan)) {
                    setCurrentTestPlan(selected);
                }
            }

        }
    });

    tankClientChooser = new JComboBox<TankClientChoice>();
    debuggerActions.setChoiceComboBoxOptions(tankClientChooser);

    actionComponents = new ActionComponents(standalone, testPlanChooser, tankClientChooser, debuggerActions);
    addScriptChangedListener(actionComponents);
    setJMenuBar(actionComponents.getMenuBar());

    Component topPanel = PanelBuilder.createTopPanel(actionComponents);
    Component bottomPanel = PanelBuilder.createBottomPanel(this);
    Component contentPanel = PanelBuilder.createContentPanel(this);

    final JPopupMenu popup = actionComponents.getPopupMenu();
    scriptEditorTA.setPopupMenu(null);

    scriptEditorTA.addMouseListener(new MouseAdapter() {
        int lastHash;

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

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

        private void maybeShow(MouseEvent e) {
            if (lastHash == getHash(e)) {
                return;
            }
            if (e.isPopupTrigger()) {
                // select the line
                try {
                    int offset = scriptEditorTA.viewToModel(e.getPoint());
                    Rectangle modelToView = scriptEditorTA.modelToView(offset);
                    Point point = new Point(modelToView.x + 1, e.getPoint().y);
                    if (modelToView.contains(point)) {
                        if (!multiSelect) {
                            int line = scriptEditorTA.getLineOfOffset(offset);
                            scriptEditorTA.setCurrentLine(line);
                        }
                        popup.show(e.getComponent(), e.getX(), e.getY());
                    }
                } catch (BadLocationException e1) {
                    e1.printStackTrace();
                }
            } else if (e.isShiftDown()) {
                int line = scriptEditorTA.getCaretLineNumber();
                int start = Math.min(line, lastLine);
                int end = Math.max(line, lastLine);
                multiSelect = end - start > 1;
                if (multiSelect) {
                    multiSelectStart = start;
                    multiSelectEnd = end;
                    try {
                        scriptEditorTA.setEnabled(true);
                        scriptEditorTA.select(scriptEditorTA.getLineStartOffset(start),
                                scriptEditorTA.getLineEndOffset(end));
                        scriptEditorTA.setEnabled(false);
                    } catch (BadLocationException e1) {
                        e1.printStackTrace();
                        multiSelect = false;
                    }
                }
            } else {
                multiSelect = false;
                lastLine = scriptEditorTA.getCaretLineNumber();
            }
            lastHash = getHash(e);
        }

        private int getHash(MouseEvent e) {
            return new HashCodeBuilder().append(e.getButton()).append(e.getSource().hashCode())
                    .append(e.getPoint()).toHashCode();
        }

    });

    JSplitPane mainSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
    mainSplit.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
    mainSplit.setTopComponent(contentPanel);
    mainSplit.setBottomComponent(bottomPanel);
    mainSplit.setDividerLocation(600);
    mainSplit.setResizeWeight(0.8D);
    mainSplit.setDividerSize(5);

    add(topPanel, BorderLayout.NORTH);
    add(mainSplit, BorderLayout.CENTER);

    WindowUtil.centerOnScreen(this);
    pack();

    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager();

    manager.addKeyEventDispatcher(new KeyEventDispatcher() {

        @Override
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_PRESSED) {
                handleKeyEvent(e);
            }
            return false;
        }
    });
}

From source file:org.photovault.swingui.PhotoCollectionThumbView.java

/**
   Checks which photo is under the specified coordinates
   @return The photo that covers the position, null if the coordinates point to free space
   between photos.//w  w w  . j  a v a  2 s . co m
*/
private PhotoInfo getPhotoAtLocation(int x, int y) {
    if (photos == null) {
        return null;
    }

    PhotoInfo photo = null;
    int row = y / rowHeight;
    int col = x / columnWidth;
    int photoNum = row * columnsToPaint + col;
    log.debug("Located photo # " + photoNum);

    if (photoNum < photos.size()) {
        Rectangle imgRect = getPhotoBounds(photoNum);
        if (imgRect.contains(new Point(x, y))) {
            photo = photos.get(photoNum);
        }
    }
    return photo;
}