4

I use SwingPaintDemo2 from Java Tutorials:

http://download.oracle.com/javase/tutorial/uiswing/examples/painting/SwingPaintDemo2Project/src/painting/SwingPaintDemo2.java

I modified it like this:

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw Text
    g.drawString("This is my custom Panel!",10,20);

    JLabel c = new JLabel("Label");
    c.paint(g);
}

g.drawString works fine. But how can I paint JLabel from this method? It doesn't work.

Dmitry D
  • 760
  • 12
  • 24

2 Answers2

4

I think you have to set a size to your label.

public void paintComponent(Graphics g) {
    super.paintComponent(g);

    // Draw Text
    g.drawString("This is my custom Panel!",10,20);

    JLabel c = new JLabel("Label");
    c.setBounds(0, 0, 400, 30);
    c.paint(g);
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
4

See the LabelRenderTest.java source on this thread. The label is eventually drawn to screen, but it is painted to BufferedImage before ever being displayed.

The important line of the source is..

textLabel.setSize(textLabel.getPreferredSize());
Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • your Examples & Html & Images together +1 – mKorbel Jul 20 '11 at 11:01
  • @mKorbel 'An image paints a thousand words' ( and gets a few up-votes, usually :). HTML is just because I could not be bothered figuring the exact position of every text element. ;) – Andrew Thompson Jul 20 '11 at 11:23
  • I can't to take as your personal attack to my excellent, exciting un-interchangeable, whatever ... form of my English speak :-), as I read some yours edits (or by other NativeSpeakers) then somebody someone must died by laughing :-) – mKorbel Jul 20 '11 at 11:32