java - 不同的按钮执行不同的操作

标签 java swing button actionlistener

我正在尝试进行实验,但似乎找不到任何可以提供帮助的地方。

我的实验是一组多个按钮,每个按钮在 SwingView 上的文本框中打印一行单独的文本。

我有多个按钮,但每个按钮都指向同一个 ActionListener。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextArea1 implements ActionListener{
JTextArea text;
int numClick = 0;

public static void main(String[] args){
    TextArea1 gui = new TextArea1();
    gui.go();
    }

public void go(){
    JFrame aFrame = new JFrame();

    JPanel aPanel = new JPanel();
    JPanel aPanel2 = new JPanel();
    JPanel aPanel3 = new JPanel();
    JPanel aPanel4 = new JPanel();
    JPanel aBoard = new JPanel();

    JButton aButton = new JButton("Just Click it");
    JButton aButton1 = new JButton("1");
    JButton aButton2 = new JButton("2");
    ...
    JButton aButton9 = new JButton("9");        

    aPanel2.setBackground(Color.darkGray);
    aPanel3.setBackground(Color.darkGray);
    aPanel4.setBackground(Color.darkGray);
    aBoard.setLayout(new GridLayout(3,3));

    aBoard.add(aButton1);
    aBoard.add(aButton2);
    ...
    aBoard.add(aButton9);

    aButton.addActionListener(this);
    aButton1.addActionListener(this);
    aButton2.addActionListener(this);
    ...
    aButton9.addActionListener(this);

    text = new JTextArea(3,20);
    text.setLineWrap(true);

    JScrollPane scroller = new JScrollPane(text);
    scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
    scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

    aPanel.add(scroller);

    aFrame.getContentPane() .add(BorderLayout.EAST, aPanel2);
    aFrame.getContentPane() .add(BorderLayout.WEST, aPanel3);
    aFrame.getContentPane() .add(BorderLayout.NORTH, aPanel4);
    aFrame.getContentPane() .add(BorderLayout.SOUTH, aPanel);
    aFrame.getContentPane() .add(BorderLayout.CENTER, aBoard);

    aFrame.setSize(350,300);
    aFrame.setVisible(true);
    }

public void actionPerformed(ActionEvent ev){
    numClick++;
    text.append("button clicked " + numClick + "time(s) \n");
    }
}

这就是我到目前为止所写的内容。我已经获得了每次单击按钮时打印出新文本的代码。但代码并没有区分每个按钮,所以无论是button1还是button2,都会发生同样的情况

最佳答案

如果您需要对所有 JButton 使用相同的 ActionListener,则使用

aButton.setActionCommand("First");

类似地,也为其他 JButton 设置 ActionCommands,并在 actionPerformed 方法中使用

if(ev.getActionCommand.equals("First"))
    // aButton was pressed as the actionCommand of it is "First"

并类似地添加其他 if 来检查其他 JButton 是否被按下。

关于java - 不同的按钮执行不同的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27664158/

相关文章:

java - 简单的 TestFX 示例失败

java - Eclipse 和包资源管理器

java - 引用游标和结果集

java - 当我尝试初始化 CategoryAxis xAxis 时出现 java.lang.ExceptionInInitializerError

java - 捕获 Java Swing 中的特定击键

java - com.google.gson.JsonSyntaxException : java. lang.IllegalStateException:需要一个字符串,但结果是 BEGIN_ARRAY

java - while 循环内的计时器

android - 在横向模式下强制关闭,但在纵向模式下不强制关闭

android - 单击按钮开始另一个 Activity

android - 按钮未显示在 LinearLayout 中