当前位置: 代码迷 >> J2SE >> 怎的给JMenuItem设置事件,使之点击生成对话框提示
  详细解决方案

怎的给JMenuItem设置事件,使之点击生成对话框提示

热度:70   发布时间:2016-04-24 00:31:23.0
怎样给JMenuItem设置事件,使之点击生成对话框提示
界面已经做好了
import javax.swing.JFrame;
import javax.swing.JSplitPane;
import java.awt.BorderLayout;

import javax.swing.JDialog;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JSeparator;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MainFrame {

private JFrame frmSql;

/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame window = new MainFrame();
window.frmSql.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

/**
* Create the application.
*/
public MainFrame() {
initialize();
}

/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmSql = new JFrame();
frmSql.setTitle("SQL客户端管理器");
frmSql.setBounds(100, 100, 450, 300);
frmSql.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JSplitPane splitPane = new JSplitPane();
frmSql.getContentPane().add(splitPane, BorderLayout.CENTER);

JMenuBar menuBar = new JMenuBar();
frmSql.setJMenuBar(menuBar);

JMenu mnFileMenu = new JMenu("文件(F)");
mnFileMenu.setMnemonic('F');//设置快捷键:ALT+f
menuBar.add(mnFileMenu);

JMenuItem mntmConnectionMenuItem = new JMenuItem("新建连接(c)");
mntmConnectionMenuItem.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {

}
});
mntmConnectionMenuItem.setMnemonic('C');
mnFileMenu.add(mntmConnectionMenuItem);

JMenuItem mntmCreateTableMenuItem = new JMenuItem("新建表(T)");
mntmCreateTableMenuItem.setMnemonic('T');
mnFileMenu.add(mntmCreateTableMenuItem);

JMenuItem mntmExcutesSQLMenuItem = new JMenuItem("执行SQL(S)");
mntmExcutesSQLMenuItem.setMnemonic('S');
mnFileMenu.add(mntmExcutesSQLMenuItem);

JSeparator separator=new JSeparator();
mnFileMenu.add(separator);

JMenuItem mntmExitMenuItem = new JMenuItem("退出(X)");
mntmExitMenuItem.setMnemonic('X');
mnFileMenu.add(mntmExitMenuItem);

JMenu mnHelpMenu = new JMenu("帮助(H)");
mnHelpMenu.setMnemonic('H');
menuBar.add(mnHelpMenu);


JMenuItem mntmAboutMenuItem = new JMenuItem("关于...(B)");
mntmAboutMenuItem.setMnemonic('B');
mnHelpMenu.add(mntmAboutMenuItem);
}

}
我想做的效果是单我点击文件菜单下的新建连接时弹出个对话框 应该怎么写
mntmConnectionMenuItem.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JDialog dlg=new JDialog();
dlg.setTitle("OK");
dlg.setVisible(true);
}
});这样写出来没有反应额;

------解决方案--------------------
mntmConnectionMenuItem.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent e) {
JDialog jd = new JDialog();
jd.setVisible(true);// TODO Auto-generated method stub
jd.setLocationRelativeTo(frmSql);
}
});