我有一个LabelTextField类,它按照其指示进行操作,它创建了一个标签,后跟文本字段。我希望此类像JTextField那样起作用,即在添加操作侦听器时响应actionPerformed。我使用LabelTextField添加了一个动作侦听器,因此此类中的JTextField将需要接收回调并转发LabelTextField对象名而不是JTextField对象名。
我已经展示了一个简单的JTextField及其工作方式,LabelTextField也在那里以及我希望如何使用它。
我提供了我想做的代码片段。
我在使用此类回调时遇到麻烦,详细信息将很有用。
//
class C_one extends JPanel
{
private JTextField mjtfOne;
private LabelTextField m_nameFind;
public C_one ()
{
setLayout(new FlowLayout());
mjtfOne = new JTextField(20);
mjtfOne.addActionListener(this);
m_nameFind = new LabelTextField("Name", 20);
m_nameFind.addActionListener(this);
add(mjtfOne);
add(m_nameFind);
}
// This is called when return is pressed in either object.
public void actionPerformed(ActionEvent ae)
{
// This works.
if (ae.getSource() == mjbnOne) {
System.out.println("Text field one!");
// ****** This doesn't work. *****
} else if (ae.getSource() == m_nameFind) {
System.out.println("Label Text Field name");
}
}
}
//
//这将创建标签和文本字段作为小部件。
LabelTextField类扩展了JPanel
{
private JTextField mjtf;
private ActionListener mal;
public LabelTextField(String label, int textfieldWidth)
{
setLayout(new FlowLayout());
JLabel lbl = new JLabel(label);
add(lbl);
mjtf = new JTextField(textfieldWidth);
add(mjtf);
}
// The caller of this class will call this as he would for
// JTextField.
public void addActionListener(ActionListener al)
{
mjtf.addActionListener(this);
mal = al;
}
// This will receive the return from JTextField and needs
// to forward this on to calling class with caller object
// not mjtf.
//
// Problem: I can not figure out how to save caller object
// name so when this is called I can forward it on just like
// what JTextField would have done, ie caller can use
// ae.getSource() == m_nameFind.
public void actionPerformed(ActionEvent ae)
{
mal.actionPerformed(ae); // This does call the caller.
}
}
最佳答案
ae.getSource()
的值将为mjtf
,因为这是生成原始ActionEvent
的组件。
如果要将事件的来源设为m_nameFind
,即您的自定义LabelTextField
对象,则需要手动进行设置:
public void actionPerformed(ActionEvent ae)
{
ae.source=this; // this makes it look like the LabelTextField generated the event
mal.actionPerformed(ae);
}
这就是你想做的吗?
-
编辑
感谢@Madprogrammer ..也许您应该像这样重新创建
ActionEvent
public void actionPerformed(ActionEvent ae)
{
mal.actionPerformed(new ActionEvent(this, ae.getID(),
ae.getCommand(), ae.getWhen(), ae.getModifiers() ));
}