1

I am new to the swing and graphics and am trying to get this to work for drawing a string on a label by making an object class called DrawString. A panel currently pops up with nothing on it. I would like to thank you for any guidance you can give.

   package view;

    import javax.swing.JFrame;
    import javax.swing.JPanel;

    public class Run {

    public static void main(String[] args) {


        JPanel panel = new JPanel();
        DrawString text = new DrawString();

        JFrame window = new JFrame();
        window.setVisible(true);
        window.setSize(400, 400);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        text.display("Boo");
        panel.setLocation(((window.getWidth()/2)-(panel.getWidth()/2)), 
        ((window.getHeight()/2)-(panel.getHeight()/2)));
        panel.setSize(200, 200);
        window.add(panel);
        panel.add(text);



    }

}



   package view;

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JLabel;

@SuppressWarnings("serial")
public class DrawString extends JLabel{

    String string;
    Font font = new Font("TimesRoman",Font.PLAIN, 30);

    public DrawString() {
        super();


    }
    public void display(String string){
        this.string=string;
        repaint();
    }
    public void drawString(Graphics comp){
        super.paintComponent(comp);
        Graphics2D g = (Graphics2D) comp;
        g.setFont(font);
        g.drawString(string, JLabel.CENTER, JLabel.CENTER);
    }


}
drhunn
  • 21
  • 1
  • 2
  • 13

1 Answers1

2

I am learning and experimenting…

It's not clear if you want to experiment with JLabel or custom painting. You might want to start with a working JLabel#setText() example or TextLayout#draw() example.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045