So, I have been modding Minecraft for a while, and I saw how it generates its buttons. It takes a very wide image of a button, takes part of the left, takes part of the right side, and puts the two back together to form a smaller image.
I’m sorry, but I can’t explain this well in words, so let me just show you with bad Paint.Net skills:

However, I cannot get it to work, as it turns out like this:

Here is part of my code:
public class ComponentToolbarButton extends JComponent implements MouseListener {
private static final int HEIGHT = 40;
// ... other methods here
private BufferedImage getImageBasedOnWidth(Graphics g) {
BufferedImage finalImage = null;
BufferedImage rawImage = null;
// Try/catch block to initialize rawImage
// Setting font and things here
int compWidth = determineComponentWidth(g); // Returns the (should-be) width of the component
if (compWidth != getWidth()) {
setPreferredSize(new Dimension(compWidth, HEIGHT)); // Just making sure :)
}
finalImage = new BufferedImage(compWidth, HEIGHT, BufferedImage.TYPE_INT_RGB);
Graphics finalImageGraphics = finalImage.getGraphics();
// Draw left side:
finalImageGraphics.drawImage(rawImage, 0, 0, 0, compWidth / 2, 0, 0, compWidth, HEIGHT, null);
// Draw right side:
finalImageGraphics.drawImage(rawImage, compWidth / 2, 0, compWidth, HEIGHT, rawImage.getWidth() / 2 - compWidth,
0, rawImage.getWidth(), rawImage.getHeight(), null);
return finalImage;
}
}
Thanks in advance! (I tried to shorten the code as much as I could BTW)
Okay, after some thinking, I came up with this little hack to demonstrate how I believe it should work 😛
First, one should never try and build all the image segments in the
paintmethod, it will slow down the paint routine and consume to much memory, but for this example, I just wanted to demonstrate the idea. Use a backing buffer instead (which I think is what you were trying to do anyway).This will produce this: