关于JavaGUI中getSource总是返回false解决
关于这个问题,首先我们应该区分一下getActionCommand()跟getSource()的区别
getActionCommand():Returns the command name of the action event fired by this button. If the command name is null (default) then this method returns the label of the button. 他返回的是一个按钮的标签,可以把它看做一个字符。
getSource():Returns:The object on which the Event initially occurred.也就是说它返回一个对象
接下来我们来看一个一个关于问题的实例
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Demo extends JFrame implements ActionListener{
private static JButton jb1,jb2;
//private static JButton jb2;
private static JPanel jp;
public static void main(String[] args) {
Demo d = new Demo();
}
public Demo() {
init();
}
private void init() {
JButton jb1 = new JButton("打开");
JButton jb2 = new JButton("关闭");
jp = new JPanel();
jp.add(jb2);
jp.add(jb1);
jb1.addActionListener(this);
jb2.addActionListener(this);
this.add(jp);
this.setVisible(true);
this.setSize(400, 300);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb1) {
System.out.println("你点击了打开按钮");
}
else if(e.getSource()==jb2) {
System.out.println("你点击了关闭按钮");
}
}
}如果你写的代码很很长且有点乱,从中你可能发现不了问题,但你对比下面的代码并进行运行一次你就会发现问题了
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Demo extends JFrame implements ActionListener{
private static JButton jb1,jb2;
//private static JButton jb2;
private static JPanel jp;
public static void main(String[] args) {
Demo d = new Demo();
}
public Demo() {
init();
}
private void init() {
jb1 = new JButton("打开");
jb2 = new JButton("关闭");
jp = new JPanel();
jp.add(jb2);
jp.add(jb1);
jb1.addActionListener(this);
jb2.addActionListener(this);
this.add(jp);
this.setVisible(true);
this.setSize(400, 300);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==jb1) {
System.out.println("你点击了打开按钮");
}
else if(e.getSource()==jb2) {
System.out.println("你点击了关闭按钮");
}
}
}
很容易你就会发现原来是重复定义了对象。
对于初学者来讲很容易出现像上面一些细节性的小问题,这个时候建议大家从新写一个小例子调试一下并对比之前写的,或许你就会容易的从中发现问题。
浙公网安备 33010602011771号