ActionListener没有使用Java

时间:2012-03-08 22:51:22

标签: java swing jbutton actionlistener

我在这里缺少什么?

 public class abc extends JFrame    {
 private JButton save = new JButton("Save");

 public abc() {
    JPanel p = new JPanel();
    save.addActionListener(new SaveL());
    p.add(save);
    Container cp = getContentPane();
    p = new JPanel();
    p.setLayout(new GridLayout(2, 1));

    cp.add(p, BorderLayout.NORTH);
  }


 }

 class SaveL implements ActionListener {

        public void actionPerformed(ActionEvent e) {    
            System.out.println("Hello"); // nothing happens

        }
}

为什么我的ActionListener不在这里工作

4 个答案:

答案 0 :(得分:6)

您正在创建JPanel,将JButton添加到其中,然后创建新的JPanel并将该面板添加到JFrame。您需要将原始面板添加到内容窗格中。

答案 1 :(得分:5)

你的代码完全搞砸了。你实例化你的JPanel p两次,你的按钮被声明"打开"但实际上是#34; save"。您将GridLayout与BorderLayour约束混合使用。以下代码有效:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class abc extends JFrame {
    private JButton save = new JButton("Save");

    public abc() {
        JPanel p = new JPanel();
        save.addActionListener(new SaveL());
        p.add(save);
        p.setLayout(new GridLayout(2, 1));

        add(p);
    }

    public static void main(String[] args) {
        abc abc = new abc();
        abc.pack();
        abc.setVisible(true);
    }

}

class SaveL implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("Hello"); // nothing happens

    }
}

答案 2 :(得分:1)

您的代码正在重新创建面板。它正在丢失按钮。

我把它改为:

public class abc extends JFrame{   
    private JButton save = new JButton("Save");

    public abc() {
       JPanel p = new JPanel();
       save.addActionListener(new SaveL());
       p.add(save);
       Container cp = getContentPane();

       cp.add(p, BorderLayout.NORTH);
     }


}

class SaveL implements ActionListener {

       public void actionPerformed(ActionEvent e) {    
           System.out.println("Hello"); // nothing happens

       }
}

并且有效

答案 3 :(得分:0)

private JButton open = new JButton("Save");

save.addActionListener(new SaveL());

你是否宣布保存为开放?