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不在这里工作
你的代码完全搞砸了.你实例化你的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)
| 归档时间: |
|
| 查看次数: |
5229 次 |
| 最近记录: |