java - 将多个按钮与 ActionEvent 结合使用

标签 java actionevent

我已经在这方面得到了一些帮助,但是现在当我按下按钮时,没有任何反应。我希望当您单击按钮时显示文本。如果是布局问题,我应该使用哪一个? FlowLayout 不适用于此程序,因为它会扭曲按钮。

import java.awt.*;
import java.awt.event.*;

public class Option3 extends Frame implements WindowListener,ActionListener
{
    Label l1;
    Label l2;
    Label l3;
    Button b1;
    Button b2;
    Button b3;
    public static void main(String[] args)
    {
        Option3 o3 = new Option3("Press a Button");
        o3.setSize(700,350);
        o3.setVisible(true);
    }
    public Option3(String option3)
    {
        super(option3);
        setLayout(null);
        addWindowListener(this);

        Label l1 = new Label();
        l1 = new Label();
        l1.setBounds(50,150,125,50);
        l1.setVisible(true);
        add(l1);

        Label l2 = new Label();
        l2 = new Label();
        l2.setBounds(275,150,125,50);
        l2.setVisible(true);
        add(l2);

        Label l3 = new Label();
        l3 = new Label();
        l3.setBounds(500,150,125,50);
        l3.setVisible(true);
        add(l3);

        Button b1 = new Button();
        b1 = new Button();
        b1.addActionListener(this);
        b1.setBounds(25,100,175,175);
        add(b1);

        Button b2 = new Button();
        b2 = new Button();
        addWindowListener(this);
        b2.addActionListener(this);
        b2.setBounds(250,100,175,175);
        add(b2);

        Button b3 = new Button();
        b3 = new Button();
        b3.addActionListener(this);
        b3.setBounds(475,100,175,175);
        add(b3);
    }
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == b1)
        {
            l1.setText("You pressed button 1.");
        }
        else if (e.getSource() == b2)
        {
            l2.setText("You pressed button 2.");
        }
        else if (e.getSource() == b3)
        {
            l3.setText("You pressed button 3.");
        }
    }
    public void windowClosing(WindowEvent e)
    {
        dispose();
        System.exit(0);
    }
    public void windowActivated(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowOpened(WindowEvent e) {}
}

最佳答案

public void actionPerformed(ActionEvent e) {
    if (e.getSource() == b1) {
        // do stuff
    } else if (e.getSource() == b2) {
        // do other stuff
    }
}

e.getSource() 返回触发事件的对象引用。

关于java - 将多个按钮与 ActionEvent 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23662962/

相关文章:

java - Smooch.io postmessage api 在 header 参数中传递 jwt

java - 目录 java Flying Saucer ?

java - 我如何使用 JUnit 测试 void actionEvent 中的信息

java - 从多个 JLabel 获取鼠标点击输入的较小程序

java - 使用静态作为对象时出现空指针异常?

java - 为什么pdf只包含一个字段大约500Kb

Java回溯问题

java - 如何根据 JavaFX 中的组合框选择对按钮执行多个操作

java - 弹跳球。球有滞后。 repaint() 太慢

java - 为 JavaFX 按钮数组中的每个按钮分配一个操作