gpt4 book ai didi

java - 在哪里放置 JFileChooser 和 ActionEvent 处理程序

转载 作者:行者123 更新时间:2023-11-30 08:10:36 25 4
gpt4 key购买 nike

我在创建 JFileChooser 和关联的 ActionEvent 以在下面的代码中单击 fileItem1 时遇到了一些问题。

问题:JFileChooser 应该在哪里声明,ActionEvent 方法应该在哪里?

import javax.swing.*;

/*
* This class encapsulates the build of the menu bar and
* is called from DrawPanelMain to add to the JFrame
*/
public class SwingMenu extends JMenuBar {

/*
* Initializes the JMenuItems that will be added to the menu. This is
* necessary for access by the ActionEvent handler. Also includes
* FileChooser that will be used for ActionEvent of clicking on fileItem1.
*/
private JMenuItem fileItem1 = null;
private JMenuItem fileItem2 = null;
private JMenuItem editItem1 = null;
private JMenuItem helpItem1 = null;
private JMenuItem toolsItem1 = null;

/*
* These will be the main items on the menuBar
*/
public SwingMenu() {
initMenuBar();
}

private void initMenuBar() {
/*
* Initializes for the main items on the menuBar
*/
JMenu fileMenu = new JMenu("File");
JMenu editMenu = new JMenu("Edit");
JMenu toolsMenu = new JMenu("Tools");
JMenu helpMenu = new JMenu("Help");

/*
* Initializes for the components of the main items
*/
JMenuItem fileItem1 = new JMenuItem("Open");
JMenuItem fileItem2 = new JMenuItem("Save");
JMenuItem editItem1 = new JMenuItem("Edit Configuration");
JMenuItem helpItem1 = new JMenuItem("User Manual");
JMenuItem toolsItem1 = new JMenuItem("Fetch Configuration");

/*
* Each component is added to the assigned menu item
*/
fileMenu.add(fileItem1);
fileMenu.add(fileItem2);
editMenu.add(editItem1);
toolsMenu.add(toolsItem1);
helpMenu.add(helpItem1);

/*
* Menu items are added to the menuBar
*/
add(fileMenu);
add(editMenu);
add(toolsMenu);
add(helpMenu);
}
}

最佳答案

您必须向 fileItem1 添加一个 ActionListener,如下所示:

fileItem1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser chooser = new JFileChooser(null);
if (chooser.showOpenDialog() != JFileChooser.CANCEL_OPTION) {
// ...
}
}
});

关于java - 在哪里放置 JFileChooser 和 ActionEvent 处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31572867/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com