ActionListener没有使用Java

Ank*_*Ank 0 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

        }
}
Run Code Online (Sandbox Code Playgroud)

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

Jef*_*rey 6

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


Gui*_*let 5

你的代码完全搞砸了.你实例化你的JPanel p两次,你的按钮被声明为"打开",但实际上是"保存".您将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

    }
}
Run Code Online (Sandbox Code Playgroud)