我想用Java做一個小圖像處理。用戶應該能夠加載圖像並通過單擊按鈕爲圖像添加一些簡單的修改。 加載和顯示圖像是沒有問題的,但是當我嘗試從中創建二進制圖像時,repaint()方法使我在屏幕上顯示一個黑色圖像。 我認爲問題與repaint()方法有關。我已經使用了搜索功能和谷歌,但我仍然不知道我的代碼中有什麼問題。 這是我到目前爲止有:重畫BufferedImage
public class ImageProcessing extends JFrame implements ActionListener {
private JPanel imagePanel;
private JPanel buttonPanel;
private JButton binaryButton;
private JButton loadButton;
private BufferedImage image;
private final String WINDOW_TITLE = "Image Processing";
public ImageProcessing() {
createWindow();
}
private void createWindow() {
this.setTitle(WINDOW_TITLE);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500, 500);
imagePanel = new ImagePanel();
buttonPanel = new JPanel();
this.add(imagePanel, BorderLayout.CENTER);
loadButton = new JButton("Load image");
loadButton.addActionListener(this);
buttonPanel.add(loadButton);
this.add(buttonPanel, BorderLayout.SOUTH);
binaryButton = new JButton("binary");
binaryButton.addActionListener(this);
buttonPanel.add(binaryButton);
this.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == this.loadButton) {
String filePath = getImageFile();
if (filePath != null) {
try {
image = ImageIO.read(new File(filePath));
// imageBackup = image;
} catch (IOException e1) {
e1.printStackTrace();
}
this.repaint();
}
} else if (e.getSource() == this.binaryButton) {
image = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_BYTE_BINARY);
imagePanel = new ImagePanel();
this.repaint();
}
}
private String getImageFile() {
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
File file = null;
if (result == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile();
return file.getPath();
} else
return null;
}
class ImagePanel extends JPanel {
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
}
我希望你能幫助我解釋什麼,我做錯了。提前致謝。
按二進制按鈕後,ImagePanel的一個新實例被分配給變量'imagePanel'。但是,這個新的ImagePanel不會添加到JFrame中。舊的ImagePanel仍然添加到JPanel中。 – gogognome
'BufferedImage.TYPE_BYTE_BINARY'爲什麼二進制而不是'image.getType()'? –