【问题标题】:ActionEvent won't appearActionEvent 不会出现
【发布时间】:2015-03-10 00:48:16
【问题描述】:

我的程序有问题。这是我的代码:

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 出现?

希望有人可以帮助我。感谢您的帮助。

【问题讨论】:

    标签: java swing awt actionevent


    【解决方案1】:

    仔细看看这个...

    String command = e.getActionCommand();
    if (command.equals(btn1)){
    

    commandStringbtn1JButton,它们什么时候可能是 equal

    有几种方法可以解决它,例如,你可以做这样的事情......

    if ("CLICK HERE".equals(command)) {
    

    或者类似的...

    if (e.getSource() == btn1) {
    

    但我更喜欢第一个...

    但是,因为ActionListener 是注册到btn1 的烦人侦听器,所以事件源不能是btn1 以外的任何东西,所以你可以简单地做这样的事情......

    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); 
        }
    
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      相关资源
      最近更新 更多