【问题标题】:Is it possible to call a different class when a Button is clicked单击按钮时是否可以调用不同的类
【发布时间】:2015-04-29 20:15:00
【问题描述】:

所以我有一个名为“start”的带有JButton 的窗口。我想要发生的是,当单击该按钮时,它将运行我已经创建的单独类。这可能吗?如果可以,我将如何去做? 感谢您的所有帮助

这是我目前所拥有的

JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(//not sure what goes here, i would like to call other class here)

顺便说一句,被调用的另一个类正在下降,以防万一

【问题讨论】:

  • 你能发布你到目前为止的内容吗?
  • 我刚刚做了,还有很多,但我认为这才是最重要的
  • This 是您所需要的一切。
  • 基本上是的,但是您的“其他”类需要实现ActionListener,或者您需要提供一个能够调用您的“其他”类的ActionListener。考虑使用ActionHow to Use Actions

标签: java swing class jbutton


【解决方案1】:

你(你的班级)可以实现 ActionListener 来处理按钮被点击的时候。

public class YourClass implements ActionListener {

  public YourClass() {
    JButton start = new JButton ("Play");
    frame.add(start);
    start.addActionListener(this);
  }

  public void actionPerformed(ActionEvent arg0) {
    // Call other class
  }

}

【讨论】:

  • 错字:构造函数后面的大括号应该是花括号。
【解决方案2】:

有很多方法可以做到这一点。如果你想使用另一个已经实现 ActionListener 的类,那么你绝对可以创建该类的对象,然后插入是这样的:

//Another class that you're already created is named MyActionListener
// and implements ActionListener for this example

MyActionListener mal = new MyActionListener();
JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(mal);

但是,这可能没有任何意义,因为您需要引用作为当前类实例成员的变量。在这种情况下,您希望当前类像这样实现ActionListener

class MyClass implements ActionListener {

    public MyClass() {
        JButton start = new JButton ("Play");
        frame.add(start);
        start.addActionListener(this);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        //do whatever you need to do here
    }
}

this 关键字表示您指的是该类的当前实例。因此它将使用您在此类中实现的actionPerformed 方法。您可以在 actionPerformed 方法中实例化其他类的对象,然后像往常一样对该对象进行任何调用,或者如果它是此类的成员,则直接调用该成员的函数。此外,如果您在第二个类上引用静态方法,您也可以直接在 actionPerformed 方法中调用它们。

还有另一种选择,即使用匿名内部类。如果您希望在单个类中拥有多个 actionPerformed 方法,这些方法不在不同组件的事件处理程序的注册之间共享(即,仅将其用于单个启动按钮),通常使用此方法。以下是如何使用该方法:

JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        //do whatever you want here for whenever start is clicked
    }
 });

与其他选项一样,您也可以在此处实例化 actionPerformed 方法中的第二个类或从另一个类调用静态方法。但是,如果您计划调用位于外部类成员变量上的方法(在这种情况下为MyClass),那么您需要使用此语法this.MyOtherClass.method()。原因是在这种情况下,this 关键字为您提供了访问匿名内部类内部的外部类的权限。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2015-10-01
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2016-08-06
    • 2014-07-02
    相关资源
    最近更新 更多