Ask Question, Ask an Expert

+61-413 786 465

info@mywordsolution.com

Ask Java Expert


Home >> Java

Explain what is FontMetrics in Java?

No word wrapping is completed when you draw a string in an applet, even if you embed newlines in the string along with \n. If you expect that a string may not fit in the applet, you should possibly use a TextArea Component instead. You'll learn about text areas and other AWT Components next class. Therefore there are times when you will require concerning yourself along with how much space a particular string will occupy. You search this out with a FontMetrics object. FontMetrics permit you to determine the height, width or other useful characteristics of a particular string, character, or array of characters in a particular font.

As an example the following program expands on the DrawString applet. Previously text would run off the side of the page if the string was too long to fit in the applet. Presently the string will wrap around if essential.

In order to tell where and whether to wrap the String, you required to measure the string, not its length in characters which can be variable but rather its width and height in pixels. Measurements of this sort on strings clearly depend on the font that's used to draw the string. All other things being equal a 14 point string will be wider than the similar string in 12 or 10 point type.

To measure character and string sizes you need to look at the FontMetrics of the current font. To obtain a FontMetrics object for the current Graphics object you use the java.awt.Graphics.getFontMetrics() method. From java.awt.FontMetrics you'll need fm.stringWidth(String s) to return the width of a string within a particular font, and fm.getLeading() to obtain the appropriate line spacing for the font. There are several more methods in java.awt.FontMetrics that let you measure the heights and widths of exact characters as well as ascenders, descenders and more, but these three methods will be enough for this program.

At last you'll need the StringTokenizer class from java.util to split up the String into individual words. therefore you do required to be careful lest some annoying beta tester (or, worse yet, end user) tries to see what happens when they feed the word antidisestablishmentarianism or supercalifragilisticexpialidocious into an applet that's 50 pixels across.

import java.applet.*;
import java.awt.*;
import java.util.*;

public class WrapTextApplet extends Applet {

private String inputFromPage;

public void init() {
this.inputFromPage = this.getParameter("Text");
}

public void paint(Graphics g) {

int line = 1;
int linewidth = 0;
int margin = 5;
StringBuffer sb = new StringBuffer();
FontMetrics fm = g.getFontMetrics();
StringTokenizer st = new StringTokenizer(inputFromPage);

while (st.hasMoreTokens()) {
String nextword = st.nextToken();
if (fm.stringWidth(sb.toString() + nextword) + margin <
this.getSize().width) {
sb.append(nextword);
sb.append(' ');
}
else if (sb.length() == 0) {
g.drawString(nextword, margin, line*fm.getHeight());
line++;
}
else {
g.drawString(sb.toString(), margin, line*fm.getHeight());
sb = new StringBuffer(nextword + " ");
line++;
}

}
if (sb.length() > 0) {
g.drawString(sb.toString(), margin, line*fm.getHeight());
line++;
}

}

}

Java, Programming

  • Category:- Java
  • Reference No.:- M9547881

Have any Question?


Related Questions in Java

Overviewyou are required to use java se 80 and javafx to

Overview You are required to use Java SE 8.0 and JavaFX to develop a Graphical User Interface (GUI) for the FlexiRent rental property management program created in Assignment 1. This assignment is designed to help you: 1 ...

Assignment taskwrite a java console application that allows

Assignment task Write a java console application that allows the user to read, validate, store, display, sort and search data such as flight departure city (String), flight number (integer), flight distance (integer), fl ...

Project descriptionwrite a java program to traverse a

Project Description: Write a java program to traverse a directory structure (DirWalker.java) of csv files that contain csv files with customer info. A simple sample in provided in with the sample code but you MUST will r ...

Overviewyou are required to use java se 80 and javafx to

Overview You are required to use Java SE 8.0 and JavaFX to develop a Graphical User Interface (GUI) for the FlexiRent rental property management program created in Assignment 1. This assignment is designed to help you: 1 ...

Assessment database and multithread programmingtasktask 1

Assessment: Database and Multithread Programming Task Task 1: Grade Processing University grading system maintains a database called "GradeProcessing" that contains number of tables to store, retrieve and manipulate stud ...

Retail price calculatorwrite a java program that asks the

Retail Price Calculator Write a JAVA program that asks the user to enter an item's wholesale cost and its markup percentage. It should then display the item's retail price. For example: (If an item's wholesale cost is 5. ...

Part a specification - robot simulationpart a

PART A Specification - Robot Simulation PART A Requirements To complete this assignment you will use the supplied eclipse project Robot P1/. It is already set up to execute a simple arm movement loop which you will build ...

In relation to javaa what is constructor the purpose of

(In relation to Java) A. What is constructor? the purpose of default constructor? B. How do you get a copy of the object but not the reference of the object? C. What are static variables and instance variables? D. Compar ...

Assessment socket programmingtaskwrite a java gui program

Assessment: Socket Programming Task Write a JAVA GUI program that would facilitate text chatting/exchanging between two or multiple computers over the network/internet, using the concept of JAVA socket programming. If yo ...

Assignment - java program using array of objectsobjectives

Assignment - JAVA Program using array of objects Objectives - This assessment item relates to the course learning outcomes as stated in the Unit Profile. Details - For this assignment, you are required to develop a Menu ...

  • 4,153,160 Questions Asked
  • 13,132 Experts
  • 2,558,936 Questions Answered

Ask Experts for help!!

Looking for Assignment Help?

Start excelling in your Courses, Get help with Assignment

Write us your full requirement for evaluation and you will receive response within 20 minutes turnaround time.

Ask Now Help with Problems, Get a Best Answer

Why might a bank avoid the use of interest rate swaps even

Why might a bank avoid the use of interest rate swaps, even when the institution is exposed to significant interest rate

Describe the difference between zero coupon bonds and

Describe the difference between zero coupon bonds and coupon bonds. Under what conditions will a coupon bond sell at a p

Compute the present value of an annuity of 880 per year

Compute the present value of an annuity of $ 880 per year for 16 years, given a discount rate of 6 percent per annum. As

Compute the present value of an 1150 payment made in ten

Compute the present value of an $1,150 payment made in ten years when the discount rate is 12 percent. (Do not round int

Compute the present value of an annuity of 699 per year

Compute the present value of an annuity of $ 699 per year for 19 years, given a discount rate of 6 percent per annum. As