【问题标题】:How to Listen two separate buttons in Java AWT?如何在 Java AWT 中监听两个单独的按钮?
【发布时间】:2021-04-19 10:45:51
【问题描述】:
import java.awt.*;  
import java.awt.event.*;  
//1st step  
public class ActionListenerExample implements ActionListener{  
public static void main(String[] args) {  
    Frame f=new Frame("ActionListener Example");  
    final TextField tf=new TextField();  
    tf.setBounds(50,50, 150,20);  
    Button b=new Button("Click Here");  
    b.setBounds(50,100,60,30);  
    //2nd step  
    b.addActionListener(this);  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
//3rd step  
public void actionPerformed(ActionEvent e){  
            tf.setText("Welcome to Javatpoint.");  
}  
}  

在上面我想添加另一个按钮并添加 ActionListener 并定义 actionPerformed 方法,但该方法需要在终端中打印 hello。

我会为此做些什么?

【问题讨论】:

    标签: java button awt actionlistener


    【解决方案1】:

    也许这会很有用。
    主要是需要为每个按钮添加单独的侦听器。(也可以使用相同的侦听器,但需要过滤来自事件的来源,以便为每个按钮执行不同的操作)
    它还针对关闭事件进行了更新.但最好尝试查看JFrame(Swing),因为Frame 非常古老。反正主要原则是一样的。

    import java.awt.Button;
    import java.awt.Frame;
    import java.awt.TextField;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    public class ALTest {
    
        public static void main(String[] args) {
    
            Frame f = new Frame("ActionListener Example");
            final TextField tf = new TextField();
            tf.setBounds(50, 50, 150, 20);
            Button b = new Button("Button_1");
            b.setBounds(50, 100, 60, 30);
            Button b2 = new Button("Button_2");
            b2.setBounds(150, 100, 60, 30);
    
            f.add(b);
            f.add(b2);
    
            ActionListener al_1 = new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    tf.setText("B1 : " + e.getActionCommand());
    
                }
            };
    
            ActionListener al_2 = new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                    tf.setText("B2 : " + e.getActionCommand());
    
                }
            };
            b.addActionListener(al_1);
            b2.addActionListener(al_2);
            f.add(tf);
            f.setSize(400, 400);
            f.setLayout(null);
            f.setVisible(true);
            // close frame
            f.addWindowListener(new java.awt.event.WindowAdapter() {
                public void windowClosing(java.awt.event.WindowEvent e) {
                    System.exit(0);
                }
            });
        }
    
    }
    

    输出:

    对于控制台输出,只需将al_2 更新为System.out... 而不是tf TextField

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-24
      • 2012-02-07
      • 1970-01-01
      • 2018-12-30
      • 2021-09-27
      • 1970-01-01
      相关资源
      最近更新 更多