java - 将 ActionListener 添加到按钮

标签 java actionlistener

我有一个使用 ShowLayout 的带有 6 个按钮的应用程序。当按下按钮时,按钮编号会显示在控制台中。

我的代码有什么问题吗?我无法让它工作!按钮显示,但无法让 actionListener 工作并显示数字。谢谢!

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;


class ShowFlowlayout extends JFrame implements ActionListener{

JPanel p1 = new JPanel();
JButton one = new JButton("One");
JButton two = new JButton("Two");
JButton three = new JButton("Three");
JPanel p2 = new JPanel();
JButton four = new JButton("Four");
JButton five = new JButton("Five");
JButton six = new JButton("Six");


public ShowFlowlayout() {

    this.setLayout (new FlowLayout(FlowLayout.LEFT, 10, 20));

    p1.add(one);
    p1.add(two);
    p1.add(three);
    p2.add(four);
    p2.add(five);
    p2.add(six);

    add(p1, FlowLayout.LEFT);
    add(p2, FlowLayout.CENTER);

}

 public void actionPerformed(ActionEvent e) {
        if(e.getSource() == one)
        {
            System.out.println("Button One");
        }
        if(e.getSource() == two)
        {
            System.out.println("Button Two");
        }
        if(e.getSource() == three)
        {
            System.out.println("Button Three");
        }
        if(e.getSource() == four)
        {
            System.out.println("Button Four");
        }
        if(e.getSource() == five)
        {
            System.out.println("Button Five");
        }
        if(e.getSource() == six)
        {
            System.out.println("Button Six");
        }


    }  




public static void main(String[] args) 
{
    ShowFlowlayout frame = new ShowFlowlayout();

     frame.setTitle ("Programming 12.1");
     frame.setLocationRelativeTo(null);
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     frame.setSize(440, 100);
     frame.setVisible(true);
}

`

最佳答案

使用按钮注册 ActionListener:

one.addActionListener(this);
two.addActionListener(this);
...

关于java - 将 ActionListener 添加到按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20556189/

相关文章:

javascript - 将 Remotemessage 中的 JSONString Bundle 解析为 JSON 对象

java - 有没有办法将 ActionListener 添加到此代码

javascript - Chrome 扩展程序 : storage listener for only one stored variable

java - 在build.properties中调用类变量

java - 以相反的顺序遍历 LinkedHashMap

java - 当 ID 为字符串时 N + 1 (JpaRepository)

java - ActionListener 和 IF 语句出现问题

java - 带 servlet 的 SQL Server 2008

Java boolean 值和 JButton

java - JPopupMenu getParent() 返回 null?