1

In Swing, in a panel, I use paintComponent to draw strings with different coordinates using Graphics2D:

g2.drawString("one", 0, 0);
g2.drawString("two", 50, 50);

Is there a way to combine the multiple resulting drawings into one drawString?

Edit: I basically draw a musical stave using unicode characters, and I want to draw another stave. I was hoping there would be a clean way of duplicating it.

trashgod
  • 203,806
  • 29
  • 246
  • 1,045
Devan Somaia
  • 645
  • 1
  • 8
  • 21

2 Answers2

2

Sample code.

private BufferedImage sample; //declare as class member to reuse instance

@Override
protected void paintComponent(Graphics g) {
    if (sample == null) { // lazy initialization, but you could do it even in constructor
        sample = new BufferedImage(sampleWidth, sampleHeight, bufferedImage.TYPE_INT_ARGB);
        Graphics2D g2d = sample.createGraphics();
        g2d.setColor(Color.WHITE);
        g2d.fillRect(0, 0, sampleWidth, sampleHeight);
        g2d.setColor(Color.BLACK);
        g2d.drawString("Some text", 10, 10);
        g2d.drawWhateverYouNeed(....);
    }

    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    // draw sample image three times, in sequence
    for (int i = 0; i < 3; i++) { 
        g.drawImage(sample, 0, i * sampleHeight, this);
    }
}
lxbndr
  • 2,159
  • 1
  • 15
  • 17
0

No, there is no way to do it. But what do you wish to achieve with such combining? Better performance? Some specific layout?

lxbndr
  • 2,159
  • 1
  • 15
  • 17
  • I basically draw a musical stave using unicode characters, and I want to draw another stave. I was hoping there would be a clean way of duplicating it. – Devan Somaia Feb 10 '12 at 00:05
  • 2
    If you need many copies of any part of your render, consider to use instance of `BufferedImage` to render sample image and then draw that image on component as many times as you need. You even may store sample outside of `paintComponent` method and render it one time (at initialization). **UPD.** I will provide sample code in separate answer if this approach fits you. – lxbndr Feb 10 '12 at 00:18
  • yes that approach fits my goal, and is something I will need later in my project. If you could provide some sample code that would be great! Thanks in advance! – Devan Somaia Feb 10 '12 at 18:12