简体   繁体   English

以编程方式在Java中生成Actionevent

[英]Programmatically Generating Actionevent in Java

I'm making an App. 我正在制作一个应用程序。 in java , in which there is a Button to which I have added an actionlistener. 在java中,我有一个Button,我已经添加了一个actionlistener。 The ActionEvent it(the button) generates executes some code. 它生成的ActionEvent(按钮)执行一些代码。 Now I want this piece of code to run whenever the app. 现在我希望这段代码能够在应用程序运行时运行。 starts and without pressing the button. 开始而不按下按钮。 I mean, I want to generate the Actionevent (without pressing the button) so that the piece of code the ActionPerformed contains gets executed as the app. 我的意思是,我想生成Actionevent(不按下按钮),以便ActionPerformed包含的代码段作为app执行。 start. 开始。 After that, it may run whenever I press the button. 之后,只要按下按钮,它就可以运行。

You can create ActionEvents like any other Java Object by just using the constructor. 只需使用构造函数,就可以像创建任何其他Java对象一样创建ActionEvent。 And then you can send them directly to the component with Component.processEvent(..) 然后你可以使用Component.processEvent(..)将它们直接发送到组件

However, in this case I think you are better making your code into a separate function which is called both: 但是,在这种情况下,我认为你最好将你的代码变成一个单独的函数,它被称为:

  • By the ActionListener when the button is pressed 按下按钮时按ActionListener
  • Directly by your application startup code (possibility using SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() if you need it to happen on the event-handling thread) 直接由您的应用程序启动代码(如果您需要在事件处理线程上发生,可能使用SwingUtilities.invokeLater()或SwingUtilities.invokeAndWait())

This way you don't mix up presentation logic with the business logic of whatever the code does.... 这样你就不会将表示逻辑与代码所做的业务逻辑混淆在一起....

Yes it can be done, but it doesn't really make sense, since your goal isn't to press a button or to call an ActionListener's code, but rather to have a common behavior on button press and on program start up. 是的,它可以完成,但它确实没有意义,因为你的目标不是按下按钮或调用ActionListener的代码,而是按下按钮和程序启动时有一个共同的行为。 To me the best way to achieve this is to have a method that is called by both the actionPerformed method of the ActionListener and by the class at start up. 对我来说,实现这一目标的最佳方法是使用一个方法,该方法由ActionListener的actionPerformed方法和启动时的类调用。

Here's a simple example. 这是一个简单的例子。 In the code below, a method disables a button, turns the JPanel green, and starts a Timer that in 2 seconds enables the button and resets the JPanel's background color to its default. 在下面的代码中,一个方法禁用一个按钮,将JPanel变为绿色,并启动一个Timer,在2秒内启用该按钮并将JPanel的背景颜色重置为其默认值。 The method that causes this behavior is called both in the main class's constructor and in the JButton's ActionListener's actionPerformed method: 导致此行为的方法在main类的构造函数和JButton的ActionListener的actionPerformed方法中调用:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ActionOnStartUp extends JPanel {
   private static final int PANEL_W = 400;
   private static final int PANEL_H = 300;
   private static final int TIMER_DELAY = 2000;
   private JButton turnGreenBtn = new JButton("Turn Panel Green for 2 seconds");;

   public ActionOnStartUp() {
      turnPanelGreen();

      turnGreenBtn.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
            turnPanelGreen();
         }
      });
      add(turnGreenBtn);
   }

   public void turnPanelGreen() {
      setBackground(Color.green);
      turnGreenBtn.setEnabled(false);
      new Timer(TIMER_DELAY, new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            setBackground(null);
            turnGreenBtn.setEnabled(true);
            ((Timer) ae.getSource()).stop(); // stop the Timer
         }
      }).start();
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PANEL_W, PANEL_H);
   }

   public static void createAndShowGui() {
      JFrame frame = new JFrame("Foo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new ActionOnStartUp());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

只需调用JButton.doClick()它就应该触发与JButton关联的ActionEvent。

Usually, the button action event responds to an external event, to notify the application that the user (or rather something or someone) interacted with the application. 通常,按钮动作事件响应外部事件,以通知应用程序用户(或者更确切地说是某人或某人)与应用程序交互。 If your button executes some code that you want to also execute at application start, why not just place everything at it's proper place? 如果你的按钮执行了一些你想在应用程序启动时执行的代码,为什么不把它放在适当的位置呢?

Example: 例:

public class SomeSharedObject {
    public void executeSomeCode() { /*....*/ }
}

Set the button with something like 用类似的东西设置按钮

public void setButtonAction(final SOmeSharedObject obj) {
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) { 
            obj.executeSomeCode();
        }
    });
}

And run at application start with something like 并在应用程序启动时运行类似的东西

public void initApplication(SomeSharedObject obj) {
    obj.executeSomeCode();     
}

And, if the code you need to execute takes a while to complete, you might want to use a separate thread inside your actionPerformed button event so your application UI does not freeze up. 而且,如果您需要执行的代码需要一段时间才能完成,您可能希望在actionPerformed按钮事件中使用单独的线程,这样您的应用程序UI就不会冻结。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM