java 将 JFileChooser 置于所有窗口之上

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5129294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:35:18  来源:igfitidea点击:

Bringing JFileChooser on top of all windows

javaswingopenfiledialogjfilechooser

提问by Carlos

I seem to have a problem with my very simple implementation of a file chooser dialogue that requires me to minimize Netbeans each time in order to get to it, and it gets pretty frustrating specially now with testing.

我对文件选择器对话框的非常简单的实现似乎有问题,它需要我每次都最小化 Netbeans 才能访问它,而且现在测试变得非常令人沮丧。

I have seen a few solutions online including SOyet none seem to do the trick, while some other seem very lengthy and complicated for my current level.

我在网上看到了一些解决方案,包括SO但似乎没有一个解决方案,而其他一些解决方案对于我目前的水平来说似乎非常冗长和复杂。

private void fileSearch() {

    JFileChooser fileSelect = new JFileChooser();
    int returnVal = fileSelect.showOpenDialog(null);
    String pathToFile;

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fileSelect.getSelectedFile();
        pathToFile = file.getAbsolutePath();
        try {
            P.binaryFileToHexString(pathToFile);
        } catch (Exception e) {
            System.out.print("Oops! there was an error there..." + e);
        }
        System.out.println("\nYou chose to open this file: " + file.getName());
    }
}

Some of my try's include using;

我的一些尝试包括使用;

.requestFocus();
.requestFocusInWindow();
.setVisible();

Is there a particular attribute/method I can set in order to solve the problem?

我可以设置特定的属性/方法来解决问题吗?

采纳答案by trashgod

The API for showOpenDialog()refers to showDialog(), which says, "If the parent is null, then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen."

的 APIshowOpenDialog()引用showDialog(),它说,“如果父是null,则对话框不依赖于可见窗口,并且它被放置在外观相关的位置,例如屏幕的中心。”

The example below positions the chooser in the center of the screen on my L&F. You might see how it compares to yours.

下面的示例将选择器定位在我的 L&F 屏幕中央。您可能会看到它与您的相比如何。

package gui;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;

/**
 * @see http://stackoverflow.com/questions/8507521
 * @see http://stackoverflow.com/questions/5129294
 */
public class ImageApp extends JPanel {

    private static final int MASK =
        Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
    private JFileChooser chooser = new JFileChooser();
    private Action openAction = new ImageOpenAction("Open");
    private Action clearAction = new ClearAction("Clear");
    private JPopupMenu popup = new JPopupMenu();
    private BufferedImage image;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new ImageApp().create();
            }
        });
    }

    public void create() {
        JFrame f = new JFrame();
        f.setTitle("Title");
        f.add(new JScrollPane(this), BorderLayout.CENTER);
        JMenuBar menuBar = new JMenuBar();
        JMenu menu = new JMenu("File");
        menu.setMnemonic('F');
        menu.add(new JMenuItem(openAction));
        menu.add(new JMenuItem(clearAction));
        menuBar.add(menu);
        f.setJMenuBar(menuBar);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setSize(new Dimension(640, 480));
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public ImageApp() {
        this.setComponentPopupMenu(popup);
        popup.add("Popup Menu");
        popup.add(new JMenuItem(openAction));
        popup.add(new JMenuItem(clearAction));
    }

    @Override
    public Dimension getPreferredSize() {
        if (image == null) {
            return new Dimension();
        } else {
            return new Dimension(image.getWidth(), image.getHeight());
        }
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }

    private class ClearAction extends AbstractAction {

        public ClearAction(String name) {
            super(name);
            this.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_C);
            this.putValue(Action.ACCELERATOR_KEY,
                KeyStroke.getKeyStroke(KeyEvent.VK_C, MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            image = null;
            revalidate();
            repaint();
        }
    }

    private class ImageOpenAction extends AbstractAction {

        public ImageOpenAction(String name) {
            super(name);
            this.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_O);
            this.putValue(Action.ACCELERATOR_KEY,
                KeyStroke.getKeyStroke(KeyEvent.VK_O, MASK));
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            int returnVal = chooser.showOpenDialog(chooser);
            if (returnVal == JFileChooser.APPROVE_OPTION) {
                File f = chooser.getSelectedFile();
                try {
                    image = ImageIO.read(f);
                    revalidate();
                    repaint();
                } catch (IOException ex) {
                    ex.printStackTrace(System.err);
                }
            }
        }
    }
}

回答by Yanick Rochon

I'm not sure what your problem actually is (it's probably your Netbeans.... who knows), but have you tried overriding the createDialogmethod?

我不确定您的问题究竟是什么(可能是您的 Netbeans .... 谁知道),但是您是否尝试过覆盖该createDialog方法?

Example:

例子:

JFileChooser fc = new JFileChooser() {
   @Override
   protected JDialog createDialog(Component parent) throws HeadlessException {
       // intercept the dialog created by JFileChooser
       JDialog dialog = super.createDialog(parent);
       dialog.setModal(true);  // set modality (or setModalityType)
       return dialog;
   }
};

This is merely a hack solution, you should not need to do that ordinarily.

这只是一个 hack 解决方案,您通常不需要这样做。

回答by Trasvi

fileSelect.showOpenDialog(this)

Of course, thismust be a Component of some sort (the JFrame or JPanel of your main interface). All dialogs need to have a parent component if you wish them to come to the front.

当然,this必须是某种类型的组件(主界面的 JFrame 或 JPanel)。如果您希望它们出现在最前面,所有对话框都需要有一个父组件。