我正在尝试创建一个可以预览用户从自定义JFileChooser中选择的图像的功能。以下是测试框架和自定义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);
}
}
}
该代码适用于该应用程序。问题是我希望使自定义的JFileChooser可以重用于所有其他框架/类。我想让我的自定义JFileChooser足够聪明,以便使用所选图像更新任何调用者类的JLabel(例如lblPicPreview),而不是从FileChooser类本身调用Test.java的lblPicPreview.setIcon()。这样做是为了让我可以将FileChooser用于其他帧/类实例。
一个问题是Test.java的lblPicPreview是一个实例变量,所以我不能直接在FileChooser类中使用它。
感谢所有帮助。先感谢您。
答案 0 :(得分:0)
只需添加一个方法来指定要设置的标签:
public class FileChooser extends JPanel implements ActionListener {
protectedJLabel activeLabel;
public void setActivelabel( JLabel label ) {
activeLabel = label;
}
}