Java 如何在非组件类中使用 JFileChooser.showOpenDialog()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1974807/
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-08-13 01:58:48  来源:igfitidea点击:

How to use JFileChooser.showOpenDialog() in a non component class?

javajfilechooser

提问by Amokrane Chentir

I have a Java GUI project containing a JMenuBar and I just added a JToolBar. In the previous version, the events were implemented in the same class that extends the JMenuBar. I found it lame and moved the events in another class that extends AbstractAction. My aim is to centralize all the common events to make them react to different sources (JMenuBar, JToolBar etc.). But, I have a problem with the JFileChooser.showOpenDialog() method. This method takes as an argument the parent component for the dialog. If I do this :

我有一个包含 JMenuBar 的 Java GUI 项目,我刚刚添加了一个 JToolBar。在以前的版本中,事件是在扩展 JMenuBar 的同一个类中实现的。我发现它很蹩脚并将事件移动到另一个扩展 AbstractAction 的类中。我的目标是集中所有常见事件,使它们对不同的源(JMenuBar、JToolBar 等)做出反应。但是,我对 JFileChooser.showOpenDialog() 方法有问题。此方法将对话框的父组件作为参数。如果我这样做:

import java.awt.*;
import java.awt.event.*;
import java.io.File;

import javax.swing.*;
import javax.swing.event.*;

public class ActionUsuels extends AbstractAction 
{

    private String nameAction;

    /** Instance de MyFileChooser pour explorer les dossiers/fichiers*/
    private MyFileChooser fc;

    /** Instance d'OpenSave qui contient les algorithmes d'ouverture/sauvegarde*/
    private OpenSave openSave;

    ActionUsuels(String inName, String inPathIcon)
    {
        nameAction = inName;
        putValue(Action.NAME, inName);
        putValue(Action.SMALL_ICON, new ImageIcon(inPathIcon));
        putValue(Action.SHORT_DESCRIPTION, inName);

        this.fc = new MyFileChooser();
        this.openSave = new OpenSave(Panneau.getUnivers());

    }

    public void actionPerformed(ActionEvent e)
    {

        // Evénement nouveau projet
        if(nameAction == "OPEN_PROJECT")
        {

            fc.ContMode();
            fc.refresh();

            int returnVal = fc.showOpenDialog(ActionUsuels.this);

            if (returnVal == MyFileChooser.APPROVE_OPTION) 
            {
                File file = fc.getSelectedFile();

                    openSave.OpenCont(file);
            } 

        }
        static ActionUsuels actionInactive;
}

I get the following error :

我收到以下错误:

The method showOpenDialog(component) in the type JFileChooser is not applicable for the arguments (ActionUsuels).

JFileChooser 类型中的 showOpenDialog(component) 方法不适用于参数 (ActionUsuels)。

I guess this is normal because ActionUsuels doesn't extend any JComponent class. But how can I overpass that ? Is what I'm trying to do a bad practice ? My intention is to write the events once and be able to call them from any component.

我想这是正常的,因为 ActionUsuels 没有扩展任何 JComponent 类。但我怎么能超越呢?我正在尝试做的事情是不好的做法吗?我的目的是编写一次事件并能够从任何组件调用它们。

Just to make you understand what I'm doing, I have this in the Menu class:

为了让您了解我在做什么,我在 Menu 类中有这个:

 actions = new ActionUsuels[nameActions.length];

 for(int i = 0; i < nameActions.length; i++)
 {
        actions[i] = new ActionUsuels(nameActions[i], pathIcons[i]);
 }

file_menu.add(actions[0]);

file_menu.addSeparator();

file_menu.add(actions[1]);

Every item is associated to the name of the action, an icon and the suitable event !

每个项目都与动作名称、图标和合适的事件相关联!

Any idea ?

任何的想法 ?

Thanks !

谢谢 !

采纳答案by Carl Smotricz

Usually, the parent class passed to JDialogs is the main JFrame of the application. Among other things, this allows for the dialog to be centered over the app's window.

通常,传递给 JDialogs 的父类是应用程序的主 JFrame。除此之外,这允许对话框以应用程序窗口为中心。

Hopefully your action class will have access to the main frame and can pass a reference to it. One way to achieve this might be to pass the main frame as an argument to the ActionUsuelsconstructor.

希望您的动作类可以访问主框架并可以传递对它的引用。实现此目的的一种方法可能是将主框架作为参数传递给ActionUsuels构造函数。

Failing that, nullis also a valid parent specification. Given null, the dialog is centered on the screen but generally works OK anyway.

否则,null也是有效的父规范。鉴于null,对话框位于屏幕中央,但通常可以正常工作。

Bonne chance! :)

博纳机会!:)

回答by duffymo

This is a bad idea:

这是一个坏主意:

if(nameAction == "OPEN_PROJECT")

You need to use this instead:

您需要改用它:

if("OPEN_PROJECT".equals(nameAction))

The == operator only checks to see if two references are equal, not whether or not the Strings they point to are identical. That's what the equals method for String is written to do. It's the difference between "shallow" and "deep" equals.

== 运算符只检查两个引用是否相等,而不是它们指向的字符串是否相同。这就是编写 String 的 equals 方法的目的。这是“浅”和“深”等于之间的区别。

You can see it in action here:

你可以在这里看到它的实际效果:

String x = new String("foo");  // don't write code like this; just an example
String y = new String("foo");  // x and y are different reference values
System.out.println(x == y);    // prints "false"
System.out.println(x.equals(y)); // prints "true"