简体   繁体   English

使用JButton ActionListener在同一个包中运行不同的类

[英]Using JButton ActionListener to run different class in same package

I'm having an issue as I'm relatively new to GUI . 我遇到了一个问题因为我对GUI比较新。

Basically to put everyone in the picture, I have a package which consists of: 基本上把每个人都放在图片中,我有一个包括以下内容的包:

  • my MainClass (Includes the GUI) 我的MainClass (包括GUI)
  • A seperate Class (Don't want it to run unless button is clicked) 单独的类(除非单击按钮,否则不要运行它)
  • Another seperate class which I don't want to run unless it's specific button is clicked. 另一个单独的类,除非点击特定按钮,否则我不想运行。

So my MainClass GUI is basically the controller. 所以我的MainClass GUI基本上就是控制器。

However, I honestly have no clue how to go about it. 但是,老实说,我不知道如何去做。 Was told to have to create a constructor and use getters/setters? 被告知必须创建一个构造函数并使用getter / setter? However I still don't understand how to call that specific class whilst leaving the other off "Turned off" . 但是,我仍然不明白如何打电话给那个特定的课程,而另一个关闭“关闭”

Thanks. 谢谢。

Well, there are quite a few ways to do this... Either you create anonymous listeners for each button, and then, depending on what you want to do, trigger methods in other classes or the like; 好吧,有很多方法可以做到这一点......要么你为每个按钮创建匿名监听器,然后根据你想要做什么,触发其他类中的方法等;

JButton b1 = new JButton();
b1.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e)
    {
        //Do something!
        OtherClass other = new OtherClass();
        other.myMethod();
    }
});

JButton b2 = new JButton();
b2.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e)
    {
        //Do something else!
        ...
    }
});

Alternatively, you use the command string and associate a unique command (made final, preferably) which you compare with when receiving a actionPerformed in a common listener implementation; 或者,您使用命令字符串并关联您在公共侦听器实现中接收actionPerformed时所比较的唯一命令(最终,最终);

//In your class, somewhere...
public final static String CMD_PRESSED_B1 = "CMD_PRESSED_B1";
public final static String CMD_PRESSED_B2 = "CMD_PRESSED_B2";

//Create buttons
JButton b1 = new JButton();
JButton b2 = new JButton();

//Assign listeners, in this case "this", but it could be any instance implementing ActionListener, since the CMDs above are declared public static
b1.addActionListener(this);
b2.addActionListener(this);

//Assign the unique commands...
b1.setActionCommand(CMD_PRESSED_B1);
b2.setActionCommand(CMD_PRESSED_B2);

And then, in your listener implementation; 然后,在你的监听器实现中;

public void actionPerformed(ActionEvent e)
{
    if (e.getActionCommand().equals(CMD_PRESSED_B1)
    {
        //Do something!
        OtherClass other = new OtherClass();
        other.myMethod();
    }

    else if (e.getActionCommand().equals(CMD_PRESSED_B2)
    {
        //Do something else!
        ...
    }
}

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

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