See this answer to Swing: Obtain Image of JFrame as well as Why does the JTable header not appear in the image? for tips on painting components that have not yet been rendered. I expect the fix to your problem is shown in the label of LabelRenderTest.java
.
JLabel textLabel = new JLabel(title);
textLabel.setSize(textLabel.getPreferredSize());
Update
Dimension dim = new Dimension(50,50);
panel.setSize(dim); // very important!
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
// ...
Or here is the complete source. The size of the label also needs to be set.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class RenderTest {
RenderTest() {
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
Dimension dim = new Dimension(50,50);
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
JLabel label = new JLabel("hello");
label.setSize(label.getPreferredSize());
panel.add(label);
BufferedImage bi = getScreenShot(panel);
JOptionPane.showMessageDialog(null, new JLabel(new ImageIcon(bi)));
}
private BufferedImage getScreenShot(JPanel panel){
BufferedImage bi = new BufferedImage(
panel.getWidth(), panel.getHeight(), BufferedImage.TYPE_INT_ARGB);
panel.paint(bi.getGraphics());
return bi;
}
public static void main(String[] args) {
new RenderTest();
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…