I am trying to create a function which can preview the image that the user selected from a customized JFileChooser. The following are the code snippets from the test frame and the customized JFileChooser.
Test.java
public class Test extends JFrame {
private JPanel contentPane;
private FileChooser file;
private static JLabel lblPicPreview;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test frame = new Test();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Test() {
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("main menu");
setBounds(100, 100, 960, 540);
setLocationRelativeTo(null);
contentPane = new JPanel();
setContentPane(contentPane);
contentPane.setLayout(new FlowLayout(FlowLayout.LEADING));
lblPicPreview = new JLabel();
lblPicPreview.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
file.setPic();
}
});
lblPicPreview.setBorder(new TitledBorder(new LineBorder(new Color(0, 0, 0)), "Preview", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
lblPicPreview.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
lblPicPreview.setToolTipText("Click to change profile picture");
file= new FileChooser();
contentPane.add(file);
contentPane.add(lblPicPreview);
}
// Method to update image
public static void updatePicture(ImageIcon icon){
lblPicPreview.setIcon(icon);
}
public void refresh(){
repaint();
revalidate();
}
}
FileChooser.java
public class FileChooser extends JPanel implements ActionListener {
/**
* Constructor FileChooser to place the UI for customized JFileChooser
*/
// actionPerformed for the "select" button in the custom UI
public void actionPerformed(ActionEvent e){
returnVal= fileChooser.showOpenDialog(button);
if(returnVal==JFileChooser.APPROVE_OPTION){
file= fileChooser.getSelectedFile();
fileLabel.setText(file.getAbsolutePath());
img= new ImageIcon(file.getAbsolutePath());
/** caller object to chg icon when user chooses new image
* i want to make this to update the image from its caller
* something like this
* {sourceLabel}.setIcon(img);
*/
Test.updatePicture(img);
}
}
}
The code works fine for the application. The problem is that i wish to make the customized JFileChooser to be reusable for all other frames/ classes. I want to make my custom JFileChooser smart enough to get any caller's class's JLabel (eg. lblPicPreview) to be updated with the chosen image instead of calling Test.java's lblPicPreview.setIcon() from the FileChooser class itself. This is done so that I can use FileChooser for other instances of frames/class.
One problem is that Test.java's lblPicPreview is an instance variable, so i cannot directly use it from FileChooser class.
All helps are appreciated. Thank you in advance.