I am an avid programmer but today is my first Java lesson.
public void Paint (Graphics g)
{
if(g instanceof Graphics2D)
{
Graphics2D g2d = (G
In the given code, what you want is
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);
}
}
}
To draw text on the screen with JFrame, you can use Graphics.drawText(String text, int x, int y)
method.
The first parameter is the string that you want to display and last two parameters are coordinates where this text will start.
Here is the example 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 out to learn more about how to display text and graphics in Java: https://javatutorial.net/display-text-and-graphics-java-jframe
1) not possible directly paint to the JFrame
, you can painting:
put there JPanel
getContentPane from JFrame
2) for Swing JComponents
is there paintComponent()
instead of paint()
, otherwise your painting couldn't be drawed corretly
3) another options are:
paint to the JFrame's RootPane
paint to the JFrame's GlassPane
4) more in 2D Graphics tutorial