List of usage examples for java.awt FontMetrics getMaxAscent
public int getMaxAscent()
From source file:Main.java
public static void main(String args[]) { JFrame f = new JFrame(); f.add(new JComponent() { public void paintComponent(Graphics g) { // Some parameters. String text = "Some Label"; int centerX = 150, centerY = 100; int ovalWidth = 200, ovalHeight = 100; // Draw oval g.setColor(Color.BLUE); g.fillOval(centerX - ovalWidth / 2, centerY - ovalHeight / 2, ovalWidth, ovalHeight); // Draw centered text FontMetrics fm = g.getFontMetrics(); double textWidth = fm.getStringBounds(text, g).getWidth(); g.setColor(Color.WHITE); g.drawString(text, (int) (centerX - textWidth / 2), (int) (centerY + fm.getMaxAscent() / 2)); }/*from w w w. j a va 2 s .c om*/ }); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(300, 300); f.setVisible(true); }
From source file:Main.java
/** * Get the string height in the context of Graphics. * //from w ww . j a v a2 s. com * @param g * The <code>Graphics</code>. * @return The height <code>int</code>. */ public static int getStringHeight(final Graphics g) { final FontMetrics fontMetrics = g.getFontMetrics(); return fontMetrics.getMaxAscent() + fontMetrics.getMaxDescent(); }
From source file:de.darkblue.bongloader2.utils.ToolBox.java
public static float getFontBaseline(Graphics2D context) { final FontMetrics fontMetrics = context.getFontMetrics(); return fontMetrics.getMaxAscent(); }
From source file:Main.java
public void paint(Graphics g) { int fontSize = 20; g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize)); FontMetrics fm = g.getFontMetrics(); String s = "www.java2s.com"; int stringWidth = fm.stringWidth(s); int w = 200;/* w w w .ja v a 2s. com*/ int h = 200; int x = (w - stringWidth) / 2; int baseline = fm.getMaxAscent() + (h - (fm.getAscent() + fm.getMaxDecent())) / 2; int ascent = fm.getMaxAscent(); int descent = fm.getMaxDecent(); int fontHeight = fm.getMaxAscent() + fm.getMaxDecent(); g.setColor(Color.white); g.fillRect(x, baseline - ascent, stringWidth, fontHeight); g.setColor(Color.gray); g.drawLine(x, baseline, x + stringWidth, baseline); g.setColor(Color.red); g.drawLine(x, baseline + descent, x + stringWidth, baseline + descent); g.setColor(Color.blue); g.drawLine(x, baseline - ascent, x + stringWidth, baseline - ascent); g.setColor(Color.black); g.drawString(s, x, baseline); }
From source file:MainClass.java
public void paint(Graphics g) { int fontSize = 20; g.setFont(new Font("TimesRoman", Font.PLAIN, fontSize)); FontMetrics fm = g.getFontMetrics(); String s = "www.java2s.com"; int stringWidth = fm.stringWidth(s); int w = 200;/*from w ww . ja va 2s .c om*/ int h = 200; int x = (w - stringWidth) / 2; int baseline = fm.getMaxAscent() + (h - (fm.getAscent() + fm.getMaxDecent())) / 2; int ascent = fm.getMaxAscent(); int descent = fm.getMaxDecent(); int fontHeight = fm.getMaxAscent() + fm.getMaxDecent(); g.setColor(Color.white); g.fillRect(x, baseline - ascent, stringWidth, fontHeight); g.setColor(Color.gray); g.drawLine(x, baseline, x + stringWidth, baseline); g.setColor(Color.red); g.drawLine(x, baseline + descent, x + stringWidth, baseline + descent); g.setColor(Color.blue); g.drawLine(x, baseline - ascent, x + stringWidth, baseline - ascent); g.setColor(Color.black); g.drawString(s, x, baseline); }
From source file:Main.java
public void paint(Graphics g) { int fontSize = 20; Font font = new Font("TimesRoman", Font.PLAIN, fontSize); g.setFont(font);/*from w w w . j a v a 2s. co m*/ FontMetrics fm = g.getFontMetrics(font); String s = "www.java2s.com"; int stringWidth = fm.stringWidth(s); int w = 200; int h = 200; int x = (w - stringWidth) / 2; int baseline = fm.getMaxAscent() + (h - (fm.getAscent() + fm.getMaxDecent())) / 2; int ascent = fm.getMaxAscent(); int descent = fm.getMaxDecent(); int fontHeight = fm.getMaxAscent() + fm.getMaxDecent(); g.setColor(Color.white); g.fillRect(x, baseline - ascent, stringWidth, fontHeight); g.setColor(Color.gray); g.drawLine(x, baseline, x + stringWidth, baseline); g.setColor(Color.red); g.drawLine(x, baseline + descent, x + stringWidth, baseline + descent); g.setColor(Color.blue); g.drawLine(x, baseline - ascent, x + stringWidth, baseline - ascent); g.setColor(Color.black); g.drawString(s, x, baseline); }
From source file:com.diversityarrays.kdxplore.trials.PlotCellRenderer.java
public void updateTableRowHeight(JTable table) { FontMetrics fm = getFontMetrics(getFont()); int lineHeight = fm.getMaxAscent() + fm.getMaxDescent(); int rowHeight = lineHeight * (3 + attributeNames.size() + 1 + traitInstancesByTraitId.size()); table.setRowHeight(rowHeight);/*from ww w . jav a2 s .com*/ }
From source file:com.diversityarrays.kdxplore.field.FieldViewDialog.java
public FieldViewDialog(Window owner, String title, SampleGroupChoice sgcSamples, Trial trial, SampleGroupChoice sgcNewMedia, KDSmartDatabase db) throws IOException { super(owner, title, ModalityType.MODELESS); advanceRetreatControls = Box.createHorizontalBox(); advanceRetreatControls.add(new JButton(retreatAction)); advanceRetreatControls.add(new JButton(advanceAction)); autoAdvanceControls = Box.createHorizontalBox(); autoAdvanceControls.add(new JButton(autoAdvanceAction)); autoAdvanceOption.addActionListener(new ActionListener() { @Override//from ww w. j av a 2 s .co m public void actionPerformed(ActionEvent e) { updateMovementControls(); } }); this.database = db; this.sampleGroupChoiceForSamples = sgcSamples; this.sampleGroupChoiceForNewMedia = sgcNewMedia; NumberSpinner fontSpinner = new NumberSpinner(new SpinnerNumberModel(), "0.00"); this.fieldViewPanel = FieldViewPanel.create(database, trial, SeparatorVisibilityOption.VISIBLE, null, Box.createHorizontalGlue(), new JButton(showInfoAction), Box.createHorizontalGlue(), new JLabel("Font Size:"), fontSpinner, Box.createHorizontalGlue(), advanceRetreatControls, autoAdvanceOption, autoAdvanceControls); initialiseAction(advanceAction, "ic_object_advance_black.png", "Auto-Advance"); this.xyProvider = fieldViewPanel.getXYprovider(); this.traitMap = fieldViewPanel.getTraitMap(); fieldLayoutTable = fieldViewPanel.getFieldLayoutTable(); JScrollPane scrollPane = fieldViewPanel.getFieldTableScrollPane(); scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); fieldLayoutTable.setTransferHandler(flth); fieldLayoutTable.setDropMode(DropMode.ON); fieldLayoutTable.addMouseListener(new MouseAdapter() { JPopupMenu popupMenu; @Override public void mouseClicked(MouseEvent e) { if (!SwingUtilities.isRightMouseButton(e) || 1 != e.getClickCount()) { return; } Point pt = e.getPoint(); int row = fieldLayoutTable.rowAtPoint(pt); if (row >= 0) { int col = fieldLayoutTable.columnAtPoint(pt); if (col >= 0) { Plot plot = fieldViewPanel.getPlotAt(col, row); if (plot != null) { if (popupMenu == null) { popupMenu = new JPopupMenu("View Attachments"); } popupMenu.removeAll(); Set<File> set = plot.getMediaFiles(); if (Check.isEmpty(set)) { popupMenu.add(new JMenuItem("No Attachments available")); } else { for (File file : set) { Action a = new AbstractAction(file.getName()) { @Override public void actionPerformed(ActionEvent e) { try { Desktop.getDesktop().browse(file.toURI()); } catch (IOException e1) { MsgBox.warn(FieldViewDialog.this, e1, file.getName()); } } }; popupMenu.add(new JMenuItem(a)); } } popupMenu.show(fieldLayoutTable, pt.x, pt.y); } } } } }); Font font = fieldLayoutTable.getFont(); float fontSize = font.getSize2D(); fontSizeModel = new SpinnerNumberModel(fontSize, fontSize, 50.0, 1.0); fontSpinner.setModel(fontSizeModel); fontSizeModel.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { float fsize = fontSizeModel.getNumber().floatValue(); System.out.println("Using fontSize=" + fsize); Font font = fieldLayoutTable.getFont().deriveFont(fsize); fieldLayoutTable.setFont(font); FontMetrics fm = fieldLayoutTable.getFontMetrics(font); int lineHeight = fm.getMaxAscent() + fm.getMaxDescent(); fieldLayoutTable.setRowHeight(4 * lineHeight); // GuiUtil.initialiseTableColumnWidths(fieldLayoutTable, false); fieldLayoutTable.repaint(); } }); fieldLayoutTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); fieldLayoutTable.setResizable(true, true); fieldLayoutTable.getTableColumnResizer().setResizeAllColumns(true); advanceAction.setEnabled(false); fieldLayoutTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { handlePlotSelection(); } } }); TableColumnModel columnModel = fieldLayoutTable.getColumnModel(); columnModel.addColumnModelListener(new TableColumnModelListener() { @Override public void columnSelectionChanged(ListSelectionEvent e) { if (!e.getValueIsAdjusting()) { handlePlotSelection(); } } @Override public void columnRemoved(TableColumnModelEvent e) { } @Override public void columnMoved(TableColumnModelEvent e) { } @Override public void columnMarginChanged(ChangeEvent e) { } @Override public void columnAdded(TableColumnModelEvent e) { } }); PropertyChangeListener listener = new PropertyChangeListener() { // Use a timer and redisplay other columns when delay is GT 100 ms Timer timer = new Timer(true); TimerTask timerTask; long lastActive; boolean busy = false; private int eventColumnWidth; private TableColumn eventColumn; @Override public void propertyChange(PropertyChangeEvent evt) { if (busy) { return; } if (evt.getSource() instanceof TableColumn && "width".equals(evt.getPropertyName())) { eventColumn = (TableColumn) evt.getSource(); eventColumnWidth = eventColumn.getWidth(); lastActive = System.currentTimeMillis(); if (timerTask == null) { timerTask = new TimerTask() { @Override public void run() { if (System.currentTimeMillis() - lastActive > 200) { timerTask.cancel(); timerTask = null; busy = true; try { for (Enumeration<TableColumn> en = columnModel.getColumns(); en .hasMoreElements();) { TableColumn tc = en.nextElement(); if (tc != eventColumn) { tc.setWidth(eventColumnWidth); } } } finally { busy = false; } } } }; timer.scheduleAtFixedRate(timerTask, 100, 150); } } } }; for (Enumeration<TableColumn> en = columnModel.getColumns(); en.hasMoreElements();) { TableColumn tc = en.nextElement(); tc.addPropertyChangeListener(listener); } Map<Integer, Plot> plotById = new HashMap<>(); for (Plot plot : fieldViewPanel.getFieldLayout()) { plotById.put(plot.getPlotId(), plot); } TrialItemVisitor<Sample> sampleVisitor = new TrialItemVisitor<Sample>() { @Override public void setExpectedItemCount(int count) { } @Override public boolean consumeItem(Sample sample) throws IOException { Plot plot = plotById.get(sample.getPlotId()); if (plot == null) { throw new IOException("Missing plot for plotId=" + sample.getPlotId() + " sampleIdent=" + Util.createUniqueSampleKey(sample)); } plot.addSample(sample); SampleCounts counts = countsByTraitId.get(sample.getTraitId()); if (counts == null) { counts = new SampleCounts(); countsByTraitId.put(sample.getTraitId(), counts); } if (sample.hasBeenScored()) { ++counts.scored; } else { ++counts.unscored; } return true; } }; database.visitSamplesForTrial(sampleGroupChoiceForSamples, trial.getTrialId(), SampleOrder.ALL_BY_PLOT_ID_THEN_TRAIT_ID_THEN_INSTANCE_NUMBER_ORDER_THEN_SPECIMEN_NUMBER, sampleVisitor); setDefaultCloseOperation(DISPOSE_ON_CLOSE); this.trial = trial; KDClientUtils.initAction(ImageId.SETTINGS_24, showInfoAction, "Trial Summary"); Action clear = new AbstractAction("Clear") { @Override public void actionPerformed(ActionEvent e) { infoTextArea.setText(""); } }; JPanel bottom = new JPanel(new BorderLayout()); bottom.add(GuiUtil.createLabelSeparator("Plot Details", new JButton(clear)), BorderLayout.NORTH); bottom.add(new JScrollPane(infoTextArea), BorderLayout.CENTER); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, fieldViewPanel, new JScrollPane(infoTextArea)); splitPane.setResizeWeight(0.0); splitPane.setOneTouchExpandable(true); setContentPane(splitPane); updateMovementControls(); pack(); }
From source file:net.pms.newgui.NavigationShareTab.java
private PanelBuilder initSharedFoldersGuiComponents(CellConstraints cc) { // Apply the orientation for the locale ComponentOrientation orientation = ComponentOrientation.getOrientation(PMS.getLocale()); String colSpec = FormLayoutUtil.getColSpec(SHARED_FOLDER_COL_SPEC, orientation); FormLayout layoutFolders = new FormLayout(colSpec, SHARED_FOLDER_ROW_SPEC); PanelBuilder builderFolder = new PanelBuilder(layoutFolders); builderFolder.opaque(true);/*from w ww . j a va2 s . c o m*/ JComponent cmp = builderFolder.addSeparator(Messages.getString("FoldTab.7"), FormLayoutUtil.flip(cc.xyw(1, 1, 7), colSpec, orientation)); cmp = (JComponent) cmp.getComponent(0); cmp.setFont(cmp.getFont().deriveFont(Font.BOLD)); folderTableModel = new SharedFoldersTableModel(); sharedFolders = new JTable(folderTableModel); JPopupMenu popupMenu = new JPopupMenu(); JMenuItem menuItemMarkPlayed = new JMenuItem(Messages.getString("FoldTab.75")); JMenuItem menuItemMarkUnplayed = new JMenuItem(Messages.getString("FoldTab.76")); menuItemMarkPlayed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String path = (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0); TableFilesStatus.setDirectoryFullyPlayed(path, true); } }); menuItemMarkUnplayed.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String path = (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0); TableFilesStatus.setDirectoryFullyPlayed(path, false); } }); popupMenu.add(menuItemMarkPlayed); popupMenu.add(menuItemMarkUnplayed); sharedFolders.setComponentPopupMenu(popupMenu); /* An attempt to set the correct row height adjusted for font scaling. * It sets all rows based on the font size of cell (0, 0). The + 4 is * to allow 2 pixels above and below the text. */ DefaultTableCellRenderer cellRenderer = (DefaultTableCellRenderer) sharedFolders.getCellRenderer(0, 0); FontMetrics metrics = cellRenderer.getFontMetrics(cellRenderer.getFont()); sharedFolders.setRowHeight(metrics.getLeading() + metrics.getMaxAscent() + metrics.getMaxDescent() + 4); sharedFolders.setIntercellSpacing(new Dimension(8, 2)); final JPanel tmpsharedPanel = sharedPanel; addButton.setToolTipText(Messages.getString("FoldTab.9")); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFileChooser chooser; try { chooser = new JFileChooser(); } catch (Exception ee) { chooser = new JFileChooser(new RestrictedFileSystemView()); } chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = chooser.showOpenDialog((Component) e.getSource()); if (returnVal == JFileChooser.APPROVE_OPTION) { int firstSelectedRow = sharedFolders.getSelectedRow(); if (firstSelectedRow >= 0) { ((SharedFoldersTableModel) sharedFolders.getModel()).insertRow(firstSelectedRow, new Object[] { chooser.getSelectedFile().getAbsolutePath(), true }); } else { ((SharedFoldersTableModel) sharedFolders.getModel()) .addRow(new Object[] { chooser.getSelectedFile().getAbsolutePath(), true }); } } } }); builderFolder.add(addButton, FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation)); removeButton.setToolTipText(Messages.getString("FoldTab.36")); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int[] rows = sharedFolders.getSelectedRows(); if (rows.length > 0) { if (rows.length > 1) { if (JOptionPane.showConfirmDialog(tmpsharedPanel, String.format(Messages.getString("SharedFolders.ConfirmRemove"), rows.length), Messages.getString("Dialog.Confirm"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE) != JOptionPane.YES_OPTION) { return; } } for (int i = rows.length - 1; i >= 0; i--) { PMS.get().getDatabase().removeMediaEntriesInFolder( (String) sharedFolders.getValueAt(sharedFolders.getSelectedRow(), 0)); ((SharedFoldersTableModel) sharedFolders.getModel()).removeRow(rows[i]); } } } }); builderFolder.add(removeButton, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation)); arrowDownButton.setToolTipText(Messages.getString("SharedFolders.ArrowDown")); arrowDownButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (int i = 0; i < sharedFolders.getRowCount() - 1; i++) { if (sharedFolders.isRowSelected(i)) { Object value1 = sharedFolders.getValueAt(i, 0); boolean value2 = (boolean) sharedFolders.getValueAt(i, 1); sharedFolders.setValueAt(sharedFolders.getValueAt(i + 1, 0), i, 0); sharedFolders.setValueAt(value1, i + 1, 0); sharedFolders.setValueAt(sharedFolders.getValueAt(i + 1, 1), i, 1); sharedFolders.setValueAt(value2, i + 1, 1); sharedFolders.changeSelection(i + 1, 1, false, false); break; } } } }); builderFolder.add(arrowDownButton, FormLayoutUtil.flip(cc.xy(4, 3), colSpec, orientation)); arrowUpButton.setToolTipText(Messages.getString("SharedFolders.ArrowUp")); arrowUpButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { for (int i = 1; i < sharedFolders.getRowCount(); i++) { if (sharedFolders.isRowSelected(i)) { Object value1 = sharedFolders.getValueAt(i, 0); boolean value2 = (boolean) sharedFolders.getValueAt(i, 1); sharedFolders.setValueAt(sharedFolders.getValueAt(i - 1, 0), i, 0); sharedFolders.setValueAt(value1, i - 1, 0); sharedFolders.setValueAt(sharedFolders.getValueAt(i - 1, 1), i, 1); sharedFolders.setValueAt(value2, i - 1, 1); sharedFolders.changeSelection(i - 1, 1, false, false); break; } } } }); builderFolder.add(arrowUpButton, FormLayoutUtil.flip(cc.xy(5, 3), colSpec, orientation)); scanButton.setToolTipText(Messages.getString("FoldTab.2")); scanBusyIcon.start(); scanBusyDisabledIcon.start(); scanButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (configuration.getUseCache()) { DLNAMediaDatabase database = PMS.get().getDatabase(); if (database != null) { if (database.isScanLibraryRunning()) { int option = JOptionPane.showConfirmDialog(looksFrame, Messages.getString("FoldTab.10"), Messages.getString("Dialog.Question"), JOptionPane.YES_NO_OPTION); if (option == JOptionPane.YES_OPTION) { database.stopScanLibrary(); looksFrame.setStatusLine(Messages.getString("FoldTab.41")); scanButton.setEnabled(false); scanButton.setToolTipText(Messages.getString("FoldTab.41")); } } else { database.scanLibrary(); scanButton.setIcon(scanBusyIcon); scanButton.setRolloverIcon(scanBusyRolloverIcon); scanButton.setPressedIcon(scanBusyPressedIcon); scanButton.setDisabledIcon(scanBusyDisabledIcon); scanButton.setToolTipText(Messages.getString("FoldTab.40")); } } } } }); /* * Hide the scan button in basic mode since it's better to let it be done in * realtime. */ if (!configuration.isHideAdvancedOptions()) { builderFolder.add(scanButton, FormLayoutUtil.flip(cc.xy(6, 3), colSpec, orientation)); } scanButton.setEnabled(configuration.getUseCache()); isScanSharedFoldersOnStartup = new JCheckBox(Messages.getString("NetworkTab.StartupScan"), configuration.isScanSharedFoldersOnStartup()); isScanSharedFoldersOnStartup.setToolTipText(Messages.getString("NetworkTab.StartupScanTooltip")); isScanSharedFoldersOnStartup.setContentAreaFilled(false); isScanSharedFoldersOnStartup.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { configuration.setScanSharedFoldersOnStartup((e.getStateChange() == ItemEvent.SELECTED)); } }); builderFolder.add(isScanSharedFoldersOnStartup, FormLayoutUtil.flip(cc.xy(7, 3), colSpec, orientation)); updateSharedFolders(); JScrollPane pane = new JScrollPane(sharedFolders); Dimension d = sharedFolders.getPreferredSize(); pane.setPreferredSize(new Dimension(d.width, sharedFolders.getRowHeight() * 2)); builderFolder.add(pane, FormLayoutUtil.flip(cc.xyw(1, 5, 7, CellConstraints.DEFAULT, CellConstraints.FILL), colSpec, orientation)); return builderFolder; }