我在 JMenu(退出)上编写代码,当单击它时,它会打开 JOption Pane 确认消息框,其中包含是/否选项,但当它弹出是/否按钮时,它第一次没有获得焦点,应该单击两次才能工作。
经过挖掘,我意识到 Jmenu(退出)选项在单击任何按钮后生成弹出窗口时不会失去焦点,下次它会获得焦点触发功能,所以我如何处理这种情况。
JMenu menu5 = new JMenu("Exit");
menu5.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
requestFocus();
callpopUp();
}
private void callpopUp() {
int choice=JOptionPane.YES_OPTION;
choice = JOptionPane.showConfirmDialog(null, "Are you sure to Exit Application",
"Confirmation", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
System.out.println("Exit Button Clicked.");
System.exit(0);
}
}
});
最佳答案
JMenu
不是为此目的而设计的,您应该使用 JMenuItem
首先查看 How to Use Menus和 How to Write an Action Listeners了解更多详情
类似...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
private JFrame frame;
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
performClose();
}
});
file.add(exit);
mb.add(file);
frame = new JFrame("Testing");
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
performClose();
}
});
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setJMenuBar(mb);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
protected void performClose() {
int choice = JOptionPane.YES_OPTION;
choice = JOptionPane.showConfirmDialog(null, "Are you sure to Exit Application",
"Confirmation", JOptionPane.YES_NO_OPTION);
if (choice == JOptionPane.YES_OPTION) {
System.out.println("Exit Button Clicked.");
frame.setVisible(false);
frame.dispose();
}
}
public class TestPane extends JPanel {
public TestPane() {
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
这将允许您使用文件->退出
菜单选项或只需通过[X]按钮关闭窗口,它将执行相同的操作,检查用户是否想要退出
关于java - J菜单 : while trigger event from Jmenu for open dialoge (confirmbox) Joption yes/No option click twice to work,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35625427/