有没有办法让按钮在不创建实现 ActionListener 的新类的情况下对对象执行操作?



只是好奇。有没有办法让我的按钮在我的面板上执行操作,而无需创建一个扩展 JPanel 并实现 ActionListener 的新类?我的意思是,没有做这样的事情:

public class TestingSomething {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(450, 250, 200, 80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// JPanel
newClass panel = new newClass();
JButton button = new JButton("Press me!");
// button action to panel
button.addActionListener(panel);
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
}
class newClass extends JPanel implements ActionListener {
// Action to perform
@Override
public void actionPerformed(ActionEvent e) {
setBackground(Color.BLUE);
}
}

这是我想执行问题中要求的操作的代码:

public class TestingSomething {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(450, 250, 200, 80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JButton button = new JButton("Press me!");
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
}

谢谢你的帮助。

当然。"扩展 JPanel 并实现 ActionListener" - 在 JPanel 中你不需要这样做。但是你应该使用 ActionListener。

public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked");
}
}
MyActionListener myListener = new MyActionListener();
button.addActionListener(myListener);

我想你需要这样代码 -

import java.awt.*;  
import java.awt.event.*; 
import javax.swing.*;
public class TestingSomething implements ActionListener{

public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setBounds(450, 250, 200, 80);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel=new JPanel();
JButton button = new JButton("Press me!");
// button action to panel
button.addActionListener(new ActionListener(){  
public void actionPerformed(ActionEvent e){  
button.setBackground(Color.BLUE);  
}  
});  
panel.add(button);
frame.add(panel);
frame.setVisible(true);
}
}

最新更新