[英]Trouble with ActionListener
我在实现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");
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.