面板需要根據需求進行佈局。如果面板已經沒有在屏幕上實現的是,它可能不會使你希望它做
以下示例假設,該小組沒有被顯示在屏幕上的方式......
setSize(getPreferredSize());
BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
printAll(g);
g.dispose();
try {
ImageIO.write(image, "png", new File([location goes here]);
} catch (IOException e) {
e.printStackTrace();
}
你應該避免自己打電話paint
,可如果組件沒有被在屏幕上實現拋出一個異常,而是使用printAll
另外,如果您創建一個資源,你應該處理掉吧;)
更新
我做了這個快速的例子。屏幕頂部拍攝,左側爲jpeg,右側爲png。
JPEG是30KB和PNG是320KB
我用它來創建它...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class PaintComponent {
public static void main(String[] args) {
new PaintComponent();
}
public PaintComponent() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JPanel paintPane;
public TestPane() {
paintPane = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
paintPane.add(new JLabel("I'm a label"), gbc);
paintPane.add(new JTextField("I'm a text field", 20), gbc);
paintPane.add(new JLabel(new ImageIcon("some\pretty\picture")), gbc);
setLayout(new BorderLayout());
add(paintPane);
JButton paint = new JButton("Capture");
paint.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
BufferedImage image = new BufferedImage(paintPane.getWidth(), paintPane.getHeight(), BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
paintPane.printAll(g);
g.dispose();
try {
ImageIO.write(image, "jpg", new File("Paint.jpg"));
ImageIO.write(image, "png", new File("Paint.png"));
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
add(paint, BorderLayout.SOUTH);
}
}
}
我會確保你實際上是在尋找正確的文件; )
感謝您的意見。不過,當我導出圖像時,我的JPanel正在屏幕上顯示。另外,無論我將圖像導入哪種格式,它們的大小都相同(就內存而言)。這是預期的嗎? – user2589692
我會認爲這並不意外。圖像是你期待的嗎? – MadProgrammer
是的,它只是與JPanel中顯示的圖像質量不同。 – user2589692