简体   繁体   中英

Draw String not visible on JFrame

So for my assignment I need to create a triangle object using this public void draw(Graphics2D g) method to render triangle shape on the canvas.

I tested it out to see if I can print out simple text onto my screen before I start going into the deeper part of my code. I am use to using public void paintComponent(Graphics g) method and it works when I use that method. But it is blank when I use the public void draw(Graphics2D g) method.

What am I doing wrong?

import javax.swing.JFrame;

public class Main {
    public static void main(String[] args){
      Window window = new Window();
      window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      window.setSize(700,500);
      window.setLocation(400,100);
      window.setTitle("Draw Pad");
      window.initialize();
      window.setVisible(true);
     }
}

import java.awt.Container;
import javax.swing.JFrame;
public class Window extends JFrame {
    public void initialize(){
    DrawPanel panel = new DrawPanel();
    Container contentPane = getContentPane(); 
    contentPane.add("Center", panel);
    }
}

import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JPanel;
public class DrawPanel extends JPanel {
    //Doesn't work using this
    public void draw(Graphics2D g)
    {
       g.drawString(("Hello"), 100, 100);
    } 
    //Works using this
    @Override
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.drawString(("Hello"),100,100); 
  }
}

Stepping over the issue of the code example not compiling; you need to start by having a look at

to better understand how painting actually works and how you can work with it

I would then recommend that you go have a look at Working with Text APIs to get a better understanding of how text is rendered using Graphics2D

Why do you expect public void draw(Graphics2D g) to do anything ?
I don't see it invoked at all.
Anyway Swing paint invokes paint() invokes paintComponent() and you should override it to add the functionality you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM