在Java中以编程方式生成Actionevent

发布于 2024-11-26 04:43:25 字数 197 浏览 1 评论 0原文

我正在制作一个应用程序。在 java 中,其中有一个按钮,我在其中添加了一个动作监听器。它(按钮)生成的 ActionEvent 执行一些代码。现在我希望这段代码在应用程序运行时运行。启动并且无需按下按钮。我的意思是,我想生成 Actionevent(无需按下按钮),以便 ActionPerformed 包含的代码片段作为应用程序执行。开始。之后,只要我按下按钮,它就可以运行。

I'm making an App. in java , in which there is a Button to which I have added an actionlistener. The ActionEvent it(the button) generates executes some code. 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. start. After that, it may run whenever I press the button.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

定格我的天空 2024-12-03 04:43:25

您可以像任何其他 Java 对象一样通过使用构造函数来创建 ActionEvent。然后您可以使用 Component.processEvent(..) 将它们直接发送到组件。

但是,在这种情况下,我认为您最好将代码制作成一个单独的函数,该函数被调用:

  • 当按下按钮时由 ActionListener
  • 直接由您的应用程序启动代码(如果需要在事件处理线程上发生,可以使用 SwingUtilities.invokeLater() 或 SwingUtilities.invokeAndWait())

这样您就不会混淆表示逻辑与代码所做的任何业务逻辑......

You can create ActionEvents like any other Java Object by just using the constructor. And then you can send them directly to the component with 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
  • Directly by your application startup code (possibility using SwingUtilities.invokeLater() or SwingUtilities.invokeAndWait() if you need it to happen on the event-handling thread)

This way you don't mix up presentation logic with the business logic of whatever the code does....

划一舟意中人 2024-12-03 04:43:25

是的,它可以完成,但它实际上没有意义,因为您的目标不是按下按钮或调用 ActionListener 的代码,而是在按下按钮和程序启动时具有共同的行为。对我来说,实现此目的的最佳方法是拥有一个由 ActionListener 的 actionPerformed 方法和启动时的类调用的方法。

这是一个简单的例子。在下面的代码中,一个方法禁用按钮,将 JPanel 变为绿色,并启动一个计时器,该计时器会在 2 秒内启用该按钮并将 JPanel 的背景颜色重置为其默认值。导致此行为的方法在主类的构造函数和 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();
         }
      });
   }
}

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. 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.

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. The method that causes this behavior is called both in the main class's constructor and in the JButton's ActionListener's actionPerformed method:

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();
         }
      });
   }
}
放我走吧 2024-12-03 04:43:25

通常,按钮操作事件响应外部事件,以通知应用程序用户(或者更确切地说,某物或某人)与应用程序进行了交互。如果您的按钮执行一些您希望在应用程序启动时也执行的代码,为什么不将所有内容放在正确的位置呢?

示例:

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

使用类似的内容设置按钮

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

并在应用程序启动时运行类似的内容

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

并且,如果您需要执行的代码需要一段时间才能完成,您可能需要在中使用单独的线程>actionPerformed 按钮事件,这样您的应用程序 UI 就不会冻结。

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.

酷到爆炸 2024-12-03 04:43:25

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

Just Call JButton.doClick() it should fire the ActionEvent associated with the JButton.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文