我在实现 ActionListener 时遇到问题。在我的类 addbutton 中,它不会让我使用 ActionListener。我想做的是显示两个 JFrame 并可以作为按钮单击。除了按钮单击操作之外,我还有其他所有工作。该按钮出现,但单击它没有任何反应,因此我添加了一个 ActionListener,但它没有为我的方法定义。我做错了什么以及我能做些什么来解决它。谢谢。
import java.awt.event.ActionEvent;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JButton;
@SuppressWarnings("serial")
public class PictureTest extends JFrame {
public static class addbutton extends JFrame implements ActionListener{
public addbutton() {
JFrame button = new JFrame();
JButton take = new JButton("Take Please");
button.add(take);
add(take);
button.addActionListener(this); //This line is the issue
}
public void actionPerformed(ActionEvent e) {
e.getSource();
System.out.println("Here");
}
}
public PictureTest() {
ImageIcon image = new ImageIcon("c:/Vending/pepsi.jpg");
JLabel label = new JLabel(image);
JPanel soda = new JPanel();
soda.add(label);
add(soda);
}
public static void main(String[] args) {
PictureTest frame = new PictureTest();
addbutton button = new addbutton();
frame.setSize(250, 450);
frame.setTitle("Pepsi");
frame.setLocation(200, 100);
frame.setUndecorated(true);
button.setSize(105, 25);
button.setLocation(275, 550);
button.setUndecorated(true);
button.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.setVisible(true);
}
}
最佳答案
不要向两个 JFrame
添加相同的按钮。将监听器添加到按钮。
添加两个按钮,但您可以让监听器监听对任一按钮的单击。
JButton take = new JButton("Take Please");
button.add(take);
take.addActionListener(this); // listen to the button
JButton take2 = new JButton("Take Please");
add(take2);
take2.addActionListener(this); // also listen to the other button
此外,按照惯例,所有 Java 类的名称都以大写字母开头。如果您遵循此规则并自己习惯它,其他人将能够更轻松地阅读您的代码。而你也是他们的。
您可以通过不同的组件命名方式来帮助避免此错误。
通常,名为“button”的变量会分配一个 JButton
对象,而不是 JFrame
,在本例中,该对象通常被命名为“otherFrame”之类的名称,表示这是一个框架,此时还有另一个框架也在运行。
执行此操作的另一种方法是使用匿名内部类来进行监听,但您不能轻松地让它以这种方式监听两个按钮。因此,假设一个 JFrame 中只有一个按钮:
JButton take = new JButton("Take Please");
button.add(take);
take.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
e.getSource();
System.out.println("Here");
}
});
关于java - ActionListener 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18837784/