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

时间:2014-12-27 03:47:06

标签: 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都没关系,同样的情况发生了

2 个答案:

答案 0 :(得分:1)

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

aButton.setActionCommand("First");

同样,为其他ActionCommands设置JButton,在actionPerformed方法中,使用

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

同样添加其他if以检查是否已按下其他JButton

答案 1 :(得分:1)

查看How to Use Actions,这可以让您隔离每个按钮的功能,还可以让它可以重复用于其他内容,如键绑定和菜单。

public class JustClickIt extends AbstractAction {  
    public JustClickIt() {
        putValue(NAME, "Just Click It");
    }

    public void actionPerformed(ActionEvent evt) {
        // Make it happen
    }
}

然后将其应用于按钮......

JButton aButton = new JButton(new JustClickIt());