Search Results

Search found 18 results on 1 pages for 'fontmetrics'.

Page 1/1 | 1 

  • Java: Friendlier way to get an instance of FontMetrics

    - by Martijn Courteaux
    Hi people, Is there a friendlier way to get an instance of FontMetrics than FontMetrics fm = Graphics.getFontMetrics(Font); I hate this way because of the following example: If you want to create in a game a menu and you want all the menuitems in the center of the screen you need fontmetrics. But, mostly, menuitems are clickable. So I create an array of Rectangles and all the rectangles fits around the items, so when the mouse is pressed, I can simply use for (int i = 0; i < rects.length; i++) if (rects[i].contains(mouseX, mouseY)) { ... } But to create the rects I also need FontMetrics for their coordinates. So this mean that I have to construct all my rectangles in the paint-method of my menu. So I want a way to get the FontMetrics so I can construct the Rectangles in a method called by the constructor. Hope you understand. Thanks in advance.

    Read the article

  • Java - FontMetrics without Graphics

    - by subSeven
    Hello! How to get FontMetrics without use Graphics ? I want to get FontMetrics in constructor, now I do this way: BufferedImage bi = new BufferedImage(5, 5, BufferedImage.TYPE_INT_RGB); FontMetrics fm = bi.getGraphics().getFontMetrics(font); int width = fm.stringWidth(pattern); int height = fm.getHeight();

    Read the article

  • Obtaining FontMetrics before getting a Graphics instance

    - by Tom Castle
    Typically, I'd obtain a graphics instance something like this: BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g = img.createGraphics(); However, in the current project I'm working on, the width and height variables above are dependent upon the size of a number of text fragments that will later be drawn onto the graphics instance. But, to obtain the dimensions of the font being used I would usually use the FontMetrics that I get from the graphics object. FontMetrics metrics = g.getFontMetrics(); So, I have a nasty little dependency cycle. I cannot create the graphics object until I know the size of the text, and I cannot know the size of the text until I have a graphics object. One solution is just to create another BufferedImage/Graphics pair first in order to get the FontMetrics instance I need, but this seems unnecessary. So, is there a nicer way? Or is it the case that the width, height etc. properties for a Font are somehow dependent upon what (graphics, component...) the text is to be drawn on?

    Read the article

  • How can I clip strings in Java2D and add ... in the end?

    - by Jonas
    I'm trying to print Invoices in a Java Swing applications. I do that by extending Printable and implement the method public int print(Graphics g, PageFormat pf, int page). I would like to draw strings in columns, and when the string is to long I want to clip it and let it end with "...". How can I measure the string and clip it at the right position? Some of my code: Font headline = new Font("Times New Roman", Font.BOLD, 14); g2d.setFont(headline); FontMetrics metrics = g2d.getFontMetrics(headline); g2d.drawString(myString, 0, 20); I.e How can I limit myString to be max 120px? I could use metrics.stringWidth(myString), but I don't get the position where I have to clip the string. Expected results could be: A longer string that exc... A shorter string. Another long string, but OK

    Read the article

  • Which text margin does SWT Table use when drawing text?

    - by Zordid
    I got a relatively easy question - but I cannot find anything anywhere to answer it. I use a simple SWT table widget in my application that displays only text in the cells. I got an incremental search feature and want to highlight text snippets in all cells if they match. So when typing "a", all "a"s should be highlighted. To get this, I add an SWT.EraseItem listener to interfere with the background drawing. If the current cell's text contains the search string, I find the positions and calculate relative x-coordinates within the text using event.gc.stringExtent - easy. With that I just draw rectangles "behind" the occurrences. Now, there's a flaw in this. The table does not draw the text without a margin, so my x coordinate does not really match - it is slightly off by a few pixels! But how many?? Where do I retrieve the cell's text margins that table's own drawing will use? No clue. Cannot find anything. :-( Bonus question: the table's draw method also shortens text and adds "..." if it does not fit into the cell. Hmm. My occurrence finder takes the TableItem's text and thus also tries to mark occurrences that are actually not visible because they are consumed by the "...". How do I get the shortened text and not the "real" text within the EraseItem draw handler? Thanks!

    Read the article

  • Really slow obtaining font metrics.

    - by Artur
    So the problem I have is that I start my application by displaying a simple menu. To size and align the text correctly I need to obtain font metrics and I cannot find a way to do it quickly. I tested my program and it looks like whatever method I use to obtain font metrics the first call takes over 500 milliseconds!? Because of it the time it takes to start-up my application is much longer than necessary. I don't know if it is platform specific or not, but just in case, I'm using Mac OS 10.6.2 on MacBook Pro (hardware isn't an issue here). If you know a way of obtaining font metrics quicker please help. I tried these 3 methods for obtaining the font metrics and the first call is always very slow, no matter which method I choose. import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.font.FontRenderContext; import java.awt.font.LineMetrics; import javax.swing.JFrame; public class FontMetricsTest extends JFrame { public FontMetricsTest() { setVisible(true); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; Font font = new Font("Dialog", Font.BOLD, 10); long start = System.currentTimeMillis(); FontMetrics fontMetrics = g2.getFontMetrics(font); // LineMetrics fontMetrics1 = // font.getLineMetrics("X", new FontRenderContext(null, false, false)); // FontMetrics fontMetrics2 = g.getFontMetrics(); long end = System.currentTimeMillis(); System.out.println(end - start); g2.setFont(font); } public static void main(String[] args) { new FontMetricsTest(); } }

    Read the article

  • Java Font Display Problem

    - by Yan Cheng CHEOK
    I realize that, in my certain customer side, when I use the font provided by Graphics2D itself, and decrease the size by 1, it cannot display properly. private void drawInformationBox(Graphics2D g2, JXLayer<? extends V> layer) { if (MainFrame.getInstance().getJStockOptions().getYellowInformationBoxOption() == JStockOptions.YellowInformationBoxOption.Hide) { return; } final Font oldFont = g2.getFont(); final Font paramFont = new Font(oldFont.getFontName(), oldFont.getStyle(), oldFont.getSize()); final FontMetrics paramFontMetrics = g2.getFontMetrics(paramFont); final Font valueFont = new Font(oldFont.getFontName(), oldFont.getStyle() | Font.BOLD, oldFont.getSize() + 1); final FontMetrics valueFontMetrics = g2.getFontMetrics(valueFont); /* * This date font cannot be displayed properly. Why? */ final Font dateFont = new Font(oldFont.getFontName(), oldFont.getStyle(), oldFont.getSize() - 1); final FontMetrics dateFontMetrics = g2.getFontMetrics(dateFont); Rest of the font is OK. Here is the screen shoot (See the yellow box. There are 3 type of different font within the yellow box) :

    Read the article

  • WYSIWYG with Qt - font size woes

    - by Rob
    I am creating a custom Qt widget that mimics an A4 printed page and am having problems getting fonts to render at the correct size. My widget uses QPainter::setViewport and QPainter::setWindow to mimic the A4 page, using units of 10ths of a millimetre which enables me to draw easily. However, attempting to create a font at a specific point size doesn't seem to work and using QFont:setPixelSize isn't accurate. Here is some code: View::View(QWidget *parent) : QWidget(parent), printer(new QPrinter) { printer->setPaperSize(QPrinter::A4); printer->setFullPage(true); } void View::paintEvent(QPaintEvent*) { QPainter painter(this); painter.setWindow(0, 0, 2100, 2970); painter.setViewport(0, 0, printer->width(), printer->height()); // Draw a rect at x = 1cm, y = 1cm, 6cm wide and 1 inch high painter.drawRect(100, 100, 600, 254); // Create a 72pt (1 inch) high font QFont font("Arial"); font.setPixelSize(254); painter.setFont(font); // Draw in the same box // The font is too large painter.drawText(QRect(100, 100, 600, 254), tr("Wg\u0102")); // Ack - the actual font size reported by the metrics is 283 pixels! const QFontMetrics fontMetrics = painter.fontMetrics(); qDebug() << "Font height = " << fontMetrics.height(); } So I'm asking for a 254 high font (1 inch, 72 pts) and it's too big and sure enough when I query for the font height via QFontMetrics it is 283 high. Does anyone else know how to use font sizes in points when using custom mapping modes like this? It must be possible. Note that I cannot see how to convert between logical/device points either (i.e. the Win32 DPtoLP/LPtoDP equivalents.)

    Read the article

  • Qt4: QPrinter / QPainter only prints the first document

    - by hurikhan77
    The problem is that my application only prints the first document fine. The second document is empty, only the page number is printed, the rest of the page is empty. In Qt4, I'm initializing the printer in the main.cpp in the following way: mw->printer = new QPrinter(QPrinter::HighResolution); mw->printer->setPaperSize(QPrinter::A5); mw->printer->setNumCopies(2); mw->printer->setColorMode(QPrinter::GrayScale); QPrintDialog *dialog = new QPrintDialog(mw->printer, mw); dialog->setWindowTitle(QObject::tr("Printer Setup")); if (dialog->exec() == QDialog::Accepted) { mw->printer->setFullPage(TRUE); return a.exec (); } This works fine for printing the first document from the application: qDebug("Printing"); QPainter p; if (!p.begin(printer)) { qDebug("Printing aborted"); return; } Q3PaintDeviceMetrics metrics(p.device()); int dpiy = metrics.logicalDpiY(); int dpix = metrics.logicalDpiX(); int tmargin = (int) ((marginTop / 2.54) * dpiy); int bmargin = (int) ((marginBottom / 2.54) * dpiy); int lmargin = (int) ((marginLeft / 2.54) * dpix); int rmargin = (int) ((marginRight / 2.54) * dpix); QRect body(lmargin, tmargin, metrics.width() - (lmargin + rmargin), metrics.height() - (tmargin + bmargin)); QString document; /* ... app logic to write a richtext document */ Q3SimpleRichText richText(QString("<qt>%1</qt>").arg(document), QFont("Arial", fontSize)); richText.setWidth(&p, body.width()); QRect view(body); int page = 1; do { // draw text richText.draw(&p, body.left(), body.top(), view, colorGroup()); view.moveBy(0, body.height()); p.translate(0, -body.height()); // insert page number p.drawText(view.right() - p.fontMetrics().width(QString::number(page)), view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page)); // exit loop on last page if (view.top () >= richText.height ()) break; printer->newPage(); page++; } while (TRUE); if (!p.end()) qDebug("Print painter yielded failure"); But when this routine runs the second time, it does not print the document. It will just print an empty page but still with the page number on it. This worked fine before with Qt3.

    Read the article

  • Qt4: QPrinter / QPainter only print the first document

    - by hurikhan77
    In Qt4, I'm initializing the printer in the main.cpp in the following way: mw->printer = new QPrinter(QPrinter::HighResolution); mw->printer->setPaperSize(QPrinter::A5); mw->printer->setNumCopies(2); mw->printer->setColorMode(QPrinter::GrayScale); QPrintDialog *dialog = new QPrintDialog(mw->printer, mw); dialog->setWindowTitle(QObject::tr("Printer Setup")); if (dialog->exec() == QDialog::Accepted) { mw->printer->setFullPage(TRUE); return a.exec (); } This works fine for printing the first document from the application: qDebug("Printing"); QPainter p; if (!p.begin(printer)) { qDebug("Printing aborted"); return; } Q3PaintDeviceMetrics metrics(p.device()); int dpiy = metrics.logicalDpiY(); int dpix = metrics.logicalDpiX(); int tmargin = (int) ((marginTop / 2.54) * dpiy); int bmargin = (int) ((marginBottom / 2.54) * dpiy); int lmargin = (int) ((marginLeft / 2.54) * dpix); int rmargin = (int) ((marginRight / 2.54) * dpix); QRect body(lmargin, tmargin, metrics.width() - (lmargin + rmargin), metrics.height() - (tmargin + bmargin)); QString document; /* ... app logic to write a richtext document */ Q3SimpleRichText richText(QString("<qt>%1</qt>").arg(document), QFont("Arial", fontSize)); richText.setWidth(&p, body.width()); QRect view(body); int page = 1; do { // draw text richText.draw(&p, body.left(), body.top(), view, colorGroup()); view.moveBy(0, body.height()); p.translate(0, -body.height()); // insert page number p.drawText(view.right() - p.fontMetrics().width(QString::number(page)), view.bottom() + p.fontMetrics().ascent() + 5, QString::number(page)); // exit loop on last page if (view.top () >= richText.height ()) break; printer->newPage(); page++; } while (TRUE); if (!p.end()) qDebug("Print painter yielded failure"); But when this routine runs the second time, it does not print the document. It will just print an empty page but still with the page number on it. This worked fine before with Qt3.

    Read the article

  • How do you draw a string centered vertically in Java?

    - by Paul Alexander
    I know it's a simple concept but I'm struggling with the font metrics. Centering horizontally isn't too hard but vertically seems a bit difficult. I've tried using the FontMetrics getAscent, getLeading, getXXXX methods in various combinations but no matter what I've tried the text is always off by a few pixels. Is there a way to measure the exact height of the text so that it is exactly centered.

    Read the article

  • For Qt 4.6.x, how to auto-size text to fit in a specified width?

    - by darenchow
    Inside of my QGraphicsRectItem::paint(), I am trying to draw the name of the item within its rect(). However, for each of the different items, they can be of variable width and similarly names can be of variable length. Currently I am starting with a maximum font size, checking if it fits and decrementing it until I find a font size that fits. So far, I haven't been able to find a quick and easy way to do this. Is there a better, or more efficient way to do this? Thanks! void checkFontSize(QPainter *painter, const QString& name) { // check the font size - need a better algorithm... this could take awhile while (painter->fontMetrics().width(name) > rect().width()) { int newsize = painter->font().pointSize() - 1; painter->setFont(QFont(painter->font().family(), newsize)); } }

    Read the article

  • Unexpected StackOverflowError in KeyListener

    - by BillThePlatypus
    I am writing a program that can write sets of questions for review to a file for another program to read. The possible answers are typed into JTextFields at the bottom. It has code to ensure that there won't bew more than one blank JTextField at the end. When I type in answers, at varying points it will throw a StackOverflowError. The stack trace: Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) at java.awt.AWTEventMulticaster.keyPressed(AWTEventMulticaster.java:232) and the code: package writer; import java.awt.BorderLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.util.ArrayList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import main.QuestionSet; public class SetPanel extends JPanel implements KeyListener { private QuestionSet set; private WriterPanel writer; private JPanel top=new JPanel(new BorderLayout()),controls=new JPanel(new GridLayout(1,0)),answerPanel=new JPanel(new GridLayout(0,1)); private JSplitPane split; private JTextField title=new JTextField(); private JTextArea question=new JTextArea(); private ArrayList<JTextField> answers=new ArrayList<JTextField>(); public SetPanel(QuestionSet s,WriterPanel writer) { super(new BorderLayout()); top.add(controls,BorderLayout.PAGE_START); title.setFont(title.getFont().deriveFont(40f)); title.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyPressed(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } @Override public void keyReleased(KeyEvent e) { title.setText(WriterPanel.convertString(title.getText())); } }); title.getDocument().addDocumentListener(new DocumentListener(){ @Override public void insertUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void removeUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } @Override public void changedUpdate(DocumentEvent e) { // TODO Auto-generated method stub fitTitle(); } }); top.add(title,BorderLayout.PAGE_END); this.add(top,BorderLayout.PAGE_START); question.setLineWrap(true); question.setWrapStyleWord(true); question.setFont(question.getFont().deriveFont(20f)); question.addKeyListener(new KeyListener(){ @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub question.setText(WriterPanel.convertString(question.getText())); }}); split=new JSplitPane(JSplitPane.VERTICAL_SPLIT,true,new JScrollPane(question),new JScrollPane(answerPanel)); split.setDividerLocation(150); this.add(split,BorderLayout.CENTER); answers.add(new JTextField()); answerPanel.add(answers.get(0)); answers.get(0).addKeyListener(this); } private void fitTitle() { if(title==null||title.getText().equals("")) return; //title.setText(WriterPanel.convertString(title.getText())); String text=title.getText(); Insets insets=title.getInsets(); int width=title.getWidth()-insets.left-insets.right; int height=title.getHeight()-insets.top-insets.bottom; Font root=title.getFont().deriveFont((float)height); FontMetrics m=title.getFontMetrics(root); if(m.stringWidth(text)<width) { title.setFont(title.getFont().deriveFont((float)height)); return; } float delta=-100; while(Math.abs(delta)>.1f) { m=title.getFontMetrics(root); int w=m.stringWidth(text); if(w==width) break; if(Math.signum(w-width)==Math.signum(delta)||root.getSize2D()+delta<0) { delta/=-10; continue; } root=root.deriveFont(root.getSize2D()+delta); } title.setFont(root); } private void fixAnswers() { //System.out.println(answers); while(answers.get(answers.size()-1).getText().equals("")&&answers.size()>1&&answers.get(answers.size()-2).getText().equals("")) removeAnswer(answers.size()-1); if(!answers.get(answers.size()-1).getText().equals("")) { answers.add(new JTextField()); answerPanel.add(answers.get(answers.size()-1)); answers.get(answers.size()-2).removeKeyListener(this); answerPanel.revalidate(); } answers.get(answers.size()-1).addKeyListener(this); } private void removeAnswer(int i) { answers.remove(i); answerPanel.remove(i); answerPanel.revalidate(); } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyPressed(KeyEvent e) { // TODO Auto-generated method stub fixAnswers(); } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } } Thank you in advance for any help.

    Read the article

  • How can I do printing in Java with layouts instead of low level coordinates?

    - by Jonas
    I need to to some printing from my Java Swing application. I have tried to use Java Tutorials, but everything is very low level, and time-consuming. I have to specify the coordinates for every line that I want to print. It it also very lowlevel to use text, because I have to use FontMetrics and calculate what space all text fills up. Is there any easier way to to printing in Java? I would like to design the documents with something like layout managers instead. Any good library or API?

    Read the article

  • How can I print a text in two columns using Java Swing?

    - by Jonas
    I have a longer text saved in a String. I would like to print the text in two columns on a single page. How can I do this using Java Swing? I don't understand how I can wrap the text when it's time to use a new line. I have read Lesson: Printing in the Java tutorial, but I haven't found any useful methods for working with text or Strings except FontMetrics. Is there any good methods in the Java API for this or is there any good library I can use for this?

    Read the article

  • Problem with boundary collision

    - by James Century
    The problem: When the player hits the left boundary he stops (this is exactly what I want), when he hits the right boundary. He continues until his rectangle's left boundary meets with the right boundary. Outcome: https://www.youtube.com/watch?v=yuJfIWZ_LL0&feature=youtu.be My Code public class Player extends GameObject{ BufferedImageLoader loader; Texture tex = Game.getInstance(); BufferedImage image; Animation playerWalkLeft; private HealthBarManager healthBar; private String username; private int width; private ManaBarManager manaBar; public Player(float x, float y, ObjectID ID) { super(x, y, ID, null); loader = new BufferedImageLoader(); playerWalkLeft = new Animation(5,tex.player[10],tex.player[11],tex.player[12],tex.player[13],tex.player[14],tex.player[15],tex.player[17],tex.player[18]); } public void tick(LinkedList<GameObject> object) { setX(getX()+velX); setY(getY()+velY); playerWalkLeft.runAnimation(); } public void render(Graphics g) { g.setColor(Color.BLACK); FontMetrics fm = g.getFontMetrics(g.getFont()); if(username != null) width = fm.stringWidth(username); if(username != null){ g.drawString(username,(int) x-width/2+15,(int) y); } if(velX != 0){ playerWalkLeft.drawAnimation(g, (int)x, (int)y); }else{ g.drawImage(tex.player[16], (int)x, (int)y, null); } g.setColor(Color.PINK); g.drawRect((int)x,(int)y,33,48); g.drawRect(0,0,(int)Game.getWalkableBounds().getWidth(), (int)Game.getWalkableBounds().getHeight()); } @SuppressWarnings("unused") private Image getCurrentImage() { return image; } public float getX() { return x; } public float getY() { return y; } public void setX(float x) { Rectangle gameBoundry = Game.getWalkableBounds(); if(x >= gameBoundry.getMinX() && x <= gameBoundry.getMaxX()){ this.x = x; } } public void setY(float y) { //IGNORE THE SetY please. this.y = y; } public float getVelX() { return velX; } public void setHealthBar(HealthBarManager healthBar){ this.healthBar = healthBar; } public HealthBarManager getHealthBar(){ return healthBar; } public float getVelY() { return velY; } public void setVelX(float velX) { this.velX = velX; } public void setVelY(float velY) { this.velY = velY; } public ObjectID getID() { return ID; } public void setUsername(String playerName) { this.username = playerName; } public String getUsername(){ return this.username; } public void setManaBar(ManaBarManager manaBar) { this.manaBar = manaBar; } public ManaBarManager getManaBar(){ return manaBar; } public int getLevel(){ return 1; } public boolean isPlayerInsideBoundry(float x, float y){ Rectangle boundry = Game.getWalkableBounds(); if(boundry.contains(x,y)){ return true; } return false; } } What I've tried: - Using a method that checks if the game boundary contains player boundary rectangle. This gave me the same result as what the check statement in my setX did.

    Read the article

  • Cannot get right height of text in java.awt.BufferdImage/Graphics2D

    - by Tommy
    Im creating a servlet that renders a jpg/png with a given text. I want the text to be centered on the rendered image. I can get the width, but the height i'm getting seems to be wrong Font myfont = new Font(Font.SANS_SERIF, Font.BOLD, 400); BufferedImage image = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setFont(myfont); g.setColor(Color.BLACK); FontMetrics fm = g.getFontMetrics(); Integer textwidth = fm.stringWidth(imagetext); Integer textheight = fm.getHeight(); FontRenderContext fr = g.getFontRenderContext(); LineMetrics lm = myfont.getLineMetrics("5", fr ); float ascent = lm.getAscent(); float descent = lm.getDescent(); float height = lm.getHeight(); g.drawString("5", ((imagewidth - textwidth) / 2) , y?); g.dispose(); ImageIO.write(image, "png", outputstream); These are the values I get: textwidth = 222 textheight = 504 ascent = 402 descent = 87 height = 503 Anyone know how to get the exact height om the "5" ? The estimated height should be around 250

    Read the article

1