我正在尝试从JPanel创建BufferedImage,而不使用JFrame.昨天,我终于能够在该社区的帮助下显示该图像(请参阅下文),但是现在遇到了一些布局问题. BufferedImage上的所有组件都从0,0开始绘制,而不是遵循布局管理器.有人知道这个问题的解决方案吗?
昨天的问题:Can I create a BufferedImage from a JPanel without rendering in a JFrame?
在下面的代码中,两个标签将在图像的左上角相互覆盖.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class RenderTest {
RenderTest() {
JPanel panel = new JPanel();
panel.setBackground(Color.RED);
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
Dimension dim = new Dimension(150,50);
panel.setSize(dim);
panel.setMinimumSize(dim);
panel.setMaximumSize(dim);
panel.setPreferredSize(dim);
JLabel label = new JLabel("hello");
JLabel label2 = new JLabel(" world");
label.setSize(label.getPreferredSize());
label2.setSize(label2.getPreferredSize());
panel.add(label);
panel.add(label2);
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();
}
}
解决方法:
更多tips from the queen.“致电addNotify()”.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class RenderTest {
RenderTest() {
JPanel panel = new JPanel(new GridLayout(0,1,10,10));
panel.setBackground(Color.RED);
panel.setBorder(new EmptyBorder(5,25,5,25));
JLabel label = new JLabel("hello");
panel.add(label);
JLabel label2 = new JLabel("goodbye");
panel.add(label2);
panel.addNotify();
panel.setSize(panel.getPreferredSize());
panel.validate();
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();
}
}
顺便说一句-我不建议将尺寸设置为任意尺寸,然后尝试将其与布局结合使用.只是以为我要提到,因为我得到的印象就是您想要的.在这种情况下,我们可能会精确定位所有位置,因此这是一种方法,而选择一种方法或另一种方法.