我认为您正在寻找的解决方案是构建一个包含所需内容的新 JPanel 并打印副本。如果您使用 CellRendererPane 执行此操作,您可以获得听起来像您正在寻找的精确大小调整行为。
如果您的 JComponent 编写得相当好,那么新建一个新的 JComponent 并将其模型设置为与原始模型相同应该不是问题。
CellRendererPane cellRendererPane = new CellRendererPane();
// It's important to add the cell renderer pane to something
// you can use the same one for all of your exporting if you like and just
// add it to your main frame's content pane - it won't show up anywhere.
add(cellRendererPane);
JPanel printPanel = createCopy(panel);
cellRendererPane.paintComponent(g, printPanel, null, 0, 0, exportDim.width, exportDim.height, true);
这是一个完整的工作示例。 createPanel() 方法应该创建您想要呈现的任何组件。真实的示例应该确保使用相同的模型,而不是为一次性组件重新创建新模型。
public class SCCE {
public static void main(String[] args) throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
final JFrame f = new JFrame("SCCE");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(SCCE.createPanel());
final CellRendererPane backgroundRenderer = new CellRendererPane();
// Add the renderer somewhere where it won't be seen
f.getContentPane().add(backgroundRenderer, BorderLayout.NORTH);
f.getContentPane().add(createSaveButton(backgroundRenderer), BorderLayout.SOUTH);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
// Create your custom component from whatever model here..
private static final Component createPanel() {
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < 10; i++) {
model.addElement("Item number " + i);
}
return new JList(model);
}
private static JButton createSaveButton(final CellRendererPane backgroundRenderer) {
return new JButton(new AbstractAction("Save image to file") {
@Override
public void actionPerformed(ActionEvent e) {
Dimension d = new Dimension(400, 300);
BufferedImage img = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();
backgroundRenderer.paintComponent(g, createPanel(), null, 0, 0, d.width, d.height, true);
g.dispose();
try {
File output = new File("test.png");
System.err.println("Saved to " + output.getAbsolutePath());
ImageIO.write(img, "png", output);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
}