什么是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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!