[英]Using JFileChooser to reselect files in directory
我正在嘗試使用Java創建UI,以便用戶僅使用JButton即可瀏覽目錄中的圖像。 但是,每當我使用JFileChooser選擇新圖像時,圖像便會彼此追加。 如何刪除上一張圖像並顯示新圖像?
我還試圖通過單擊“下一個/上一個”按鈕來找出如何轉到目錄中的下一個/上一個圖像。 我該如何實現? 以下是我的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");
}
}
}
這是問題所在。您創建了新標簽並添加到面板上。這就是為什么圖像會附加到面板上的原因
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 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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.