關於JavaGUI中getSource總是返回false解決
阿新 • • 發佈:2018-11-09
關於這個問題,首先我們應該區分一下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("你點選了關閉按鈕"); } } }
很容易你就會發現原來是重複定義了物件。
對於初學者來講很容易出現像上面一些細節性的小問題,這個時候建議大家從新寫一個小例子除錯一下並對比之前寫的,或許你就會容易的從中發現問題。