-1

我 1 周前刚开始学习 Java,而且我是 100% 的初学者。在这段代码中,我似乎无法让 actionlistener/get one 工作。尽管阅读了数十篇教程,但我什至不知道在哪里/如何/以什么方式放置它。我创建了一个带有 JPanel 的 JFrame,在 JPanel 上有一个按钮。到目前为止一切都很好(并且正在工作)。但是,我希望它是这样,如果单击该按钮,则会出现另一个按钮。非常感谢您提前!

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Skeleton extends JFrame implements ActionListener {

    public static void main(String[] args) {
    //------------------------------------------------
    JFrame frame = new JFrame("Skeleton");
    JPanel panel = new JPanel();
frame.setContentPane(panel);
    frame.setSize(600,600);
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    JButton button = new JButton("This is a button.");
    JButton button2 = new JButton("Hello");
    panel.setLayout(null);
    button.setBounds(20,20,200,25);
    button2.setBounds(20,70,200,25);
    panel.add(button);
   //-------------------------------------------

button.addMouseListener(this);


}

public void ActionPerformed(ActionEvent e) {
    System.out.println("Hello");

}
}
4

2 回答 2

4

我会给你一些建议

1)不要在顶级类中实现ActionListener,而是使用匿名类或私有类。

例子 :

匿名类(也称为 Swing 动作)

myComponent.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent evt){
              //code here
      }

})

或者

//inner class
public class Skeleton{

// in some part
private class MyActionListener implements ActionListener{
      public void actionPerformed(ActionEvent evt){
             //code here
       }
}


}

2)您的代码无法编译,因为您没有实现 ActionListener 接口

public void actionPerformed(ActionEvent evt)是签名。

你必须addActionListener到你的组件

button.addActionListener(this);

3)不要使用空布局,因为如果你想添加更多组件或调整窗口大小,你会遇到很多问题,因为你必须setBounds手动,而不是使用[Layout Manager][1].

4) 例如,如果没有必要,尽量不要扩展 JFrame,而是在你的类中有引用。

  public class Skeleton{

    private JFrame frame;

    }
于 2013-07-04T18:38:32.377 回答
2

您需要添加动作监听器。

将事件处理程序类的实例注册为一个或多个组件的侦听器。例如:

yourdesiredcomponent.addActionListener(this);

有关更多详细信息,请查看文档

于 2013-07-04T17:57:01.040 回答