java swing手动启动一个事件,无需用户输入

huangapple go评论77阅读模式
英文:

java swing manual start an event without user input

问题

我想在不点击所有按钮界面的情况下触发一个事件。
例如,当我点击button_0时,它将打印红色,并在同一时间执行button_1和button_2上的动作,因此也会同时打印蓝色和绿色。

这三个操作必须分开进行,因此合并这两个操作的解决方案不适用于我的情况,我只是制作了一个小指南示例。

public void actionPerformed(ActionEvent e) 
{
    if(e.getSource()==button_0)
    {
       System.out.println("红色");
    }
    else if(e.getSource()==button_1)
    {   
        System.out.println("蓝色");
    }
    else if(e.getSource()==button_2)
    {
        System.out.println("绿色");
    }
}
英文:

I want to activate an event without clicking all the button interface.
ex. when i click button_0, it will print red, and at the same time it will perform action on button_1 and button_2, hence will also print blue and green at the same time.

Those three operation must be separate, solution as merging both action is not applicable on my case, I only made the example as a small guide.

public void actionPerformed(ActionEvent e) 
{
    if(e.getSource()==button_0)
    {
       System.out.println("red");
    }
    else if(e.getSource()==button_1)
    {   
        System.out.println("blue");
    }
    else if(e.getSource()==button_2)
    {
        System.out.println("green");
    }
}

答案1

得分: 0

这是一种不太规范的做法:

public void actionPerformed(ActionEvent e) 
{
    if(e.getSource()==button_0)
    {
       System.out.println("红色");
       button_1.doClick();
       button_2.doClick();
    }
    else if(e.getSource()==button_1)
    {   
        System.out.println("蓝色");
    }
    else if(e.getSource()==button_2)
    {
        System.println("绿色");
    }
}
英文:

Here's a dirty way to do it:

public void actionPerformed(ActionEvent e) 
{
    if(e.getSource()==button_0)
    {
       System.out.println("red");
       button_1.doClick();
       button_2.doClick();
    }
    else if(e.getSource()==button_1)
    {   
        System.out.println("blue");
    }
    else if(e.getSource()==button_2)
    {
        System.out.println("green");
    }
}

huangapple
  • 本文由 发表于 2020年8月13日 22:45:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/63397605.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定