import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main implements ActionListener{
JButton button;
public static void main(String[] args) {
JButton button = new JButton();
JLabel label = new JLabel();
label.setText("");
label.setHorizontalAlignment(JLabel.CENTER);
JPanel redPanel = new JPanel();
redPanel.setBackground(Color.red);
redPanel.setBounds(0,250,250,250);
redPanel.setLayout(new BorderLayout());
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.blue);
bluePanel.setBounds(250,250,250,250);
bluePanel.setLayout(new BorderLayout());
JPanel greenPanel = new JPanel();
greenPanel.setBackground(Color.green);
greenPanel.setBounds(0,0,500,250);
greenPanel.setLayout(new BorderLayout());
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
frame.setSize(750, 750);
frame.setVisible(true);
redPanel.add(label);
redPanel.add(button);
frame.add(redPanel);
frame.add(bluePanel);
frame.add(greenPanel);
button.setBounds(0,250,250,250);
button.addActionListener(redPanel);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
System.out.print("ahahah");
}
}
}
我想在主类中添加一个功能齐全的按钮
我遇到了错误:AbstractButton 类型中的方法 addActionListener(ActionListener) 不适用于参数 (JPanel)
(我尝试将 JPanel 作为参数)
button.addActionListener(redPanel);
您无法将
java.awt.Component
(即 JPanel)注册为 ActionListener
的 JButton
。相反,您应该使用此处列出的适当侦听器之一,将其注册到 JPanel
: https://docs.oracle.com/javase/7/docs/api/java/awt/Component.html
你应该这样做:
button.addActionListener(new Main());
但是如果你为
ActionListener
创建一个新类并在那里实现接口,然后在 main 方法中使用你自己的侦听器的构造函数,那就更好了。
并始终阅读文档;)
你尝试过吗 redPanel.addActionListener(this);