wilkers
wilkers

Reputation: 35

Why can I post text with JLabel but not with .drawString

Im not sure what I'm doing wrong as i've seen it done this way countless times before in various open source programs and games. below is my code that is giving me the error that g2 isn't a assigned variable? im confused..

package scratch;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/* FrameDemo.java requires no other files. */
public class okay {
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Create and set up the window.
        JFrame frame = new JFrame("FrameDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel emptyLabel = new JLabel("helllo", JLabel.CENTER);
        emptyLabel.setPreferredSize(new Dimension(250, 100));
        frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

    public void paint ( Graphics g ){
        Graphics2D g2 = (Graphics2D) g;
        g2.drawString("hello",0,0);
}





    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
                paint(g2);
            }
        });
    }
}

Upvotes: 1

Views: 145

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Your class extends no Swing component and so the paint method is not an override and does nothing. Instead you should have your class extend JPanel, put this JPanel into a JFrame, and override paintComponent. Also, 1) always give methods that you think are overriding super methods the @Override annotation. This way the compiler would have told you immediately that what you're doing is wrong. 2) Don't guess when it comes to learning new Java features -- look at and study the appropriate tutorial before trying this stuff. Here the painting in Swing tutorial would have answered these questions for you.


e.g.,

public class Foo extends JPanel {
  @Override
  protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString("hello", 0, 20);
  }

  public static void main(String[] args) {
    JFrame frame = new JFrame("Foo");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.add(new Foo());
    frame.pack();
    frame.setVisible(true);
  }
}

Upvotes: 1

Related Questions