質問

I am trying to code a small text editor and I was building the GUI.

I added a JMenu and added a JMenuItem to it. I gave the menu item the value of "open". The reason is because I want that when "open" is pressed a JFileChooser appears on the screen

Here is what I have:

public void mousePressed(MouseEvent me) {
    JFileChooser fs = new JFileChooser();
}

This method is in a class called listener which implements MouseListener. This is the step that I'm stuck at.

getContentPane() 

..does not work:

Is it good code practice the way I'm approaching this? Is there a better way? If not how do I go around doing this?

役に立ちましたか?

解決

While in general your approach could work, you might want to look into the Swing concept of Actions. JMenuItem has direct support for actions, you would not need a MouseListener (which is a bit to low-level for your usecase).

Try to look at the examples, it might look a little overwhelming at first, but in the end it is a nice and clean encapsulation of what you want. And it is reusable, meaning you could use the action on a different menu (maybe the context menu) as well.

And for your code, you are missing the call to fs.showOpenDialog(component).

他のヒント

Firstly, don't use a MouseListener for JMenuItem or JButton, this is not the appropriate means for managing these components, instead, use an ActionListener.

The main reason for this is that your menu item could be triggered via a keyboard shortcut or programmatically.

Secondly "does not work" is not information about what you problem is, but I assume it's because the method does not exist.

A simply solution would be to check the source the event to determine if it's a Component or not and use it instead, or null if the source of the event is not a Component...

public void actionPerformed(ActionEvent evt) {
    Object source = evt.getSource();
    Component parent = null;
    if (source instanceof Component) {
        parent = (Component)source;
    }

    // Show file chooser dialog...
}

Take a look at How to use menus for more details

You may also find How to use actions of some interest

Have a look at the Javadoc on the JFileChooser class. It has an example of how to open it.

The following code pops up a file chooser for the user's home directory that sees only .jpg and .gif images:

JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
    "JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
   System.out.println("You chose to open this file: " +
        chooser.getSelectedFile().getName());
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top