Drawing strings in java

Java monospace draw string

How can I draw a String in Java (using Graphics2d) in monospace mode? I have a font that looks like LCD screen font, and I want to draw something like LCD label. I am using Digital 7 Mono font. Do you know where I can find another font that will be monospace and lcd (I wan to type only digitals)?

Welcome to SO, javaAmator! Unfortunately, even though you’re doing a project in Java, this question isn’t really suitable for SO because the act of finding a font isn’t programming-related. I suggest you ask over at doctype.com where there are more design-oriented folks. If you ever have questions about stuff like algorithms, programming language syntax or bugs in code, though, we’ll be happy to help!

@Lord Torgamus: I agree with your comment, but I proposed an answer to the drawing question. Sorry if I preempted your offer to help. I usually stick with the platform-specified font families, so I’d welcome any additions or corrections on how to select alternate fonts.

1 Answer 1

How can I draw a String in Java (using Graphics2d) in monospace mode?

The essential method needed to render text is drawString() , as outlined below. There is no «monospace mode», per se, but even proportionally spaced fonts typically use a constant width for digit glyphs .

private static final Font font = new Font("Monospaced", Font.PLAIN, 32); private static final String s = "12:34"; . @Override protected void paintComponent(Graphics g) < super.paintComponent(g); g.setFont(font); int xx = this.getWidth(); int yy = this.getHeight(); int w2 = g.getFontMetrics().stringWidth(s) / 2; int h2 = g.getFontMetrics().getDescent(); g.setColor(Color.green); g.drawString(s, xx / 2 - w2, yy / 2 + h2); >

There’s a complete example here, and you can extend a suitable JComponent to control positioning using a layout manager, as seen here.

Читайте также:  Моя тестовая страница

Источник

How to draw any text using drawString() in Java

Result The above code sample will produce the following result. java_simple_gui.htm All String Methods The String class has a set of built-in methods that you can use on strings. Returns true if the strings are equal, and false if not boolean equalsIgnoreCase() Compares two strings, ignoring case considerations boolean format()

How to draw any text using drawString() in Java

I’m getting into graphical stuff in Java and want to display text. As I’ve read, drawString() is the standard method for this. My code to draw the string is:

import java.awt.*; import javax.swing.*; public class TextDisplay extends JPanel < public void paint(Graphics g) < g.drawString("My Text", 10, 20); >> 

The class executing this is:

import javax.swing.*; public class Main < public static void main(String[] args) < TextDisplay d = new TextDisplay(); JFrame f = new JFrame(); f.getContentPane().add(d); f.setSize(200,200); f.setVisible(true); >> 

This produces a window with the text «My Text» in it as expected. The question now is: How can I draw any String? With this I have to write the String into the paint() method, but I want to input it from somewhere else as a variable.

Don’t use paint() or draw directly into a JFrame . Draw into a JPanel and override paintComponent() . To draw a specific String, store it in an instance field and then call repaint() . You may also want to examine LineMetrics and FontMetrics to be able to properly center the string.

public void paintComponent(Graphics g)

Check out The Java Tutorials for more on painting.

How to draw any text using drawString() in Java, To draw a specific String, store it in an instance field and then call repaint(). You may also want to examine LineMetrics and FontMetrics to be able to properly center the string. public void paintComponent(Graphics g) < super.paintComponent(g); g.drawString(mystring, x, y); >Check out The Java Tutorials for more on painting.

Java Examples — Draw text using GUI

Problem Description

How to draw text using GUI?

Solution

Following example demonstrates how to draw text drawString(), setFont() methods of Graphics class.

import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel < public void paint(Graphics g) < Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 96); g2.setFont(font); g2.drawString("Text", 40, 120); >public static void main(String[] args) < JFrame f = new JFrame(); f.getContentPane().add(new Main()); f.setSize(300, 200); f.setVisible(true); >>

Result

The above code sample will produce the following result.

Text is displayed in a frame.

The following is an example to draw text using GUI.

import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; public class Panel extends JPanel < public void paint(Graphics gr) < Graphics2D g = (Graphics2D)gr; g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 96); g.setFont(font); g.drawString("Tutorialspoint", 40, 120); >public static void main(String[] args) < JFrame f = new JFrame(); f.getContentPane().add(new Panel()); f.setSize(300, 200); f.setVisible(true); >>

Result

The above code sample will produce the following result.

Text is displayed in a frame.

Java String format() Method With Examples, Java String format () Method With Examples. In java, String format () method returns a formatted string using the given locale, specified format string, …

Java String Methods

All String Methods

The String class has a set of built-in methods that you can use on strings.

Method Description Return Type
charAt() Returns the character at the specified index (position) char
codePointAt() Returns the Unicode of the character at the specified index int
codePointBefore() Returns the Unicode of the character before the specified index int
codePointCount() Returns the number of Unicode values found in a string. int
compareTo() Compares two strings lexicographically int
compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences int
concat() Appends a string to the end of another string String
contains() Checks whether a string contains a sequence of characters boolean
contentEquals() Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer boolean
copyValueOf() Returns a String that represents the characters of the character array String
endsWith() Checks whether a string ends with the specified character(s) boolean
equals() Compares two strings. Returns true if the strings are equal, and false if not boolean
equalsIgnoreCase() Compares two strings, ignoring case considerations boolean
format() Returns a formatted string using the specified locale, format string, and arguments String
getBytes() Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array byte[]
getChars() Copies characters from a string to an array of chars void
hashCode() Returns the hash code of a string int
indexOf() Returns the position of the first found occurrence of specified characters in a string int
intern() Returns the canonical representation for the string object String
isEmpty() Checks whether a string is empty or not boolean
lastIndexOf() Returns the position of the last found occurrence of specified characters in a string int
length() Returns the length of a specified string int
matches() Searches a string for a match against a regular expression, and returns the matches boolean
offsetByCodePoints() Returns the index within this String that is offset from the given index by codePointOffset code points int
regionMatches() Tests if two string regions are equal boolean
replace() Searches a string for a specified value, and returns a new string where the specified values are replaced String
replaceFirst() Replaces the first occurrence of a substring that matches the given regular expression with the given replacement String
replaceAll() Replaces each substring of this string that matches the given regular expression with the given replacement String
split() Splits a string into an array of substrings String[]
startsWith() Checks whether a string starts with specified characters boolean
subSequence() Returns a new character sequence that is a subsequence of this sequence CharSequence
substring() Returns a new string which is the substring of a specified string String
toCharArray() Converts this string to a new character array char[]
toLowerCase() Converts a string to lower case letters String
toString() Returns the value of a String object String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends of a string String
valueOf() Returns the string representation of the specified value String

Java String, Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), … Code samplechar[] ch=<'j','a','v','a','t','p','o','i','n','t'>;String s=new String(ch);Feedback

What is the simplest way to draw in Java?

What is the simplest way to draw in Java?

import java.awt.*; import javax.swing.*; public class Canvas < private JFrame frame; private Graphics2D graphic; private JPanel canvas; public Canvas() < frame = new JFrame("A title"); canvas = new JPanel(); frame.setContentPane(canvas); frame.pack(); frame.setVisible(true); >public void paint(Graphics g) < BufferedImage offImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Grapics2D g2 = offImg.createGraphics(); g2.setColor(new Color(255,0,0)); g2.fillRect(10,10,200,50); >> 

This doesn’t work and I have no idea how to get anything to appear.

Источник

How do you draw a string centered vertically in Java?

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.

4 Answers 4

Note, you do need to consider precisely what you mean by vertical centering.

Fonts are rendered on a baseline, running along the bottom of the text. The vertical space is allocated as follows:

--- ^ | leading | -- ^ Y Y | Y Y | Y Y | ascent Y y y | Y y y | Y y y -- baseline ______Y________y_________ | y v descent yy -- 

The leading is simply the font’s recommended space between lines. For the sake of centering vertically between two points, you should ignore leading (it’s ledding, BTW, not leeding; in general typography it is/was the lead spacing inserted between lines in a printing plate).

So for centering the text ascenders and descenders, you want the

baseline=(top+((bottom+1-top)/2) - ((ascent + descent)/2) + ascent; 

Without the final «+ ascent», you have the position for the top of the font; therefore adding the ascent goes from the top to the baseline.

Also, note that the font height should include leading, but some fonts don’t include it, and due to rounding differences, the font height may not exactly equal (leading + ascent + descent).

Источник

How to draw a String using Graphics2D class?

Greeting, I am working on a simple application to get video feedback from drone. So here is my problem. I have no idea why I cannot show the string words «No video connection» to my panel. Any idea what is happening here? When I run this frame, it just show me a plain empty frame without anything. Thanks. Code:

package dronetest; import com.codeminders.ardrone.ARDrone; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import javax.swing.*; public class testStringVideo extends javax.swing.JFrame < private AtomicReferenceimage = new AtomicReference(); private AtomicBoolean preserveAspect = new AtomicBoolean(true); private BufferedImage noConnection = new BufferedImage(500, 500, BufferedImage.TYPE_INT_RGB); /** * Creates new form testStringVideo */ public testStringVideo() < initComponents(); Graphics2D g2d = (Graphics2D) noConnection.getGraphics(); Font f = g2d.getFont().deriveFont(24.0f); System.err.println(f); g2d.drawString("No video connection", 40, 100); image.set(noConnection); System.err.println(image); >public void setDrone(ARDrone drone) < drone.addImageListener(this); >public void setPreserveAspect(boolean preserve) < preserveAspect.set(preserve); >public void frameReceived(BufferedImage im) < image.set(im); repaint(); >public void paintComponent(Graphics g) < Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int width = getWidth(); int height = getHeight(); drawDroneImage(g2d, width, height); >private void drawDroneImage(Graphics2D g2d, int width, int height) < BufferedImage im = image.get(); if (im == null) < return; >int xPos = 0; int yPos = 0; if (preserveAspect.get()) < g2d.setColor(Color.BLACK); g2d.fill3DRect(0, 0, width, height, false); float widthUnit = ((float) width / 4.0f); float heightAspect = (float) height / widthUnit; float heightUnit = ((float) height / 3.0f); float widthAspect = (float) width / heightUnit; if (widthAspect >4) < xPos = (int) (width - (heightUnit * 4)) / 2; width = (int) (heightUnit * 4); >else if (heightAspect > 3) < yPos = (int) (height - (widthUnit * 3)) / 2; height = (int) (widthUnit * 3); >> if (im != null) < g2d.drawImage(im, xPos, yPos, width, height, null); >> public static void main(String args[]) < /* Set the Nimbus look and feel */ ///* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try < for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) < if ("Nimbus".equals(info.getName())) < javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; >> > catch (ClassNotFoundException ex) < java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (InstantiationException ex) < java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (IllegalAccessException ex) < java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >catch (javax.swing.UnsupportedLookAndFeelException ex) < java.util.logging.Logger.getLogger(testStringVideo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); >// /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() < public void run() < new testStringVideo().setVisible(true); >>); > // Variables declaration - do not modify private javax.swing.JPanel jPanel1; // End of variables declaration > 

Источник

Оцените статью