Master Font Manipulation in Java

Master Font Manipulation in Java

hether you think very much about fonts or not, as an application user, you are constantly interacting with and manipulating fonts. Particularly in word processing programs, where it’s common to change typestyles and typefaces for different parts of your document.

So too, the ability to change typestyles and typefaces is useful as an application programmer. As a simple example, think of the “About” screen, which most every program has. It is common to see the program name in large text, to help it stand out, and legal jargon and copyright notices in smaller sized text. You can see this in Microsoft Word’s Help/About menu.

When writing computer programs, you want your user interface to be as intuitive as possible. This means you will use radio buttons and checkboxes and other visual components that your end users already understand. However, it also means that you want written information to stand out as clearly as possible.

As well as varying the size of text, you may want to enhance specific words?by rendering them in bold, perhaps, or italics?to draw readers’ attention.

Also, you might want to consider how the reader will use the textual information you have provided. For instance, for information displayed on the screen, you might wish to use a sans-serif font such as Arial. However, for information that the user will print out from your application onto paper, you might wish to use a serif font such as Times Roman. These simple changes can help your user read and digest the information you want to convey.

So, with that in mind, let’s see how you can manage your textual information in Java, to enhance your own applications.

Anatomy of a Java Font Object
In Java, fonts are represented by instances of the java.awt.Font class. A Font object comprises three parts: a font name (e.g. serif), style identifier (e.g. bold) and a point size (e.g. 10).

As with any Java object, we can create an instance of the Font object in memory at any time. Of course, a visual item like a font is only meaningful if we actually apply it to something displayed on the screen, such as the text on a button or a label. Just because we can create a font object?as in the following examples?doesn’t necessarily mean anything is seen on the screen.

Here are some examples of declaring fonts:

Font littleFont = new Font("Monospaced", Font.PLAIN, 10);Font bigFont = new Font("Serif", Font.BOLD, 24);

In word processing programs we’re accustomed to selecting specific fonts, by name, such as Arial, Garamond, Times New Roman, etc. However, because it was designed to run on as many different operating systems as possible, Java does not use specific font names because those names may be specific to a particular system. Rather, it uses symbolic names that refer to a particular type of font?”Monospaced” and “Serif.” These names are translated to a specific font on the executing computer by the Java interpreter.

Table 1 describes the five font classes that are available.

Table 1. The Five Font Classes

Serif

Contains serifs on the edges of characters, e.g. Times Roman

SansSerif

A font without serifs, e.g. Helvetica

Monospaced

A non-proportional font, such as Courier, where the letter “i” takes as much space as the letter “w”

Dialog

A font used for dialog screens, such as opening a file

DialogInput

A font used for user input on dialog screens, such as typing in a file name

The way the Java interpreter maps the font is through a file called fonts.properties. This file will easily be found in the lib subdirectory of your Java development environment, whether you’re using Sun’s JDK or a third-party Java implementation such as Borland JBuilder.

There are three style identifiers, namely PLAIN, BOLD, and ITALIC. These are constant values that belong to the Font object. You can apply both BOLD and ITALIC to a font at the same time. (Actually, you can apply any combination, but as you will appreciate, PLAIN has no effect unless it is used by itself.)

To actually use a Font object, you simply specify it as an argument to the setFont() method of any component?such as a button?or to an applet’s Graphics object, which is used to paint the canvas. Any subsequent text-drawing command for that applet, such as drawString(),will use the specified font.

A second useful class is java.awt.FontMetrics. This object can give us detailed size and spacing information about text that has been rendered in a specific font. As you might imagine, different systems will have different fonts available, and so careful programmers will never presume that a word will take up the exact same amount of space on one screen that it will on another. So, FontMetrics is useful for retrieving information about how the font you choose is sized on a specific system.

The Graphics object has a getFontMetrics() method that gives us the information we need about how the font is sized for the font currently in use:

public void paint (Graphics g){  FontMetrics fm = g.getFontMetrics ();  ...}

Listing 1 is a Java applet that draws a word in a particular font and then draws reference lines showing certain characteristics, namely, the font’s baselines and its descent and ascent properties (described below).

Figure 1: Running the FontShow applet in Sun’s AppletViewer.
Figure 2 : Running the FontShow applet in Internet Explorer.

The applet requires two parameters be passed to it: “word” (the word to be displayed) and “fontname” (the font style to be used). Once you’ve written the code to pass these parameters, try entering different values in the HTML page (see Listing 2) and re-running the applet.

The program might look a bit complicated, but there’s not really much to it. Most of the code is in the applet’s paint() method, which merely sets the font, draws our word, and overlays a few lines that help illustrate some of the font’s metrics. You can make use of the metrics information to format a screen without making any prior assumptions about the font.

By default, text is rendered above and to the right of the coordinates specified in the drawString() method. If that starting point is the origin of a coordinate system, then the axes are the baselines of the font, and here these lines are drawn in white.

In the sample application the ascent, where characters stretch above the baseline (such as the letter “l”) is shown with a green line. Some fonts also have parts of letters that fall below the baseline (such as the letter “g”). This is called the descent and is shown in red.

The FontMetrics object has getMaxAscent() and getMaxDescent() methods that yield the lengths of the ascent and descent. The applet centers our word vertically in the display area by averaging the influence of the ascent and descent. FontMetrics also has a useful stringWidth() method which advises the width of the string when rendered in this font?we use this information for centering our word horizontally.

There are three other FontMetrics methods that I haven’t used here?getLeading() gives the vertical spacing between multiple lines in the font, getHeight() gives the total line height (namely, ascent + descent + leading) in the font, and getMaxAdvance() returns the maximum character width of any character in the font.

That’s really all there is to font handling in Java?or, at least as far as the native language goes. Sun has developed more font handling features in its new 2D graphics API libraries, including portable fonts. With portable fonts the font itself is actually taken and bundled into the Java program. This guarantees that the font used will be exactly the one that you selected, regardless of the operating system. However, this is a separate download and is not yet in widespread use or widely supported by Web browsers.

Listings 3 and 4 contain a second applet, AllFonts.java, which lists a sample of each font class. You can use this list to see the appearance of a given message in different fonts and across different operating systems.

Figure 3: Running the AllFonts applet in Sun’s AppletViewer.Pictured is a sample run of the AllFonts applet, running in Sun’s AppletViewer on a Sun Solaris computer.
Figure 4 : Running the AllFonts applet in Internet Explorer.Pictured is a sample run of the AllFonts applet, running in Internet Explorer on a Windows PC.

Less Can Be More
If you can apply everything demonstrated in this article in a live application, then you can consider yourself a Java font master! You should have all the information you need to change the type and style of fonts in your own Java programs and applets to enhance your presentation and help the user.

However, do use this wisely; overuse of font styles is distracting. Many of us remember the rise of desktop publishing back in the ’80s and all the kitsch fliers, brochures, and other documents that tried to cram as many possible font changes as possible into a single page. The purpose of changing your font type and style is to enhance communications, making your programs clearer and more intuitive. So, keep in mind then, that too many font changes can have the opposite effect.

One thing I like to do when considering a new visual technique is to explore how other programmers have implemented it. For example, if you’re making a menu bar, it makes sense to follow the established conventions of software manufacturers who generally use the menu names “File,” “Edit,” and “View” and always put the “Help” menu at the far right.

You can follow similar logic when selecting fonts. Where have other developers varied the font type or style? Did they use a particular type of font for screen information as opposed to print information? The more your application conforms to commonly-accepted standards, the more natural and intuitive your users will find it.

devx-admin

devx-admin

Share the Post:
USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

USA Companies

Top Software Development Companies in USA

Navigating the tech landscape to find the right partner is crucial yet challenging. This article offers a comparative glimpse into the top software development companies in the USA. Through a

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.

Sitemap