I am trying to create a UI in Java so that users can browse through images in a directory just by the use of JButtons. However, whenever I select a new image using JFileChooser, the images appends to each other. How can I delete the previous image and show that new one?
I am also trying to figure out how to go on to the next/previous image in the directory just by clicking on the next/previous button. How do I achieve that? Below is my code for my ButtonListener:
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == chooseBtn)
{
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
if (returnValue == JFileChooser.APPROVE_OPTION)
{
File selectedFile = fileChooser.getSelectedFile();
String fileName = selectedFile.toString();
image = new JLabel(new ImageIcon(fileName));
imgPanel.add(image);
frame.add(imgPanel, BorderLayout.WEST);
frame.repaint();
frame.validate();
}
}
else if(e.getSource() == nextBtn)
{
System.out.println("Next");
}
else if(e.getSource() == prevBtn)
{
System.out.println("Previous");
}
}
}
here is the problem.you create new labels and add to panel .that's why images append to panel
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String fileName = selectedFile.toString();
image = new JLabel(new ImageIcon(fileName));
imgPanel.add(image);
frame.add(imgPanel, BorderLayout.WEST);
frame.repaint();
frame.validate();
}
don't create lables each time.just onetime and change image icon when choose image
////don't repeate this code block
image = new JLabel();
imgPanel.add(image);
frame.add(imgPanel, BorderLayout.WEST);
frame.repaint();
frame.validate();
/////////
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
String fileName = selectedFile.toString();
image.setIcon(new ImageIcon(fileName ));
//repaint
frame.repaint();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.