Example usage for java.awt Component getFont

List of usage examples for java.awt Component getFont

Introduction

In this page you can find the example usage for java.awt Component getFont.

Prototype

@Transient
public Font getFont() 

Source Link

Document

Gets the font of this component.

Usage

From source file:Main.java

/**
 * Returns whether component font is bold or not.
 *
 * @param component/*from w  w  w.  j  a  va2s .  co  m*/
 *            component to process
 * @return true if component font is bold, false otherwise
 */
public static boolean isBoldFont(final Component component) {
    return component != null && component.getFont() != null && component.getFont().isBold();
}

From source file:Main.java

/**
 * Returns whether component font is plain or not.
 *
 * @param component/*  w  w w. jav  a2s  .  c o  m*/
 *            component to process
 * @return true if component font is plain, false otherwise
 */
public static boolean isPlainFont(final Component component) {
    return !(component != null && component.getFont() != null) || component.getFont().isPlain();
}

From source file:Main.java

/**
 * Returns component font name./*from ww  w  .j  av  a2s. com*/
 *
 * @param component
 *            component to process
 * @return component font name
 */
public static String getFontName(final Component component) {
    if (component != null && component.getFont() != null) {
        return component.getFont().getFontName();
    }
    return null;
}

From source file:Main.java

/**
 * Returns font size of the specified component.
 *
 * @param component/*from  w  ww  .j  a v a  2  s.co  m*/
 *            component to process
 * @return font size of the specified component
 */
public static int getFontSize(final Component component) {
    if (component != null && component.getFont() != null) {
        return component.getFont().getSize();
    }
    return -1;
}

From source file:Main.java

/**
 * Calculates the average character width for the given {@link Component}.
 * This can be useful as a scaling factor when designing for font scaling.
 *
 * @param component the {@link Component} for which to calculate the
 *        average character width.// w w w .j ava  2s  .  c  om
 * @return The average width in pixels
 */
public static float getComponentAverageCharacterWidth(Component component) {
    FontMetrics metrics = component.getFontMetrics(component.getFont());
    int i = 0;
    float avgWidth = 0;
    for (int width : metrics.getWidths()) {
        avgWidth += width;
        i++;
    }
    return avgWidth / i;
}

From source file:Main.java

/**
 * Returns the height of the given component.
 *
 * @param c the component where the text is contained
 * @return the height of the text/*from   www . j av a  2  s  . c o  m*/
 */
public static int getStringHeight(Component c) {
    // get metrics from the graphics
    FontMetrics metrics = c.getFontMetrics(c.getFont());
    // get the height of a line of text in this font and render context
    int hgt = metrics.getHeight();
    // calculate the height of a box to hold the text with some padding.
    return hgt + 2;
}

From source file:Main.java

/**
 * Returns the size of the given text computed towards to the given
 * component.//from   w ww . ja  va 2  s. c o m
 *
 * @param c the component where the text is contained
 * @param text the text to measure
 * @return the dimensions of the text
 */
public static Dimension getStringSize(Component c, String text) {
    // get metrics from the graphics
    FontMetrics metrics = c.getFontMetrics(c.getFont());
    // get the height of a line of text in this font and render context
    int hgt = metrics.getHeight();
    // get the advance of my text in this font and render context
    int adv = metrics.stringWidth(text);
    // calculate the size of a box to hold the text with some padding.
    return new Dimension(adv + 2, hgt + 2);
}

From source file:de.codesourcery.eve.skills.ui.components.AbstractComponent.java

protected static void setMonospacedFont(Component comp) {

    final int size;
    if (comp.getFont() != null) {
        size = comp.getFont().getSize();
    } else {/*from   ww w  .j av  a  2  s  .  com*/
        size = 12;
    }
    Font font = new Font("Monospaced", Font.PLAIN, size);

    comp.setFont(font);
}

From source file:com.simiacryptus.util.Util.java

/**
 * To image buffered image./*  www  .  j a v  a  2s . c  o  m*/
 *
 * @param component the component
 * @return the buffered image
 */
public static BufferedImage toImage(@javax.annotation.Nonnull final Component component) {
    try {
        com.simiacryptus.util.Util.layout(component);
        @javax.annotation.Nonnull
        final BufferedImage img = new BufferedImage(component.getWidth(), component.getHeight(),
                BufferedImage.TYPE_INT_ARGB_PRE);
        final Graphics2D g = img.createGraphics();
        g.setColor(component.getForeground());
        g.setFont(component.getFont());
        component.print(g);
        return img;
    } catch (@javax.annotation.Nonnull final Exception e) {
        return null;
    }
}

From source file:edu.ku.brc.ui.tmanfe.SpreadSheet.java

/**
  * /* w  ww . j a  va  2  s . c  om*/
  */
protected void buildSpreadsheet() {

    this.setShowGrid(true);

    int numRows = model.getRowCount();

    scrollPane = new JScrollPane(this, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    final SpreadSheet ss = this;
    JButton cornerBtn = UIHelper.createIconBtn("Blank", IconManager.IconSize.Std16, "SelectAll",
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    ss.selectAll();
                }
            });
    cornerBtn.setEnabled(true);
    scrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, cornerBtn);

    // Allows row and collumn selections to exit at the same time
    setCellSelectionEnabled(true);

    setRowSelectionAllowed(true);
    setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    addMouseListener(new MouseAdapter() {
        /* (non-Javadoc)
         * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
         */
        @SuppressWarnings("synthetic-access")
        @Override
        public void mouseReleased(MouseEvent e) {
            // XXX For Java 5 Bug
            prevRowSelInx = getSelectedRow();
            prevColSelInx = getSelectedColumn();

            if (e.getClickCount() == 2) {
                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                ss.editCellAt(rowIndexStart, colIndexStart);
                if (ss.getEditorComponent() != null && ss.getEditorComponent() instanceof JTextComponent) {
                    ss.getEditorComponent().requestFocus();

                    final JTextComponent txtComp = (JTextComponent) ss.getEditorComponent();
                    String txt = txtComp.getText();
                    FontMetrics fm = txtComp.getFontMetrics(txtComp.getFont());
                    int x = e.getPoint().x - ss.getEditorComponent().getBounds().x - 1;
                    int prevWidth = 0;
                    for (int i = 0; i < txt.length(); i++) {

                        int width = fm.stringWidth(txt.substring(0, i));
                        int basePlusHalf = prevWidth + (int) (((width - prevWidth) / 2) + 0.5);
                        //System.out.println(prevWidth + " X[" + x + "] " + width+" ["+txt.substring(0, i)+"] " + i + " " + basePlusHalf);
                        //System.out.println(" X[" + x + "] " + prevWidth + " - "+ basePlusHalf+" - " + width+" ["+txt.substring(0, i)+"] " + i);
                        if (x < width) {
                            // Clearing the selection is needed for Window for some reason
                            final int inx = i + (x <= basePlusHalf ? -1 : 0);
                            SwingUtilities.invokeLater(new Runnable() {
                                @SuppressWarnings("synthetic-access")
                                public void run() {
                                    txtComp.setSelectionStart(0);
                                    txtComp.setSelectionEnd(0);
                                    txtComp.setCaretPosition(inx > 0 ? inx : 0);
                                }
                            });
                            break;
                        }
                        prevWidth = width;
                    }
                }
            }
        }
    });

    // Create a row-header to display row numbers.
    // This row-header is made of labels whose Borders,
    // Foregrounds, Backgrounds, and Fonts must be
    // the one used for the table column headers.
    // Also ensure that the row-header labels and the table
    // rows have the same height.

    //i have no idea WHY this has to be called.  i rearranged
    //the table and find replace panel, 
    // i started getting an array index out of
    //bounds on the column header ON MAC ONLY.  
    //tried firing this off, first and it fixed the problem.//meg
    this.getModel().fireTableStructureChanged();

    /*
     * Create the Row Header Panel
     */
    rowHeaderPanel = new JPanel((LayoutManager) null);

    if (getColumnModel().getColumnCount() > 0) {
        TableColumn column = getColumnModel().getColumn(0);
        TableCellRenderer renderer = getTableHeader().getDefaultRenderer();
        if (renderer == null) {
            renderer = column.getHeaderRenderer();
        }

        Component cellRenderComp = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false,
                false, -1, 0);
        cellFont = cellRenderComp.getFont();

    } else {
        cellFont = (new JLabel()).getFont();
    }

    // Calculate Row Height
    cellBorder = (Border) UIManager.getDefaults().get("TableHeader.cellBorder");
    Insets insets = cellBorder.getBorderInsets(tableHeader);
    FontMetrics metrics = getFontMetrics(cellFont);

    rowHeight = insets.bottom + metrics.getHeight() + insets.top;
    rowLabelWidth = metrics.stringWidth("9999") + insets.right + insets.left;

    Dimension dim = new Dimension(rowLabelWidth, rowHeight * numRows);
    rowHeaderPanel.setPreferredSize(dim); // need to call this when no layout manager is used.

    rhCellMouseAdapter = new RHCellMouseAdapter(this);

    // Adding the row header labels
    for (int ii = 0; ii < numRows; ii++) {
        addRow(ii, ii + 1, false);
    }

    JViewport viewPort = new JViewport();
    dim.height = rowHeight * numRows;
    viewPort.setViewSize(dim);
    viewPort.setView(rowHeaderPanel);
    scrollPane.setRowHeader(viewPort);

    // Experimental from the web, but I think it does the trick.
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (!ss.isEditing() && !e.isActionKey() && !e.isControlDown() && !e.isMetaDown() && !e.isAltDown()
                    && e.getKeyCode() != KeyEvent.VK_SHIFT && e.getKeyCode() != KeyEvent.VK_TAB
                    && e.getKeyCode() != KeyEvent.VK_ENTER) {
                log.error("Grabbed the event as input");

                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                if (rowIndexStart == -1 || colIndexStart == -1)
                    return;

                ss.editCellAt(rowIndexStart, colIndexStart);
                Component c = ss.getEditorComponent();
                if (c instanceof JTextComponent)
                    ((JTextComponent) c).setText("");
            }
        }
    });

    resizeAndRepaint();

    // Taken from a JavaWorld Example (But it works)
    KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false);

    Action ssAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SpreadSheet.this.actionPerformed(e);
        }
    };

    getInputMap().put(cut, "Cut");
    getActionMap().put("Cut", ssAction);

    getInputMap().put(copy, "Copy");
    getActionMap().put("Copy", ssAction);

    getInputMap().put(paste, "Paste");
    getActionMap().put("Paste", ssAction);

    ((JMenuItem) UIRegistry.get(UIRegistry.COPY)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.CUT)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.PASTE)).addActionListener(this);

    setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
}