問題描述
什么是getSource?它返回什么?
What is getSource? and what does it return?
什么是getActionCommand(),它返回什么??
and what is getActionCommand() and what does it return??
我對這兩者感到困惑,任何人都可以給我或區分它們嗎?UI 中的 getSource 和 getActionCommand() 有什么用?具體是 TextField 還是 JTextField?
I am getting confused between these two can anyone give or differentiate them to me? what's the use of getSource and getActionCommand() in UI's? specifically TextField or JTextField?
推薦答案
假設你說的是 ActionEvent
類,那么這兩種方法有很大區別.
Assuming you are talking about the ActionEvent
class, then there is a big difference between the two methods.
getActionCommand()
給你一個代表動作命令的字符串.該值是特定于組件的;對于 JButton
您可以選擇使用 setActionCommand(String command)
設置值,但對于 JTextField
如果您不設置此值,它會自動為您提供文本字段的值.根據 javadoc,這是為了與 java.awt.TextField
兼容.
getActionCommand()
gives you a String representing the action command. The value is component specific; for a JButton
you have the option to set the value with setActionCommand(String command)
but for a JTextField
if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField
.
getSource()
由 ActionEvent
是子級的 EventObject
類指定(通過 java.awt.AWTEvent
).這為您提供了對事件來自的對象的引用.
getSource()
is specified by the EventObject
class that ActionEvent
is a child of (via java.awt.AWTEvent
). This gives you a reference to the object that the event came from.
這是一個例子.有兩個字段,一個具有明確設置的操作命令,另一個沒有.在每個中輸入一些文本,然后按 Enter.
Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.
public class Events implements ActionListener {
private static JFrame frame;
public static void main(String[] args) {
frame = new JFrame("JTextField events");
frame.getContentPane().setLayout(new FlowLayout());
JTextField field1 = new JTextField(10);
field1.addActionListener(new Events());
frame.getContentPane().add(new JLabel("Field with no action command set"));
frame.getContentPane().add(field1);
JTextField field2 = new JTextField(10);
field2.addActionListener(new Events());
field2.setActionCommand("my action command");
frame.getContentPane().add(new JLabel("Field with an action command set"));
frame.getContentPane().add(field2);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(220, 150);
frame.setResizable(false);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent evt) {
String cmd = evt.getActionCommand();
JOptionPane.showMessageDialog(frame, "Command: " + cmd);
}
}
這篇關于getSource() 和 getActionCommand()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!