在Swing的面板中,我使用paintComponent使用Graphics2D绘制具有不同坐标的字符串:

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


有没有一种方法可以将多个结果图纸组合成一个drawString?

编辑:我基本上使用unicode字符绘制一个音乐梯级,我想绘制另一个梯级。我希望会有一种干净的方法来复制它。

最佳答案

样例代码。

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);
    }
}

关于java - Java-在Swing中加入多个drawString,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9220703/

10-10 03:28