0

My problem is that when i use

 public void paint(Graphics g)
 {}

Method to draw a String as

 g.drawString("hello java",0,0);

My full code is

import javax.swing.*;
 import java.awt.*;
class test
extends JFrame
{
public void testing()
{
setSize(500,500);
show();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{ super.paint(g);
g.drawString("HELLO JAVA");
}
public static void main(String arg[])
{
test t=new test();
t.testing();
} }

In JFrame i am getting a black screen without hello java being drawn Please help me Thanks in advance

Priyank
  • 37
  • 1
  • 7
  • That's not enough information to give a qualified answer. Please give us a minimal working example of your problem. -> http://en.wikipedia.org/wiki/Minimal_Working_Example – Thomas Nov 02 '14 at 11:58
  • maybe calling `super.paint(g)` first would help – SomethingSomething Nov 02 '14 at 12:03
  • See examples [here](http://stackoverflow.com/a/11567852/230513) and [here](http://stackoverflow.com/a/3845270/230513). – trashgod Nov 02 '14 at 14:01

1 Answers1

0

To display the inherited frame correctly, the paint method in the inherited class should contain the call of super.paint():

class MyFrame extends JFrame {

    public void paint(Graphics g) {
        super.paint(g);
        g.drawString("hello java", 50, 50);
    }

}

EDIT (painting in the panel):

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

public class CustomPaint {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                JFrame frame = new JFrame("CustomPaint");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new MyPanel());
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
}

class MyPanel extends JPanel {

    public Dimension getPreferredSize() {
        return new Dimension(320, 240);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        String msg = "HELLO JAVA";
        g2.setPaint(Color.BLUE);
        int w = (getWidth() - g.getFontMetrics().stringWidth(msg)) / 2;
        g2.drawString(msg, w, getHeight() / 2);
    }
}
MirecXP
  • 443
  • 7
  • 18
  • 1
    Don't override paint() on a JFrame!!! Custom painting is done by overriding paintComponent() on a JPanel and then you add the panel to the frame. Read the section from the Swing tutorial on [Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/index.html) for more information and working examples. – camickr Nov 02 '14 at 13:47
  • You are right camickr. Priyank, see the edited post. – MirecXP Nov 02 '14 at 15:02