Example usage for java.awt Font createFont

List of usage examples for java.awt Font createFont

Introduction

In this page you can find the example usage for java.awt Font createFont.

Prototype

public static Font createFont(int fontFormat, File fontFile)
        throws java.awt.FontFormatException, java.io.IOException 

Source Link

Document

Returns a new Font using the specified font type and the specified font file.

Usage

From source file:fr.fg.server.core.TerritoryManager.java

private static BufferedImage createTerritoryMap(int idSector) {
    List<Area> areas = new ArrayList<Area>(DataAccess.getAreasBySector(idSector));

    float[][] points = new float[areas.size()][2];
    int[] dominatingAllies = new int[areas.size()];
    int i = 0;/* ww w.ja  va  2s . co m*/
    for (Area area : areas) {
        points[i][0] = area.getX() * MAP_SCALE;
        points[i][1] = area.getY() * MAP_SCALE;
        dominatingAllies[i] = area.getIdDominatingAlly();
        i++;
    }

    Hull hull = new Hull(points);
    MPolygon hullPolygon = hull.getRegion();
    float[][] newPoints = new float[points.length + hullPolygon.count()][2];
    System.arraycopy(points, 0, newPoints, 0, points.length);

    float[][] hullCoords = hullPolygon.getCoords();

    for (i = 0; i < hullPolygon.count(); i++) {
        double angle = Math.atan2(hullCoords[i][1], hullCoords[i][0]);
        double length = Math.sqrt(hullCoords[i][0] * hullCoords[i][0] + hullCoords[i][1] * hullCoords[i][1]);

        newPoints[i + points.length][0] = (float) (Math.cos(angle) * (length + 8 * MAP_SCALE));
        newPoints[i + points.length][1] = (float) (Math.sin(angle) * (length + 8 * MAP_SCALE));
    }

    points = newPoints;

    Voronoi voronoi = new Voronoi(points);
    Delaunay delaunay = new Delaunay(points);

    // Dcoupage en rgions
    MPolygon[] regions = voronoi.getRegions();

    // Calcule le rayon de la galaxie
    int radius = 0;

    for (Area area : areas) {
        radius = Math.max(radius, area.getX() * area.getX() + area.getY() * area.getY());
    }

    radius = (int) Math.floor(Math.sqrt(radius) * MAP_SCALE) + 10 * MAP_SCALE;
    int diameter = 2 * radius + 1;

    // Construit l'image avec les quadrants
    BufferedImage territoriesImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    Graphics2D g = (Graphics2D) territoriesImage.getGraphics();

    // Affecte une couleur  chaque alliance
    HashMap<Integer, Color> alliesColors = new HashMap<Integer, Color>();

    for (Area area : areas) {
        int idDominatingAlly = area.getIdDominatingAlly();
        if (idDominatingAlly != 0)
            alliesColors.put(idDominatingAlly,
                    Ally.TERRITORY_COLORS[DataAccess.getAllyById(idDominatingAlly).getColor()]);
    }

    Polygon[] polygons = new Polygon[regions.length];
    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] != 0) {
            polygons[i] = createPolygon(regions[i].getCoords(), radius + 1, 3);
        }
    }

    // Dessine tous les secteurs
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        Polygon p = polygons[i];

        // Dessine le polygone
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.fill(p);

        // Rempli les espaces entre les polygones adjacents qui
        // correspondent au territoire d'une mme alliance
        int[] linkedRegions = delaunay.getLinked(i);
        for (int j = 0; j < linkedRegions.length; j++) {
            int linkedRegion = linkedRegions[j];

            if (linkedRegion >= areas.size())
                continue;

            if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                if (linkedRegion <= i)
                    continue;

                float[][] coords1 = regions[i].getCoords();
                float[][] coords2 = regions[linkedRegion].getCoords();

                int junctionIndex = 0;
                int[][] junctions = new int[2][2];

                search: for (int k = 0; k < coords1.length; k++) {
                    for (int l = 0; l < coords2.length; l++) {
                        if (coords1[k][0] == coords2[l][0] && coords1[k][1] == coords2[l][1]) {
                            junctions[junctionIndex][0] = k;
                            junctions[junctionIndex][1] = l;

                            junctionIndex++;

                            if (junctionIndex == 2) {
                                int[] xpts = new int[] { polygons[i].xpoints[junctions[0][0]],
                                        polygons[linkedRegion].xpoints[junctions[0][1]],
                                        polygons[linkedRegion].xpoints[junctions[1][1]],
                                        polygons[i].xpoints[junctions[1][0]], };
                                int[] ypts = new int[] { polygons[i].ypoints[junctions[0][0]],
                                        polygons[linkedRegion].ypoints[junctions[0][1]],
                                        polygons[linkedRegion].ypoints[junctions[1][1]],
                                        polygons[i].ypoints[junctions[1][0]], };

                                Polygon border = new Polygon(xpts, ypts, 4);
                                g.setStroke(new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_ROUND));
                                g.fill(border);
                                g.draw(border);
                                break search;
                            }
                            break;
                        }
                    }
                }
            }
        }
    }

    // Dessine des lignes de contours des territoires
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0)
            continue;

        g.setStroke(new BasicStroke(1.5f));
        g.setColor(alliesColors.get(dominatingAllies[i]).brighter().brighter());

        float[][] coords1 = regions[i].getCoords();

        lines: for (int j = 0; j < coords1.length; j++) {
            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]
                                && ((coords1[(j + 1) % coords1.length][0] == coords2[(m + 1)
                                        % coords2.length][0]
                                        && coords1[(j + 1) % coords1.length][1] == coords2[(m + 1)
                                                % coords2.length][1])
                                        || (coords1[(j + 1)
                                                % coords1.length][0] == coords2[(m - 1 + coords2.length)
                                                        % coords2.length][0]
                                                && coords1[(j + 1)
                                                        % coords1.length][1] == coords2[(m - 1 + coords2.length)
                                                                % coords2.length][1]))) {
                            continue lines;
                        }
                    }
                }
            }

            g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                    Math.round(polygons[i].xpoints[(j + 1) % coords1.length]),
                    Math.round(polygons[i].ypoints[(j + 1) % coords1.length]));
        }

        for (int j = 0; j < coords1.length; j++) {
            int neighbours = 0;
            int lastNeighbourRegion = -1;
            int neighbourCoordsIndex = -1;

            int[] linkedRegions = delaunay.getLinked(i);
            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size())
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion]) {
                    float[][] coords2 = regions[linkedRegion].getCoords();

                    for (int m = 0; m < coords2.length; m++) {
                        if (coords1[j][0] == coords2[m][0] && coords1[j][1] == coords2[m][1]) {
                            neighbours++;
                            lastNeighbourRegion = linkedRegion;
                            neighbourCoordsIndex = m;
                            break;
                        }
                    }
                }
            }

            if (neighbours == 1) {
                g.drawLine(Math.round(polygons[i].xpoints[j]), Math.round(polygons[i].ypoints[j]),
                        Math.round(polygons[lastNeighbourRegion].xpoints[neighbourCoordsIndex]),
                        Math.round(polygons[lastNeighbourRegion].ypoints[neighbourCoordsIndex]));
            }
        }
    }

    BufferedImage finalImage = new BufferedImage(diameter, diameter, BufferedImage.TYPE_INT_ARGB);

    g = (Graphics2D) finalImage.getGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .15f));
    g.drawImage(territoriesImage, 0, 0, null);
    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC, .5f));

    // Charge la police pour afficher le nom des alliances
    try {
        Font textFont = Font.createFont(Font.TRUETYPE_FONT,
                Action.class.getClassLoader().getResourceAsStream("fr/fg/server/resources/TinDog.ttf"));
        textFont = textFont.deriveFont(12f).deriveFont(Font.BOLD);
        g.setFont(textFont);
    } catch (Exception e) {
        LoggingSystem.getServerLogger().warn("Could not load quadrant map font.", e);
    }
    FontMetrics fm = g.getFontMetrics();

    ArrayList<Integer> closedRegions = new ArrayList<Integer>();

    for (i = 0; i < areas.size(); i++) {
        if (dominatingAllies[i] == 0 || closedRegions.contains(i))
            continue;

        ArrayList<Integer> allyRegions = new ArrayList<Integer>();
        ArrayList<Integer> openRegions = new ArrayList<Integer>();

        openRegions.add(i);

        while (openRegions.size() > 0) {
            int currentRegion = openRegions.remove(0);
            allyRegions.add(currentRegion);
            closedRegions.add(currentRegion);

            int[] linkedRegions = delaunay.getLinked(currentRegion);

            for (int k = 0; k < linkedRegions.length; k++) {
                int linkedRegion = linkedRegions[k];

                if (linkedRegion >= areas.size() || openRegions.contains(linkedRegion)
                        || allyRegions.contains(linkedRegion))
                    continue;

                if (dominatingAllies[i] == dominatingAllies[linkedRegion])
                    openRegions.add(linkedRegion);
            }
        }

        Area area = areas.get(i);
        long xsum = 0;
        long ysum = 0;

        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);
            area = areas.get(allyRegion);

            xsum += area.getX();
            ysum += area.getY();
        }

        int x = (int) (xsum / allyRegions.size()) * MAP_SCALE + radius + 1;
        int y = (int) (-ysum / allyRegions.size()) * MAP_SCALE + radius + 1;
        ;

        Point point = new Point(x, y);
        boolean validLocation = false;
        for (int k = 0; k < allyRegions.size(); k++) {
            int allyRegion = allyRegions.get(k);

            if (polygons[allyRegion].contains(point)) {
                validLocation = true;
                break;
            }
        }

        if (validLocation) {
            if (allyRegions.size() == 1)
                y -= 14;
        } else {
            int xmid = (int) (xsum / allyRegions.size());
            int ymid = (int) (ysum / allyRegions.size());

            area = areas.get(i);
            int dx = area.getX() - xmid;
            int dy = area.getY() - ymid;
            int distance = dx * dx + dy * dy;

            int nearestAreaIndex = i;
            int nearestDistance = distance;

            for (int k = 0; k < allyRegions.size(); k++) {
                int allyRegion = allyRegions.get(k);

                area = areas.get(allyRegion);
                dx = area.getX() - xmid;
                dy = area.getY() - ymid;
                distance = dx * dx + dy * dy;

                if (distance < nearestDistance) {
                    nearestAreaIndex = allyRegion;
                    nearestDistance = distance;
                }
            }

            area = areas.get(nearestAreaIndex);
            x = area.getX() * MAP_SCALE + radius + 1;
            y = -area.getY() * MAP_SCALE + radius - 13;
        }

        // Dessine le tag de l'alliance
        String allyTag = "[ " + DataAccess.getAllyById(dominatingAllies[i]).getTag() + " ]";
        g.setColor(Color.BLACK);
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2 + 1, y);
        g.setColor(alliesColors.get(dominatingAllies[i]));
        g.drawString(allyTag, x - fm.stringWidth(allyTag) / 2, y);
    }

    return finalImage;
}

From source file:cognitivej.vision.overlay.builder.ImageOverlayBuilder.java

private ImageOverlayBuilder(@NotNull BufferedImage bufferedImage) {
    this.bufferedImage = bufferedImage;
    try {/*w  w  w  .j a v  a 2  s . co  m*/
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(Font.createFont(Font.TRUETYPE_FONT,
                new File("src/main/resources/font/notosans/NotoSans-Bold.ttf")));
    } catch (IOException | FontFormatException ignored) {
    }

}

From source file:org.apache.pdfbox.pdmodel.font.PDTrueTypeFont.java

/**
 * {@inheritDoc}//www  .  j a v a 2  s  . c o m
 */
public Font getawtFont() throws IOException {
    PDFontDescriptorDictionary fd = (PDFontDescriptorDictionary) getFontDescriptor();
    if (awtFont == null) {
        PDStream ff2Stream = fd.getFontFile2();
        if (ff2Stream != null) {
            try {
                // create a font with the embedded data
                awtFont = Font.createFont(Font.TRUETYPE_FONT, ff2Stream.createInputStream());
            } catch (FontFormatException f) {
                log.info("Can't read the embedded font " + fd.getFontName());
            }
            if (awtFont == null) {
                awtFont = FontManager.getAwtFont(fd.getFontName());
                if (awtFont != null) {
                    log.info("Using font " + awtFont.getName() + " instead");
                }
                setIsFontSubstituted(true);
            }
        } else {
            // check if the font is part of our environment
            awtFont = FontManager.getAwtFont(fd.getFontName());
            if (awtFont == null) {
                log.info("Can't find the specified font " + fd.getFontName());
                // check if there is a font mapping for an external font file
                TrueTypeFont ttf = getExternalFontFile2(fd);
                if (ttf != null) {
                    try {
                        awtFont = Font.createFont(Font.TRUETYPE_FONT, ttf.getOriginalData());
                    } catch (FontFormatException f) {
                        log.info("Can't read the external fontfile " + fd.getFontName());
                    }
                }
            }
        }
        if (awtFont == null) {
            // we can't find anything, so we have to use the standard font
            awtFont = FontManager.getStandardFont();
            log.info("Using font " + awtFont.getName() + " instead");
            setIsFontSubstituted(true);
        }
    }
    return awtFont;
}

From source file:org.apache.pdfbox.pdmodel.font.PDType1CFont.java

private static Font prepareAwtFont(CFFFont font) throws IOException {
    byte[] type1Bytes = Type1FontFormatter.format(font);

    InputStream is = new ByteArrayInputStream(type1Bytes);
    try {//from   w w  w  .  j  ava 2  s . c  o m
        return Font.createFont(Font.TYPE1_FONT, is);
    } catch (FontFormatException ffe) {
        throw new WrappedIOException(ffe);
    } finally {
        is.close();
    }
}

From source file:org.geopublishing.geopublisher.AMLExporter.java

/**
 * Creates an aml:fonts tag that lists the names of all the fonts files in
 * ad/font folder. The list of fonts is determined while
 *//*from   ww  w  .j a va 2  s .c  o  m*/
protected Node exportFonts(Document document) {
    final Element fontsElement = document.createElementNS(AMLUtil.AMLURI, AMLUtil.TAG_FONTS);

    File fontsDir = getAce().getFontsDir();

    Collection<File> listFiles = FileUtils.listFiles(fontsDir, GpUtil.FontsFilesFilter,
            FilterUtil.BlacklistedFoldersFilter);
    for (File f : listFiles) {

        // Test whether the font is readable
        String relPath = f.getAbsolutePath().substring(fontsDir.getAbsolutePath().length() + 1);
        try {
            Font.createFont(Font.TRUETYPE_FONT, f);
            final Element fontElement = document.createElementNS(AMLUtil.AMLURI, AMLUtil.TAG_FONT);
            fontElement.setAttribute(AMLUtil.ATT_FONT_FILENAME, relPath);
            fontsElement.appendChild(fontElement);
        } catch (Exception e) {
            LOGGER.info("Not exporting a reference to broken font " + relPath + " in " + fontsDir, e);
        }

    }

    return fontsElement;
}

From source file:literarytermsquestionbank.RomeoAndJuliet.java

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    // Set custom  icon
    this.setIconImage(
            Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/Images/book-icon_rj.png")));

    // Set custom fonts
    try {//  ww w. j  a va  2s . c o  m
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        // Load Old English from resources
        Font englishFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/OLDENGL.TTF"));
        ge.registerFont(englishFontFace);
        actLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 30f));
        sceneLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 16f));
        lineNumberLabel.setFont(englishFontFace.deriveFont(Font.PLAIN, 16f));

        // Load Matura Script font from resources
        Font maturaFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/MATURASC.TTF"));
        ge.registerFont(maturaFontFace);
        tabbedPane.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f));
        questionLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f));
        checkButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));
        stuckLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));
        rescueButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));
        answerLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));
        youAreViewingLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f));
        quoteIndexTextField.setFont(maturaFontFace.deriveFont(Font.PLAIN, 24f));
        totalNumberLabel.setFont(maturaFontFace.deriveFont(Font.PLAIN, 36f));
        goButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 24f));
        randomButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 18f));
        previousButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));
        nextButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));
        backButton.setFont(maturaFontFace.deriveFont(Font.PLAIN, 14f));

        // Load Corsova font from resources
        Font corsovaFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/MTCORSVA.TTF"));
        ge.registerFont(corsovaFontFace);
        clueLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f));
        passageLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f));
        examplesLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 18f));
        commentsLabel.setFont(corsovaFontFace.deriveFont(Font.PLAIN, 14f));

        // Load Imprint font from resources
        Font imprintFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/IMPRISHA.TTF"));
        ge.registerFont(imprintFontFace);
        quoteTopLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f));
        quoteBottomLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f));
    } catch (FontFormatException ex) {
        Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONParser parser = new JSONParser();

    try {
        // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package.
        Object quoteObj = parser
                .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json")));

        // This casts the object to a JSONObject for future manipulation
        JSONObject jsonObject = (JSONObject) quoteObj;

        // This array holds all the quotes
        JSONArray quotesArray = (JSONArray) jsonObject.get("Romeo and Juliet");
        Iterator<JSONObject> iterator = quotesArray.iterator();

        // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList
        while (iterator.hasNext()) {
            Collections.addAll(quotesList, iterator.next());
            totalNumberOfQuotes++;
        }

        // Init randomizer
        Random rand = new Random();

        // Generate a random integer between 1 and size of the ArrayList
        quoteIndex = rand.nextInt(quotesList.size()) + 1;

        generateQuote(quoteIndex); // This calls a method to generate a quote and display it
    } catch (Exception e) { // This means something went very wrong when starting the program
        System.out.println("Uh oh, something bad happened. Possible database corruption.");
        JOptionPane.showMessageDialog(null,
                "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }
}

From source file:Gui.HistoryAdminGUINew.java

public void showStatHistory() {
    // method statGreensociety......  History 
    int tempRepair = history.statGreensocietyRepair();
    int tempBorrow = history.statGreensocietyBorrow();
    int tempReturn = history.statGreensocietyReturn();
    DefaultCategoryDataset barchartData = new DefaultCategoryDataset();

    barchartData.setValue(tempRepair, "0", "RepairHistory");
    barchartData.setValue(tempBorrow, "1", "BorrowHistory");
    barchartData.setValue(tempReturn, "2", "ReturnHistory");

    JFreeChart chart = ChartFactory.createBarChart("History Statictics", "History", "Times", barchartData,
            PlotOrientation.HORIZONTAL, false, true, false);

    //        chart.getTitle().setPaint(Color.WHITE);   //??

    //--------SET FONT--------------
    try {/*  w w  w. j a  v a  2 s  . c  o  m*/
        File f = new File("leelawad.ttf");
        Font customFont = Font.createFont(Font.TRUETYPE_FONT, f);
        customFont = customFont.deriveFont(16f);
        chart.getTitle().setFont(customFont);
        System.out.println(customFont.getFontName());
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (FontFormatException | IOException e) {
        e.printStackTrace();
    }
    //------------------------------
    chart.setBackgroundPaint(new Color(19, 175, 248)); //setBackground ?

    CategoryPlot barchartPlot = chart.getCategoryPlot();

    barchartPlot.setRangeGridlinePaint(Color.BLACK); //set ??

    //Customize renderer
    BarRenderer renderer = (BarRenderer) barchartPlot.getRenderer();
    java.awt.Paint paint1 = new Color(255, 0, 0);
    java.awt.Paint paint2 = new Color(0, 0, 255);
    java.awt.Paint paint3 = new Color(255, 255, 0);

    renderer.setSeriesPaint(0, paint1); //Color for RepairGraph
    renderer.setSeriesPaint(1, paint2); //Color for BorrowGraph
    renderer.setSeriesPaint(2, paint3); //Color for ReturnGraph

    ChartPanel barPanel = new ChartPanel(chart);
    jPanelShowGraph.removeAll();
    jPanelShowGraph.add(barPanel, BorderLayout.CENTER);
    jPanelShowGraph.validate();
}

From source file:literarytermsquestionbank.ShortStories.java

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    // Set window icon
    this.setIconImage(
            Toolkit.getDefaultToolkit().getImage(getClass().getResource("/Resources/Images/book-icon_ss.png")));

    // Set custom fonts
    try {// w  w  w  .  ja  v  a 2s. c  o  m
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        // Load Great Vibes from resources
        Font bradleyFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/BRADHITC.TTF"));
        ge.registerFont(bradleyFontFace);
        questionLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f));
        checkButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 36f));
        stuckLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 24f));
        rescueButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        answerLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        youAreViewingLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        quoteIndexTextField.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        totalNumberLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 36f));
        goButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        randomButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        previousButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        nextButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        backButton.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 24f));
        clueTitleLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 24f));
        clueLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f));
        passageLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f));
        examplesLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f));
        commentsLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 30f));
        storyLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 20f));
        tabbedPane.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));
        menuTitleLabel.setFont(bradleyFontFace.deriveFont(Font.PLAIN, 18f));

        // Load and set Imprint font face
        Font imprintFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/IMPRISHA.TTF"));
        ge.registerFont(imprintFontFace);
        quoteTopLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f));
        quoteBottomLabel.setFont(imprintFontFace.deriveFont(Font.PLAIN, 48f));
    } catch (FontFormatException ex) {
        Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONParser parser = new JSONParser();
    try {
        // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package.
        Object quoteObj = parser
                .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json")));

        // This casts the object to a JSONObject for future manipulation
        JSONObject jsonObject = (JSONObject) quoteObj;

        // This array holds all the quotes
        JSONArray quotesArray = (JSONArray) jsonObject.get("Short Stories");
        Iterator<JSONObject> iterator = quotesArray.iterator();

        // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList
        while (iterator.hasNext()) {
            Collections.addAll(quotesList, iterator.next());
            totalNumberOfQuotes++;
        }

        // Init randomizer
        Random rand = new Random();

        // Generate a random integer between 1 and size of the ArrayList
        quoteIndex = rand.nextInt(quotesList.size()) + 1;

        generateQuote(quoteIndex); // This calls a method to generate a quote and display it
    } catch (Exception e) { // This means something went very wrong when starting the program
        System.out.println("Uh oh, something bad happened. Possible database corruption.");
        JOptionPane.showMessageDialog(null,
                "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }
}

From source file:literarytermsquestionbank.AChristmasCarol.java

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
    // Set window icon
    this.setIconImage(Toolkit.getDefaultToolkit()
            .getImage(getClass().getResource("/Resources/Images/book-icon_acc.png")));

    // Set custom fonts
    try {//from  w  w w  .  jav a  2  s.co m
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();

        // Load Gill Sans from resources
        Font gillSansFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/GILLSANS.TTF"));
        ge.registerFont(gillSansFontFace);

        tabbedPane.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f));
        questionLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f));
        checkButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f));
        youAreViewingLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f));
        quoteIndexTextField.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 24f));
        totalNumberLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 36f));
        goButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 20f));
        randomButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 20f));
        backButton.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f));
        clueLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f));
        passageLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f));
        exampleLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f));
        commentsLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f));
        realAnswerLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 14f));
        realAnswerTitleLabel.setFont(gillSansFontFace.deriveFont(Font.PLAIN, 18f));

        // Load the FreeStyle Script font from resources
        Font freeStyleFontFace = Font.createFont(Font.TRUETYPE_FONT,
                getClass().getResourceAsStream("/Resources/Fonts/FREESCPT.TTF"));
        ge.registerFont(freeStyleFontFace);
        salutationLabel.setFont(freeStyleFontFace.deriveFont(Font.PLAIN, 30f));
        signatureLabel.setFont(freeStyleFontFace.deriveFont(Font.PLAIN, 30f));

    } catch (FontFormatException ex) {
        Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(RomeoAndJuliet.class.getName()).log(Level.SEVERE, null, ex);
    }

    JSONParser parser = new JSONParser();

    try {
        // This object is the result of parsing the JSON file at the relative filepath as defined above; the JSON file is in the Resources source package.
        Object quoteObj = parser
                .parse(new InputStreamReader(getClass().getResourceAsStream("/Resources/Files/db.json")));

        // This casts the object to a JSONObject for future manipulation
        JSONObject jsonObject = (JSONObject) quoteObj;

        // This array holds all the quotes
        JSONArray quotesArray = (JSONArray) jsonObject.get("A Christmas Carol");
        Iterator<JSONObject> iterator = quotesArray.iterator();

        // Using the iterator as declared above, add each JSONObject in the Romeo and Juliet array to the ArrayList
        while (iterator.hasNext()) {
            Collections.addAll(quotesList, iterator.next());
            totalNumberOfQuotes++;
        }

        // Init randomizer
        Random rand = new Random();

        // Generate a random integer between 1 and size of the ArrayList
        quoteIndex = rand.nextInt(quotesList.size()) + 1;

        generateQuote(quoteIndex); // This calls a method to generate a quote and display it
    } catch (Exception e) { // This means something went very wrong when starting the program
        System.out.println("Uh oh, something bad happened. Possible database corruption.");
        JOptionPane.showMessageDialog(null,
                "Something went wrong while starting the app! Please tell Aaron with code 129.", "Uh-oh!",
                JOptionPane.ERROR_MESSAGE);
        e.printStackTrace();
    }
}

From source file:view.AppearanceSettingsDialog.java

private void changeLabel() {
    String fontLocation = getFontCbBox();

    try {/* w w w  .ja  v  a 2s  .c om*/
        Font newFont = Font.createFont(Font.TRUETYPE_FONT, new File(getFontLocationByName(fontLocation)));
        Font font = null;

        if (cbBold.isSelected() && cbItalic.isSelected()) {
            font = newFont.deriveFont(Font.ITALIC + Font.BOLD, 36);
        } else if (cbBold.isSelected() && !cbItalic.isSelected()) {
            font = newFont.deriveFont(Font.BOLD, 36);
        } else if (!cbBold.isSelected() && cbItalic.isSelected()) {
            font = newFont.deriveFont(Font.ITALIC, 36);
        } else {
            font = newFont.deriveFont(Font.PLAIN, 36);
        }
        lblSampleText.setFont(font);
        return;
    } catch (FontFormatException ex) {
        Logger.getLogger(AppearanceSettingsDialog.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(AppearanceSettingsDialog.class.getName()).log(Level.SEVERE, null, ex);
    }

    if (cbBold.isSelected() && cbItalic.isSelected()) {
        lblSampleText.setFont(new Font(fontLocation, Font.BOLD + Font.ITALIC, 36));
    } else if (cbBold.isSelected() && !cbItalic.isSelected()) {
        lblSampleText.setFont(new Font(fontLocation, Font.BOLD, 36));
    } else if (!cbBold.isSelected() && cbItalic.isSelected()) {
        lblSampleText.setFont(new Font(fontLocation, Font.ITALIC, (Integer) 36));
    } else {
        lblSampleText.setFont(new Font(cbFontType.getSelectedItem().toString(), Font.PLAIN, (Integer) 36));
    }
}