我正在构建一个java程序,您应该可以在其中选择一个文件。对话框应弹出为JInternalFrame,不应该是自己的窗口。我的进步:
JFileChooser chooser = new JFileChooser();
JInternalFrame fr = new JInternalFrame("Öffnen", true, // resizable
false, // closable
true, // maximizable
true);// iconifiable);
fr.add(chooser);
fr.setSize(300, 600);
fr.setVisible(true);
JOS.mainWindow.jdpDesktop.add(fr);
chooser.setVisible(true);
chooser.setSize(300, 600);
chooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fr.setVisible(false);
JOS.mainWindow.jdpDesktop.remove(fr);
}
});
如果按下关闭按钮,它会关闭,但如果用户按下“打开”,我就不会收到活动。我可以使用任何ActionListener吗?怎么办呢? 谢谢! -Jakob
答案 0 :(得分:3)
JFileChooser
只是一个组件,它有一个方便的方法,允许你在对话框中显示它
您可以使用JOptionPane.showInternalOptionDialog
来显示JFileChooser
,它会像一个模态对话框,但包含在JInternalFrame
例如......
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JDesktopPane;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JDesktopPane dp = new JDesktopPane();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(dp);
frame.setSize(800, 800);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JFileChooser chooser = new JFileChooser();
chooser.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JInternalFrame parent = (JInternalFrame) SwingUtilities.getAncestorOfClass(JInternalFrame.class, chooser);
if (JFileChooser.CANCEL_SELECTION.equals(e.getActionCommand())) {
// Dialog was canceled
} else if (JFileChooser.APPROVE_SELECTION.equals(e.getActionCommand())) {
// Dialog was "approved"
}
parent.dispose();
}
});
JOptionPane.showInternalOptionDialog(dp, chooser, "Choose", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE, null, new Object[0], null);
}
});
}
}