0

Part of a simple Java application I have draws out two strings within a frame. The first string is rendered, however, the second is not.

import java.awt.*;
//Begin troublesome section    
class NewFrame extends Frame {

  public void paint (Graphics g)
  {
    g.drawString ("Foo", 70, 70);
  }

 public void paint2 (Graphics g)
  {
    g.drawString ("Bar", 600, 600);
  }

}
//End troublesome section
public class FooBar {

  public static void main (String[] argv)
  {
    NewFrame nf = new NewFrame ();

    nf.setTitle ("Foo Bar");
    nf.setResizable (true);
    nf.setBackground (Color.cyan);
    nf.setSize (700, 700);

    nf.setVisible (true);
  }
}

The part of the code in question is what is noted as the "troublesome section".

2 Answers2

5

The method paint is called automatically by Java to paint the window. See the method documentation

The method paint2 is not standard and will not be invoked automatically.

Either

public void paint(Graphics g) {
    super.paint(g);
    g.drawString ("Foo", 70, 70);
    g.drawString ("Bar", 600, 600);
}

or

public void paint(Graphics g) {
    super.paint(g);
    g.drawString ("Foo", 70, 70);
    paint2(g);
}

public void paint2(Graphics g) {
    g.drawString ("Bar", 600, 600);
}
Matteo
  • 14,696
  • 9
  • 68
  • 106
  • 1
    Remember, when overriding `paint()` in `Frame` or `paintComponent()` in `JPanel`: You must call the superclass method. i.e. `super.paint(g);` and `super.paintComponent(g);` respectively. – Ron Jan 03 '14 at 12:08
  • Don't you need to pass `Graphics g` to `paint2()` in the second snippet? – PakkuDon Jan 03 '14 at 12:08
4

That's hardly surprising: paint is being called by a base class function (somewhere in the implementation of one of the methods in Frame: put a breakpoint in paint and, using your debugger, look at the call stack when the breakpoint is reached), paint2 is not called by anything.

Why not call paint2 from paint yourself? Better still, incorporate the code from paint2 to paint. So you don't get yourself into this kind of pickle again, add an @Override annotation to paint; not forgetting to call paint in the parent class:

@Override
public void paint (Graphics g)
{
    super.paint(g); /*your first job is to call the base method*/
Bathsheba
  • 231,907
  • 34
  • 361
  • 483