如何通过点击另一个按钮执行按钮java?

问题描述 投票:1回答:4
menuBar = new JMenuBar();
// File Menu
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// File->New
JMenuItem newMenuItem = new JMenuItem("New");
frame.setJMenuBar(menuBar);
newMenuItem.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent arg0) {
        btnExample.setText("Clicked");
        btnExample.doClick();
    //---------->SOME HOW TO EXECUTE btnExample<---------//
}
});
fileMenu.add(newMenuItem);

final JButton btnExample = new JButton("SD");
frame.getContentPane().add(btnExample, "cell 4 0,growx,aligny top");
btnExample.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseClicked(MouseEvent arg0) {
    spinnerForVar.setValue(4);//default value for spinner
    spinnerForFunc.setValue(4);//default value for spinner
    ...             
  }
});

你好!请问有谁可以帮助我?我希望有人能帮助我。问题是这样的:我有一个菜单项 "New",有按钮btnExample。我想如下。当我点击 "File->New "时,它会执行btnExample。我的代码只能改变按钮的标题和显示点击的视觉效果。但我如何才能真正执行它呢?

java click mouse execute jbutton
4个回答
8
投票

我只有一个建议--不要这么做。不要用这种方式绑定GUI组件。

如果你想让两个组件执行相同的操作,只需将这个操作打包在一个方法中,然后从两个组件中调用该方法。

另外,使用ActionListener--你确定用户是要用鼠标而不是键盘来按吗,如果你给那些按钮组件添加快捷键呢?


2
投票
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    //My button to click on it

    jButton1ActionPerformed(evt);//this is the call for the other button to execut it
}

1
投票

你不应该使用MouseListener。

你应该使用Action。然后你可以将Action添加到JButton和JMemuItem中。

请阅读Swing教程中关于 如何使用行动.


0
投票

太神奇了,我在你的代码中找到了我的解决方案!

        btnExample.doClick();

这为我做了工作

© www.soinside.com 2019 - 2024. All rights reserved.