Draw text with a graphic on a JFrame

I am a greedy programmer, but today is my first Java lesson.

public void Paint (Graphics g) { if(g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D)g; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } g.drawString("This is gona be awesome", 200, 200); } 

With the code above, I want to write a sentence in a window, but it never writes. What am I doing wrong?

Edit: Nothing. Paint should be paint. I apologize profusely.

+9
source share
3 answers

In this code you need

  g2d.drawString("This is gona be awesome", 200, 200); ^ 

A working example for your reference:

 package Experiments; import java.awt.Container; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JComponent; import javax.swing.JFrame; public class MainClass{ public static void main(String[] args) { JFrame jf = new JFrame("Demo"); Container cp = jf.getContentPane(); MyCanvas tl = new MyCanvas(); cp.add(tl); jf.setSize(300, 200); jf.setVisible(true); } } class MyCanvas extends JComponent { @Override public void paintComponent(Graphics g) { if(g instanceof Graphics2D) { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.drawString("This is gona be awesome",70,20); } } } 
+18
source

1) it is impossible to draw directly on a JFrame , you can color:

  • enter JPanel

  • getContentPane by JFrame

2) for Swing JComponents there is paintComponent() instead of paint() , otherwise your picture cannot be drawn correctly

3) other options:

  • draw a JFrame RootPane

  • paint in JFrame GlassPane

4) more details in a 2D graphics tutorial

+3
source

To draw text on the screen using a JFrame, you can use the Graphics.drawText(String text, int x, int y) method Graphics.drawText(String text, int x, int y) .

The first parameter is the line you want to display, and the last two parameters are the coordinates at which this text starts.

Here is a sample code:

 package example.com; import java.awt.Graphics; import javax.swing.JFrame; import javax.swing.JPanel; public class JFrameGraphics extends JPanel { public void paint(Graphics g){ g.drawString("Hello Text!", 10, 10); } public static void main(String[] args){ JFrame frame= new JFrame("Hello"); frame.getContentPane().add(new JFrmaeGraphics()); frame.setSize(300, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setResizable(false); } } 

Check to learn more about how to display text and graphics in Java: https://javatutorial.net/display-text-and-graphics-java-jframe

0
source

All Articles