首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ActionEvent不会出现

ActionEvent不会出现
EN

Stack Overflow用户
提问于 2015-03-10 08:48:17
回答 1查看 35关注 0票数 0

我的程序出了点问题。下面是我的代码:

代码语言:javascript
复制
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;`

public class click_rep extends JFrame{`

    public click_rep(){

        super("CLICK");
        final JButton btn1 = new JButton("CLICK HERE");
        final JLabel label = new JLabel();
        FlowLayout flo = new FlowLayout();
        setLayout(flo);
        add(btn1);
        setSize(315,120);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);

        btn1.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                try{
                    String command = e.getActionCommand();
                    if (command.equals(btn1)){
                        label.setText("CLICK");
                        setVisible(true);
                    }
                }catch(Exception e1){
                    e1.printStackTrace();
                }

            }


        });

    }

    public static void main(String[] a){
        click_rep cp = new click_rep();
    }

}

我的问题是ActionEvent不会出现。我该怎么做才能让ActionEvent出现呢?

希望有人能帮我。谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2015-03-10 08:54:26

仔细看看这个。

代码语言:javascript
复制
String command = e.getActionCommand();
if (command.equals(btn1)){

commandStringbtn1JButton,它们什么时候可能成为equal

有几种方法可以修复它,例如,可以这样做……

代码语言:javascript
复制
if ("CLICK HERE".equals(command)) {

或者像这样..。

代码语言:javascript
复制
if (e.getSource() == btn1) {

但我更喜欢第一个...

但是,因为ActionListener是注册到btn1的一个恼人的鼠标侦听器,所以事件的来源只能是btn1,所以您可以简单地执行以下操作……

代码语言:javascript
复制
btn1.addActionListener(new ActionListener(){

    public void actionPerformed(ActionEvent e){
        label.setText("CLICK");
        // Not sure what this is meant for, as the component
        // must already be visible in order for the user to 
        // activate the button...
        setVisible(true); 
    }

});
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28954380

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档