Example usage for java.awt Dimension getWidth

List of usage examples for java.awt Dimension getWidth

Introduction

In this page you can find the example usage for java.awt Dimension getWidth.

Prototype

public double getWidth() 

Source Link

Usage

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private void scaleSize() {
    Dimension d = mainPanel.getPreferredSize();
    Dimension screen = GuiUtil.getWorkingScreenSize();
    int height = MIN_HEIGHT > screen.getHeight() ? (int) (screen.getHeight() - 50) : MIN_HEIGHT;

    setSize(new Dimension((int) d.getWidth(), height));

    GuiUtil.centerOnScreen(EntrainerFX.this);
    JFXUtils.runLater(() -> unexpandTitledPanes());
}

From source file:org.geotools.gce.imagemosaic.RasterLayerResponse.java

/**
 * This method loads the granules which overlap the requested
 * {@link GeneralEnvelope} using the provided values for alpha and input
 * ROI./* w  ww  .j a va 2 s  .c  o m*/
 * @return
 * @throws DataSourceException
 */
private RenderedImage prepareResponse() throws DataSourceException {

    try {

        //
        // prepare the params for executing a mosaic operation.
        //
        // It might important to set the mosaic type to blend otherwise
        // sometimes strange results jump in.

        // select the relevant overview, notice that at this time we have
        // relaxed a bit the requirement to have the same exact resolution
        // for all the overviews, but still we do not allow for reading the
        // various grid to world transform directly from the input files,
        // therefore we are assuming that each granuleDescriptor has a scale and
        // translate only grid to world that can be deduced from its base
        // level dimension and envelope. The grid to world transforms for
        // the other levels can be computed accordingly knowing the scale
        // factors.
        if (request.getRequestedBBox() != null && request.getRequestedRasterArea() != null
                && !request.isHeterogeneousGranules())
            imageChoice = ReadParamsController.setReadParams(request.getRequestedResolution(),
                    request.getOverviewPolicy(), request.getDecimationPolicy(), baseReadParameters,
                    request.rasterManager, request.rasterManager.overviewsController); // use general overviews controller
        else
            imageChoice = 0;
        assert imageChoice >= 0;
        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine(new StringBuffer("Loading level ").append(imageChoice)
                    .append(" with subsampling factors ").append(baseReadParameters.getSourceXSubsampling())
                    .append(" ").append(baseReadParameters.getSourceYSubsampling()).toString());

        // ok we got something to return, let's load records from the index
        final BoundingBox cropBBOX = request.getCropBBox();
        if (cropBBOX != null)
            mosaicBBox = ReferencedEnvelope.reference(cropBBOX);
        else
            mosaicBBox = new ReferencedEnvelope(coverageEnvelope);

        //compute final world to grid
        // base grid to world for the center of pixels
        final AffineTransform g2w;
        final OverviewLevel baseLevel = rasterManager.overviewsController.resolutionsLevels.get(0);
        final OverviewLevel selectedLevel = rasterManager.overviewsController.resolutionsLevels
                .get(imageChoice);
        final double resX = baseLevel.resolutionX;
        final double resY = baseLevel.resolutionY;
        final double[] requestRes = request.getRequestedResolution();

        g2w = new AffineTransform((AffineTransform) baseGridToWorld);
        g2w.concatenate(CoverageUtilities.CENTER_TO_CORNER);

        if ((requestRes[0] < resX || requestRes[1] < resY)) {
            // Using the best available resolution
            oversampledRequest = true;
        } else {

            // SG going back to working on a per level basis to do the composition
            // g2w = new AffineTransform(request.getRequestedGridToWorld());
            g2w.concatenate(
                    AffineTransform.getScaleInstance(selectedLevel.scaleFactor, selectedLevel.scaleFactor));
            g2w.concatenate(AffineTransform.getScaleInstance(baseReadParameters.getSourceXSubsampling(),
                    baseReadParameters.getSourceYSubsampling()));
        }

        // move it to the corner
        finalGridToWorldCorner = new AffineTransform2D(g2w);
        finalWorldToGridCorner = finalGridToWorldCorner.inverse();// compute raster bounds
        final GeneralEnvelope tempRasterBounds = CRS.transform(finalWorldToGridCorner, mosaicBBox);
        rasterBounds = tempRasterBounds.toRectangle2D().getBounds();

        //          SG using the above may lead to problems since the reason is that  may be a little (1 px) bigger
        //          than what we need. The code below is a bit better since it uses a proper logic (see GridEnvelope
        //          Javadoc)
        //         rasterBounds = new GridEnvelope2D(new Envelope2D(tempRasterBounds), PixelInCell.CELL_CORNER);
        if (rasterBounds.width == 0)
            rasterBounds.width++;
        if (rasterBounds.height == 0)
            rasterBounds.height++;
        if (oversampledRequest)
            rasterBounds.grow(2, 2);

        // make sure we do not go beyond the raster dimensions for this layer
        final GeneralEnvelope levelRasterArea_ = CRS.transform(finalWorldToGridCorner,
                rasterManager.spatialDomainManager.coverageBBox);
        final GridEnvelope2D levelRasterArea = new GridEnvelope2D(new Envelope2D(levelRasterArea_),
                PixelInCell.CELL_CORNER);
        XRectangle2D.intersect(levelRasterArea, rasterBounds, rasterBounds);

        // create the index visitor and visit the feature
        final MosaicBuilder visitor = new MosaicBuilder(request);
        final List times = request.getRequestedTimes();
        final List elevations = request.getElevation();
        final Map<String, List> additionalDomains = request.getRequestedAdditionalDomains();
        final Filter filter = request.getFilter();
        final boolean hasTime = (times != null && times.size() > 0);
        final boolean hasElevation = (elevations != null && elevations.size() > 0);
        final boolean hasAdditionalDomains = additionalDomains.size() > 0;
        final boolean hasFilter = filter != null && !Filter.INCLUDE.equals(filter);

        // create query
        final SimpleFeatureType type = rasterManager.granuleCatalog.getType();
        Query query = null;
        Filter bbox = null;
        if (type != null) {
            query = new Query(rasterManager.granuleCatalog.getType().getTypeName());
            bbox = FeatureUtilities.DEFAULT_FILTER_FACTORY.bbox(
                    FeatureUtilities.DEFAULT_FILTER_FACTORY
                            .property(rasterManager.granuleCatalog.getType().getGeometryDescriptor().getName()),
                    mosaicBBox);
            query.setFilter(bbox);
        } else {
            throw new IllegalStateException("GranuleCatalog feature type was null!!!");
        }

        // prepare eventual filter for filtering granules
        // handle elevation indexing first since we then combine this with the max in case we are asking for current in time
        if (hasElevation) {

            final Filter elevationF = rasterManager.parent.elevationDomainManager
                    .createFilter(ImageMosaicReader.ELEVATION_DOMAIN, elevations);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), elevationF));
        }

        // handle generic filter since we then combine this with the max in case we are asking for current in time
        if (hasFilter) {
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), filter));
        }

        // fuse time query with the bbox query
        if (hasTime) {
            final Filter timeFilter = this.rasterManager.parent.timeDomainManager
                    .createFilter(ImageMosaicReader.TIME_DOMAIN, times);
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(), timeFilter));
        }

        if (hasAdditionalDomains) {
            final List<Filter> additionalFilter = new ArrayList<Filter>();
            for (Entry<String, List> entry : additionalDomains.entrySet()) {

                // build a filter for each dimension
                final String domainName = entry.getKey() + DomainDescriptor.DOMAIN_SUFFIX;
                additionalFilter.add(
                        rasterManager.parent.domainsManager.createFilter(domainName, (List) entry.getValue()));

            }
            // merge with existing ones
            query.setFilter(FeatureUtilities.DEFAULT_FILTER_FACTORY.and(query.getFilter(),
                    FeatureUtilities.DEFAULT_FILTER_FACTORY.and(additionalFilter)));
        }

        //
        // handle secondary query parameters
        //

        // max number of elements
        if (request.getMaximumNumberOfGranules() > 0) {
            query.setMaxFeatures(request.getMaximumNumberOfGranules());
        }

        // sort by clause
        final String sortByClause = request.getSortClause();
        if (sortByClause != null && sortByClause.length() > 0) {
            final String[] elements = sortByClause.split(",");
            if (elements != null && elements.length > 0) {
                final List<SortBy> clauses = new ArrayList<SortBy>(elements.length);
                for (String element : elements) {
                    // check
                    if (element == null || element.length() <= 0) {
                        continue;// next, please!
                    }
                    try {
                        // which clause?
                        // ASCENDING
                        element = element.trim();
                        if (element.endsWith(Utils.ASCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.ASCENDING));
                        } else
                        // DESCENDING
                        if (element.contains(Utils.DESCENDING_ORDER_IDENTIFIER)) {
                            String attribute = element.substring(0, element.length() - 2);
                            clauses.add(
                                    new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),
                                            SortOrder.DESCENDING));
                        }
                        //                        if(element.startsWith(Utils.ASCENDING_ORDER_IDENTIFIER)){
                        //                           String attribute=element.substring(Utils.ASCENDING_ORDER_IDENTIFIER.length()+1);
                        //                           attribute=attribute.substring(0, attribute.length()-1);
                        //                           clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.ASCENDING));
                        //                        } else 
                        //                           // DESCENDING
                        //                           if(element.startsWith(Utils.DESCENDING_ORDER_IDENTIFIER)){
                        //                               String attribute=element.substring(Utils.DESCENDING_ORDER_IDENTIFIER.length()+1);
                        //                               attribute=attribute.substring(0, attribute.length()-1);
                        //                               clauses.add(new SortByImpl(FeatureUtilities.DEFAULT_FILTER_FACTORY.property(attribute),SortOrder.DESCENDING));
                        //                        } else {
                        else {
                            if (LOGGER.isLoggable(Level.FINE)) {
                                LOGGER.fine("Ignoring sort clause :" + element);
                            }
                        }
                    } catch (Exception e) {
                        if (LOGGER.isLoggable(Level.INFO)) {
                            LOGGER.log(Level.INFO, e.getLocalizedMessage(), e);
                        }
                    }
                }

                // assign to query if sorting is supported!
                final SortBy[] sb = clauses.toArray(new SortBy[] {});
                if (rasterManager.granuleCatalog.getQueryCapabilities().supportsSorting(sb)) {
                    query.setSortBy(sb);
                }
            }
        }

        // collect granules
        rasterManager.getGranules(query, visitor);

        // get those granules
        visitor.produce();

        //
        // Did we actually load anything?? Notice that it might happen that
        // either we have holes inside the definition area for the mosaic
        // or we had some problem with missing tiles, therefore it might
        // happen that for some bboxes we don't have anything to load.
        //
        RenderedImage returnValue = null;
        if (visitor.granulesNumber >= 1) {

            //
            // Create the mosaic image by doing a crop if necessary and also
            // managing the transparent color if applicable. Be aware that
            // management of the transparent color involves removing
            // transparency information from the input images.
            //          
            returnValue = buildMosaic(visitor);
            if (returnValue != null) {
                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Loaded bbox " + mosaicBBox.toString() + " while crop bbox "
                            + request.getCropBBox().toString());
                return returnValue;
            }

        }

        // Redo the query without filter to check whether we got no granules due
        // to a filter. In that case we need to return null
        if (hasTime || hasElevation || hasFilter || hasAdditionalDomains) {
            query.setFilter(bbox);
            rasterManager.getGranules(query, visitor);
            // get those granules
            visitor.produce();
            if (visitor.granulesNumber >= 1) {
                // It means the previous lack of granule was due to a filter excluding all the results. Then we return null
                return null;
            }
        }

        if (LOGGER.isLoggable(Level.FINE))
            LOGGER.fine("Creating constant image for area with no data");

        // if we get here that means that we do not have anything to load
        // but still we are inside the definition area for the mosaic,
        // therefore we create a fake coverage using the background values,
        // if provided (defaulting to 0), as well as the compute raster
        // bounds, envelope and grid to world.

        final Number[] values = ImageUtilities.getBackgroundValues(rasterManager.defaultSM, backgroundValues);
        // create a constant image with a proper layout
        RenderedImage finalImage = ConstantDescriptor.create(Float.valueOf(rasterBounds.width),
                Float.valueOf(rasterBounds.height), values, null);
        if (rasterBounds.x != 0 || rasterBounds.y != 0) {
            finalImage = TranslateDescriptor.create(finalImage, Float.valueOf(rasterBounds.x),
                    Float.valueOf(rasterBounds.y), Interpolation.getInstance(Interpolation.INTERP_NEAREST),
                    null);
        }
        if (rasterManager.defaultCM != null) {
            final ImageLayout2 il = new ImageLayout2();
            il.setColorModel(rasterManager.defaultCM);
            Dimension tileSize = request.getTileDimensions();
            if (tileSize == null) {
                tileSize = JAI.getDefaultTileSize();
            }
            il.setSampleModel(
                    rasterManager.defaultCM.createCompatibleSampleModel(tileSize.width, tileSize.height));
            il.setTileGridXOffset(0).setTileGridYOffset(0).setTileWidth((int) tileSize.getWidth())
                    .setTileHeight((int) tileSize.getHeight());
            return FormatDescriptor.create(finalImage, Integer.valueOf(il.getSampleModel(null).getDataType()),
                    new RenderingHints(JAI.KEY_IMAGE_LAYOUT, il));
        }
        return finalImage;

    } catch (Exception e) {
        throw new DataSourceException("Unable to create this mosaic", e);
    }
}

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

@Override
public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    Rectangle clipRect = g.getClipBounds();
    Dimension compSize = getSize();
    // columnCount = (int)(compSize.getWidth()/columnWidth);

    int photoCount = 0;
    if (photos != null) {
        photoCount = photos.size();//from  w ww.j  av a  2 s .c o m
    }

    // Determine the grid size based on couln & row count
    columnsToPaint = columnCount;
    // if columnCount is not specified determine it based on row count
    if (columnCount < 0) {
        if (rowCount > 0) {
            columnsToPaint = photoCount / rowCount;
            if (columnsToPaint * rowCount < photoCount) {
                columnsToPaint++;
            }
        } else {
            columnsToPaint = (int) (compSize.getWidth() / columnWidth);
        }
    }

    int col = 0;
    int row = 0;
    Rectangle thumbRect = new Rectangle();

    for (PhotoInfo photo : photos) {
        thumbRect.setBounds(col * columnWidth, row * rowHeight, columnWidth, rowHeight);
        if (thumbRect.intersects(clipRect)) {
            if (photo != null) {
                paintThumbnail(g2, photo, col * columnWidth, row * rowHeight, selection.contains(photo));
            }
        }
        col++;
        if (col >= columnsToPaint) {
            row++;
            col = 0;
        }
    }

    // Paint the selection rectangle if needed
    if (dragSelectionRect != null) {
        Stroke prevStroke = g2.getStroke();
        Color prevColor = g2.getColor();
        g2.setStroke(new BasicStroke(1.0f));
        g2.setColor(Color.BLACK);
        g2.draw(dragSelectionRect);
        g2.setColor(prevColor);
        g2.setStroke(prevStroke);
        lastDragSelectionRect = dragSelectionRect;
    }
}

From source file:com.centurylink.mdw.designer.pages.ExportHelper.java

public void printImagePdf(String filename, DesignerCanvas canvas, Dimension graphsize) {
    try {/*from  ww w  .j ava  2s. co m*/
        DefaultFontMapper mapper = new DefaultFontMapper();
        FontFactory.registerDirectories();
        mapper.insertDirectory("c:\\winnt\\fonts");
        // mapper.insertDirectory("c:\\windows\\fonts");
        // we create a template and a Graphics2D object that corresponds
        // with it
        int margin = 72; // 1 inch
        float scale = 0.5f;
        boolean multiple_page = true;
        Rectangle page_size;
        if (multiple_page) {
            page_size = PageSize.LETTER.rotate();
        } else {
            page_size = new Rectangle((int) (graphsize.getWidth() * scale) + margin,
                    (int) (graphsize.getHeight() * scale) + margin);
        }
        Document document = new Document(page_size);
        DocWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
        document.open();
        document.setPageSize(page_size);
        int image_w = (int) page_size.getWidth() - margin;
        int image_h = (int) page_size.getHeight() - margin;
        boolean edsave = canvas.editable;
        canvas.editable = false;
        Color bgsave = canvas.getBackground();
        canvas.setBackground(Color.white);
        if (multiple_page) {
            int horizontal_pages = (int) (graphsize.width * scale) / image_w + 1;
            int vertical_pages = (int) (graphsize.height * scale) / image_h + 1;
            for (int i = 0; i < horizontal_pages; i++) {
                for (int j = 0; j < vertical_pages; j++) {
                    Image img;
                    PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
                    PdfTemplate tp = cb.createTemplate(image_w, image_h);
                    Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
                    tp.setWidth(image_w);
                    tp.setHeight(image_h);
                    g2.scale(scale, scale);
                    g2.translate(-i * image_w / scale, -j * image_h / scale);
                    canvas.paintComponent(g2);
                    g2.dispose();
                    img = new ImgTemplate(tp);
                    document.add(img);
                }
            }
        } else {
            Image img;
            PdfContentByte cb = ((PdfWriter) writer).getDirectContent();
            PdfTemplate tp = cb.createTemplate(image_w, image_h);
            Graphics2D g2 = tp.createGraphics(image_w, image_h, mapper);
            tp.setWidth(image_w);
            tp.setHeight(image_h);
            g2.scale(scale, scale);
            canvas.paintComponent(g2);
            g2.dispose();
            img = new ImgTemplate(tp);
            document.add(img);
        }
        canvas.setBackground(bgsave);
        canvas.editable = edsave;
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.fop.render.pcl.PCLGenerator.java

private RenderedImage getMask(RenderedImage img, Dimension targetDim) {
    ColorModel cm = img.getColorModel();
    if (cm.hasAlpha()) {
        BufferedImage alpha = new BufferedImage(img.getWidth(), img.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
        Raster raster = img.getData();
        GraphicsUtil.copyBand(raster, cm.getNumColorComponents(), alpha.getRaster(), 0);

        BufferedImageOp op1 = new LookupOp(new ByteLookupTable(0, THRESHOLD_TABLE), null);
        BufferedImage alphat = op1.filter(alpha, null);

        BufferedImage mask;//ww  w .  j  a v a 2  s  .  co m
        if (true) {
            mask = new BufferedImage(targetDim.width, targetDim.height, BufferedImage.TYPE_BYTE_BINARY);
        } else {
            byte[] arr = { (byte) 0, (byte) 0xff };
            ColorModel colorModel = new IndexColorModel(1, 2, arr, arr, arr);
            WritableRaster wraster = Raster.createPackedRaster(DataBuffer.TYPE_BYTE, targetDim.width,
                    targetDim.height, 1, 1, null);
            mask = new BufferedImage(colorModel, wraster, false, null);
        }

        Graphics2D g2d = mask.createGraphics();
        try {
            AffineTransform at = new AffineTransform();
            double sx = targetDim.getWidth() / img.getWidth();
            double sy = targetDim.getHeight() / img.getHeight();
            at.scale(sx, sy);
            g2d.drawRenderedImage(alphat, at);
        } finally {
            g2d.dispose();
        }
        /*
        try {
        BatchDiffer.saveAsPNG(alpha, new java.io.File("D:/out-alpha.png"));
        BatchDiffer.saveAsPNG(mask, new java.io.File("D:/out-mask.png"));
        } catch (IOException e) {
        e.printStackTrace();
        }*/
        return mask;
    } else {
        return null;
    }
}

From source file:jhplot.HChart.java

/**
 * Resize the pad given by the inxX and indxY. It calculates the original
 * pad sizes, and then scale it by a given factor. In this case, the pad
 * sizes can be different./*from  ww  w.j a  va 2s  .  c  o  m*/
 * 
 * @param n1
 *            the location of the plot in x
 * @param n2
 *            the location of the plot in y
 * 
 * @param widthScale
 *            scale factor applied to the width of the current pad
 * @param heightScale
 *            scale factor applied the height of the current pad.
 */
public void resizePad(int n1, int n2, double widthScale, double heightScale) {
    Dimension dim = cp[n1][n2].getSize();
    double h = dim.getHeight();
    double w = dim.getWidth();
    cp[n1][n2].setPreferredSize(new Dimension((int) (w * widthScale), (int) (h * heightScale)));
    cp[n1][n2].setMinimumSize(new Dimension((int) (w * widthScale), (int) (h * heightScale)));
    cp[n1][n2].setSize(new Dimension((int) (w * widthScale), (int) (h * heightScale)));
}

From source file:jhplot.HChart.java

/**
 * Resize the current pad. It calculates the original pad sizes, and then
 * scale it by a given factor. In this case, the pad sizes can be different.
 * /*from   w w  w. jav  a 2 s.c  om*/
 * @param widthScale
 *            scale factor applied to the width of the current pad
 * @param heightScale
 *            scale factor applied the height of the current pad.
 */

public void resizePad(double widthScale, double heightScale) {

    Dimension dim = cp[N1][N2].getSize();
    double h = dim.getHeight();
    double w = dim.getWidth();
    cp[N1][N2].setPreferredSize(new Dimension((int) (w * widthScale), (int) (h * heightScale)));
    cp[N1][N2].setMinimumSize(new Dimension((int) (w * widthScale), (int) (h * heightScale)));
    cp[N1][N2].setSize(new Dimension((int) (w * widthScale), (int) (h * heightScale)));
}

From source file:it.cnr.icar.eric.client.ui.swing.RegistryBrowser.java

/**
 * Creates a new RegistryBrowser object.
 *//*from  ww  w .  j  ava2  s .  c o  m*/
@SuppressWarnings("unchecked")
private RegistryBrowser() {
    instance = this;

    classLoader = getClass().getClassLoader(); // new
    // JAXRBrowserClassLoader(getClass().getClassLoader());
    Thread.currentThread().setContextClassLoader(classLoader);

    /*
     * try { classLoader.loadClass("javax.xml.soap.SOAPMessage"); } catch
     * (ClassNotFoundException e) {
     * log.error("Could not find class javax.xml.soap.SOAPMessage", e); }
     */

    UIManager.addPropertyChangeListener(new UISwitchListener(getRootPane()));

    // add listener for 'locale' bound property
    addPropertyChangeListener(PROPERTY_LOCALE, this);

    menuBar = new JMenuBar();
    fileMenu = new JMenu();
    editMenu = new JMenu();
    viewMenu = new JMenu();
    helpMenu = new JMenu();

    JSeparator JSeparator1 = new JSeparator();
    newItem = new JMenuItem();
    importItem = new JMenuItem();
    saveItem = new JMenuItem();
    saveAsItem = new JMenuItem();
    exitItem = new JMenuItem();
    cutItem = new JMenuItem();
    copyItem = new JMenuItem();
    pasteItem = new JMenuItem();
    aboutItem = new JMenuItem();
    setJMenuBar(menuBar);
    setTitle(resourceBundle.getString("title.registryBrowser.java"));
    setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    getContentPane().setLayout(new BorderLayout(0, 0));

    // Scale window to be centered using 70% of screen
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

    setBounds((int) (dim.getWidth() * .15), (int) (dim.getHeight() * .1), (int) (dim.getWidth() * .7),
            (int) (dim.getHeight() * .75));
    setVisible(false);
    saveFileDialog.setMode(FileDialog.SAVE);
    saveFileDialog.setTitle(resourceBundle.getString("dialog.save.title"));

    GridBagLayout gb = new GridBagLayout();

    topPanel.setLayout(gb);
    getContentPane().add("North", topPanel);

    GridBagConstraints c = new GridBagConstraints();
    toolbarPanel.setLayout(new FlowLayout(FlowLayout.LEADING, 0, 0));
    toolbarPanel.setBounds(0, 0, 488, 29);

    discoveryToolBar = createDiscoveryToolBar();
    toolbarPanel.add(discoveryToolBar);

    // c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.5;
    c.weighty = 0.5;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 0, 0);
    gb.setConstraints(toolbarPanel, c);
    topPanel.add(toolbarPanel);

    // Panel containing context info like registry location and user context
    JPanel contextPanel = new JPanel();
    GridBagLayout gb1 = new GridBagLayout();
    contextPanel.setLayout(gb1);

    locationLabel = new JLabel(resourceBundle.getString("label.registryLocation"));

    // locationLabel.setPreferredSize(new Dimension(80, 23));
    // c.gridx = 0;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.0;
    c.weighty = 0.5;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 5, 0, 0);
    gb1.setConstraints(locationLabel, c);

    // contextPanel.setBackground(Color.green);
    contextPanel.add(locationLabel);

    selectAnItemText = new ItemText(selectAnItem);
    registryCombo.addItem(selectAnItemText.toString());

    ConfigurationType uiConfigurationType = UIUtility.getInstance().getConfigurationType();
    RegistryURIListType urlList = uiConfigurationType.getRegistryURIList();

    List<String> urls = urlList.getRegistryURI();
    Iterator<String> urlsIter = urls.iterator();
    while (urlsIter.hasNext()) {
        ItemText url = new ItemText(urlsIter.next());
        registryCombo.addItem(url.toString());
    }

    registryCombo.setEditable(true);
    registryCombo.setEnabled(true);
    registryCombo.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            final String url = (String) registryCombo.getSelectedItem();
            if ((url == null) || (url.equals(selectAnItem))) {
                return;
            }

            // Clean tabbedPaneParent. Will create new content
            tabbedPaneParent.removeAll();
            conceptsTreeDialog = null;
            ConceptsTreeDialog.clearCache();

            // design:
            // 1. connect and construct tabbedPane in a now swing thread
            // 2. add tabbedPane in swing thread
            // 3. call reloadModel that should use WingWorkers
            final SwingWorker worker1 = new SwingWorker(RegistryBrowser.this) {
                public Object doNonUILogic() {
                    try {
                        // Try to connect
                        if (connectToRegistry(url)) {
                            return new JBTabbedPane();
                        }
                    } catch (JAXRException e1) {
                        displayError(e1);
                    }
                    return null;
                }

                public void doUIUpdateLogic() {
                    tabbedPane = (JBTabbedPane) get();
                    if (tabbedPane != null) {
                        tabbedPaneParent.add(tabbedPane, BorderLayout.CENTER);
                        tabbedPane.reloadModel();
                        try {
                            // DBH 1/30/04 - Add the submissions panel if
                            // the user is authenticated.
                            ConnectionImpl connection = RegistryBrowser.client.connection;
                            boolean newValue = connection.isAuthenticated();
                            firePropertyChange(PROPERTY_AUTHENTICATED, false, newValue);
                            getRootPane().updateUI();
                        } catch (JAXRException e1) {
                            displayError(e1);
                        }
                    }
                }
            };
            worker1.start();
        }
    });
    // c.gridx = 1;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.9;
    c.weighty = 0.5;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new Insets(0, 0, 5, 0);
    gb1.setConstraints(registryCombo, c);
    contextPanel.add(registryCombo);

    JLabel currentUserLabel = new JLabel(resourceBundle.getString("label.currentUser"),
            SwingConstants.TRAILING);
    c.gridx = 2;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.0;
    c.weighty = 0.0;
    c.fill = GridBagConstraints.NONE;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 5, 5, 0);
    gb1.setConstraints(currentUserLabel, c);

    // contextPanel.add(currentUserLabel);
    currentUserText.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent evt) {
            @SuppressWarnings("unused")
            String text = currentUserText.getText();
        }
    });

    currentUserText.setEditable(false);
    c.gridx = 3;
    c.gridy = 0;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.9;
    c.weighty = 0.5;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.LINE_START;
    c.insets = new Insets(0, 0, 5, 5);
    gb1.setConstraints(currentUserText, c);

    // contextPanel.add(currentUserText);
    c.gridx = 0;
    c.gridy = 1;
    c.gridwidth = 1;
    c.gridheight = 1;
    c.weightx = 0.9;
    c.weighty = 0.5;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.anchor = GridBagConstraints.CENTER;
    c.insets = new Insets(0, 0, 0, 0);
    gb.setConstraints(contextPanel, c);
    topPanel.add(contextPanel, c);

    tabbedPaneParent.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
    tabbedPaneParent.setLayout(new BorderLayout());
    tabbedPaneParent.setToolTipText(resourceBundle.getString("tabbedPane.tip"));

    getContentPane().add("Center", tabbedPaneParent);

    fileMenu.setText(resourceBundle.getString("menu.file"));
    fileMenu.setActionCommand("File");
    fileMenu.setMnemonic((int) 'F');
    menuBar.add(fileMenu);

    saveItem.setHorizontalTextPosition(SwingConstants.TRAILING);
    saveItem.setText(resourceBundle.getString("menu.save"));
    saveItem.setActionCommand("Save");
    saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, Event.CTRL_MASK));
    saveItem.setMnemonic((int) 'S');

    // fileMenu.add(saveItem);
    fileMenu.add(JSeparator1);
    importItem.setText(resourceBundle.getString("menu.import"));
    importItem.setActionCommand("Import");
    importItem.setMnemonic((int) 'I');
    importItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            RegistryBrowser.setWaitCursor();
            importFromFile();
            RegistryBrowser.setDefaultCursor();
        }
    });
    fileMenu.add(importItem);

    exitItem.setText(resourceBundle.getString("menu.exit"));
    exitItem.setActionCommand("Exit");
    exitItem.setMnemonic((int) 'X');
    fileMenu.add(exitItem);

    editMenu.setText(resourceBundle.getString("menu.edit"));
    editMenu.setActionCommand("Edit");
    editMenu.setMnemonic((int) 'E');

    // menuBar.add(editMenu);
    cutItem.setHorizontalTextPosition(SwingConstants.TRAILING);
    cutItem.setText(resourceBundle.getString("menu.cut"));
    cutItem.setActionCommand("Cut");
    cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, Event.CTRL_MASK));
    cutItem.setMnemonic((int) 'T');
    editMenu.add(cutItem);

    copyItem.setHorizontalTextPosition(SwingConstants.TRAILING);
    copyItem.setText(resourceBundle.getString("menu.copy"));
    copyItem.setActionCommand("Copy");
    copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, Event.CTRL_MASK));
    copyItem.setMnemonic((int) 'C');
    editMenu.add(copyItem);

    pasteItem.setHorizontalTextPosition(SwingConstants.TRAILING);
    pasteItem.setText(resourceBundle.getString("menu.paste"));
    pasteItem.setActionCommand("Paste");
    pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, Event.CTRL_MASK));
    pasteItem.setMnemonic((int) 'P');
    editMenu.add(pasteItem);

    viewMenu.setText(resourceBundle.getString("menu.view"));
    viewMenu.setActionCommand("view");
    viewMenu.setMnemonic((int) 'V');

    themeMenu = new MetalThemeMenu(resourceBundle.getString("menu.theme"), themes);
    viewMenu.add(themeMenu);
    menuBar.add(viewMenu);

    helpMenu.setText(resourceBundle.getString("menu.help"));
    helpMenu.setActionCommand("Help");
    helpMenu.setMnemonic((int) 'H');
    menuBar.add(helpMenu);
    aboutItem.setHorizontalTextPosition(SwingConstants.TRAILING);
    aboutItem.setText(resourceBundle.getString("menu.about"));
    aboutItem.setActionCommand("About...");
    aboutItem.setMnemonic((int) 'A');

    aboutItem.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Object[] aboutArgs = { BROWSER_VERSION };
            MessageFormat form = new MessageFormat(resourceBundle.getString("dialog.about.text"));
            JOptionPane.showMessageDialog(RegistryBrowser.this, form.format(aboutArgs),
                    resourceBundle.getString("dialog.about.title"), JOptionPane.INFORMATION_MESSAGE);
        }
    });

    helpMenu.add(aboutItem);

    // REGISTER_LISTENERS
    SymWindow aSymWindow = new SymWindow();

    this.addWindowListener(aSymWindow);

    SymAction lSymAction = new SymAction();

    saveItem.addActionListener(lSymAction);
    exitItem.addActionListener(lSymAction);

    SwingUtilities.updateComponentTreeUI(getContentPane());
    SwingUtilities.updateComponentTreeUI(menuBar);
    SwingUtilities.updateComponentTreeUI(fileChooser);

    // Auto select the registry that is configured to connect to by default
    String selectedIndexStr = ProviderProperties.getInstance()
            .getProperty("jaxr-ebxml.registryBrowser.registryLocationCombo.initialSelectionIndex", "0");

    int index = Integer.parseInt(selectedIndexStr);

    try {
        registryCombo.setSelectedIndex(index);
    } catch (IllegalArgumentException e) {
        Object[] invalidIndexArguments = { new Integer(index) };
        MessageFormat form = new MessageFormat(resourceBundle.getString("message.error.invalidIndex"));
        displayError(form.format(invalidIndexArguments), e);
    }
}

From source file:org.yccheok.jstock.gui.charting.ChartJDialog.java

/** Creates new form ChartJDialog */
public ChartJDialog(java.awt.Frame parent, String title, boolean modalNotUsed,
        StockHistoryServer stockHistoryServer) {
    super(title);

    this.parent = parent;
    this.parent.addWindowListener(this);

    this.setIconImage(parent.getIconImage());

    initComponents();/*w  w w  . j a va  2s .c  o m*/
    initKeyBindings();

    // Must initialized first before any other operations. Our objective
    // is to show this chart as fast as possible. Hence, we will pass in
    // null first, till we sure what are we going to create.
    this.chartPanel = new ChartPanel(null, true, true, true, true, true);
    this.stockHistoryServer = stockHistoryServer;

    final ChartJDialogOptions chartJDialogOptions = JStock.instance().getChartJDialogOptions();
    this.changeInterval(chartJDialogOptions.getInterval());

    // Yellow box and chart resizing (#2969416)
    //
    // paradoxoff :
    // If the available size for a ChartPanel exceeds the dimensions defined
    // by the maximumDrawWidth and maximumDrawHeight attributes, the
    // ChartPanel will draw the chart in a Rectangle defined by the maximum
    // sizes and then scale it to fill the available size.
    // All you need to do is to avoid that scaling by using sufficiently
    // large values for the maximumDrawWidth and maximumDrawHeight, e. g.
    // by using the Dimension returned from
    // Toolkit.getDefaultToolkit().getScreenSize()
    // http://www.jfree.org/phpBB2/viewtopic.php?f=3&t=30059
    final Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
    this.chartPanel.setMaximumDrawWidth((int) Math.round(dimension.getWidth()));
    this.chartPanel.setMaximumDrawHeight((int) Math.round(dimension.getHeight()));

    // Make chartPanel able to receive key event.
    // So that we may use arrow key to move around yellow information box.
    this.chartPanel.setFocusable(true);
    this.chartPanel.requestFocus();

    final org.jdesktop.jxlayer.JXLayer<ChartPanel> layer = new org.jdesktop.jxlayer.JXLayer<ChartPanel>(
            this.chartPanel);
    this.chartLayerUI = new ChartLayerUI<ChartPanel>(this);
    layer.setUI(this.chartLayerUI);

    // Call after JXLayer has been initialized. changeType assumes JXLayer 
    // is ready.
    this.changeType(chartJDialogOptions.getType());

    getContentPane().add(layer, java.awt.BorderLayout.CENTER);

    // Handle resize.
    this.addComponentListener(new java.awt.event.ComponentAdapter() {
        @Override
        public void componentResized(ComponentEvent e) {
            ChartJDialog.this.chartLayerUI.updateTraceInfos();
        }
    });

    // Update GUI.
    if (JStock.instance().getJStockOptions().getChartTheme() == JStockOptions.ChartTheme.Light) {
        this.jRadioButtonMenuItem3.setSelected(true);
    } else {
        this.jRadioButtonMenuItem4.setSelected(true);
    }
}

From source file:org.gtdfree.GTDFree.java

private void flashMessage(String string, Point location) {
    if (flasher == null) {
        flasher = new JWindow();
        flasher.addMouseListener(new MouseAdapter() {
            @Override// www .j a v  a  2  s. co  m
            public void mouseClicked(MouseEvent e) {
                flasher.setVisible(false);
            }
        });
        flasher.setContentPane(flasherText = new JLabel());
        flasherText.setBorder(new Border() {
            Insets insets = new Insets(5, 11, 5, 11);

            @Override
            public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
                //
            }

            @Override
            public boolean isBorderOpaque() {
                return false;
            }

            @Override
            public Insets getBorderInsets(Component c) {
                return insets;
            }
        });
        flasherText.setBackground(new Color(0xf3f3ad));
        flasherText.setOpaque(true);
    }
    flasher.setVisible(false);
    flasherText.setText(string);
    flasher.pack();
    flasher.setLocation(location.x - flasher.getWidth() / 2, location.y - flasher.getHeight());
    if (flasher.getLocation().x < 0) {
        flasher.setLocation(0, flasher.getLocation().y);
    }
    if (flasher.getLocation().y < 0) {
        flasher.setLocation(flasher.getLocation().x, 0);
    }
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    if (flasher.getLocation().x + flasher.getWidth() > d.getWidth()) {
        flasher.setLocation((int) (d.getWidth() - flasher.getWidth()), flasher.getLocation().y);
    }
    if (flasher.getLocation().y + flasher.getHeight() > d.getHeight()) {
        flasher.setLocation(flasher.getLocation().x, (int) (d.getHeight() - flasher.getHeight()));
    }
    flasher.setVisible(true);
    new Thread() {
        @Override
        public synchronized void run() {
            try {
                wait(3000);
            } catch (InterruptedException e) {
                Logger.getLogger(this.getClass()).debug("Internal error.", e); //$NON-NLS-1$
            }
            flasher.setVisible(false);
        }
    }.start();
}