如何在Java Swing中单击执行多个操作

时间:2017-05-12 06:58:41

标签: java swing jbutton action

我对单buttons次点击执行其他button操作有疑问。三个按钮的一些示例代码:

JButton a = new JButton("a");
a.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Action of a is Here                   
  }
});

JButton b = new JButton("b");
b.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Action of b is Here                   
  }
});

那些应该聚集在一起,如:

JButton c = new JButton("c");
c.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // Action of c is Here
    // Action of a 
    // Action of b              
   }
});

在上面的示例中,我有三个按钮a,b,c,它们有自己的动作;但正如你所看到的,C还必须运行A和B的动作。有什么好方法可以解决这个问题?

3 个答案:

答案 0 :(得分:2)

1)方法

为每个操作使用方法并调用ActionListener.actionPerformed

中的操作
public void methodA(){}
public void methodB(){
    methodA();
}

2)动作实例

您可以创建自己的ActionListener类来执行操作

第一步:

class ActionA implements ActionListener{
     public void actionPerformed(ActionEvent e) {
          ...
    }
}

改进的行动

class ActionB extends ActionA{
    public void actionPerformed(ActionEvent e) {
           super.actionPerformed(e);  //Will call the first action
           ...
    }
}

这是有限的,因为你不能有多个扩展,但也是一个很好的解决方案

3)点击

最后但我不喜欢它,使用AbstractButton.doClick动态点击其他按钮。

4)添加多项操作

请注意,这些方法不是setActionListener,而是addActionListener,这意味着它将接受多个ActionListener。

所以定义创建两个实例

ActionListener listenerA = new ActionLisener ..
ActionListener listenerB = new ActionLisener ..

buttonA.addActionListener(listenerA);

buttonB.addActionListener(listenerB);

buttonC.addActionListener(listenerA);
buttonC.addActionListener(listenerB);

通过一个小测试,我注意到动作是按照B - >的顺序执行的。 A(可能不是一般性的)。

正如评论中所说,这应该是我们知道风险,这将是。如果某个操作因异常而失败,是否应执行下一个操作?默认情况下它不会,因为该过程不会隐藏异常。

我会将此解决方案限制为GUI管理,例如重置字段,禁用,......可以在不同的按钮中使用。

答案 1 :(得分:1)

无论你想在Button上做什么,点击a,你都可以输入一个方法并从你想要的任何地方调用它。

public void methodForA(){
   // do here what you want
}

您现在可以在希望它调用的方法中调用此方法。在您的情况下,从按钮单击A和按钮单击C

JButton a = new JButton("a");
a.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        methodForA();
    }
 });

// and also in your c-Button
JButton c = new JButton("c");
c.addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent e) {
          // Action of c is Here
          methodForA(); 
   }
});

答案 2 :(得分:1)

从actionListeners操作独立地为每个按钮创建3个方法执行方法并从actionPerfomed方法中调用它们:

self.webView.isOpaque = false;
self.webView.backgroundColor = UIColor.clear
相关问题