我在绘制 JPanel 时遇到问题。这是我目前正在做的事情。我知道该图像是有效的,因为我已将其写入此类的文件并获得了我想要绘制的确切图像,但是当我尝试将其绘制到 JPanel 时,它似乎立即被删除了。我试过谷歌,但已经干了。有任何想法吗?
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import utilities.Log;
public class Signature extends JFrame {
/**
*
*/
private static final long serialVersionUID = 8908413895953622794L;
private JPanel contentPane;
private JPanel panel;
private BufferedImage image;
/**
* Create the frame.
*/
private Signature() {
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 631, 338);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblDateSigned = new JLabel("Date Signed:");
lblDateSigned.setBounds(48, 248, 91, 14);
contentPane.add(lblDateSigned);
JLabel lblDateGoesHere = new JLabel("date goes here");
lblDateGoesHere.setBounds(48, 262, 83, 14);
contentPane.add(lblDateGoesHere);
JButton btnClose = new JButton("Close");
btnClose.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
dispose();
}
});
btnClose.setBounds(521, 258, 89, 23);
contentPane.add(btnClose);
panel = new JPanel() {
private static final long serialVersionUID = -7148070953904995529L;
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
Graphics gc = this.getGraphics();
// gc.setColor(Color.WHITE);
gc.drawImage(image, 0, 0, null);
}
}
@Override
public void repaint() {
super.repaint();
if (image != null) {
Graphics gc = this.getGraphics();
// gc.setColor(Color.WHITE);
gc.drawImage(image, 0, 0, null);
// gc.dispose();
}
}
};
panel.setBounds(10, 11, 600, 200);
contentPane.add(panel);
}
public byte[] getImageByteArray() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] imageInBytes = null;
try {
ImageIO.write(image, "jpg", baos);
baos.flush();
imageInBytes = baos.toByteArray();
baos.close();
} catch (IOException e) {
Log.showMessage("Error processing signature: " + e.toString());
}
return imageInBytes;
}
public void setVisible() {
setVisible(true);
panel.repaint();
}
public Signature(BufferedImage image) {
this();
this.image = image;
}
}