The code snippet below show you how to draw a string using Graphics2D
. The drawString()
method accept the string to be drawn and their x
and y
coordinate. Here you can also see how to set the antialiasing mode using the setRenderingHint()
method.
package org.kodejava.awt.geom;
import javax.swing.*;
import java.awt.*;
public class DrawString extends JPanel {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setTitle("Draw String Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(new DrawString());
frame.pack();
frame.setSize(420, 300);
frame.setVisible(true);
}
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
// Define rendering hint, font name, font style and font size
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setFont(new Font("Segoe Script", Font.BOLD + Font.ITALIC, 40));
g2.setPaint(Color.ORANGE);
// Draw Hello World String
g2.drawString("Hello World!", 50, 100);
}
}
Run the snippet, and you’ll see the following screen:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024