我试图在下面调用此事件;我使用TabBuilder创建框架(因为它是我的应用程序的一部分)然后它调用弹出的搜索屏幕;但是使用键绑定或单击按钮进行搜索的事件不起作用,当然我做错了但我不知道是什么因为我有点新的Java。请有人帮帮我吗?
public class SearchScreen extends EventSearch{
public static void main (String[] args){
SearchScreen s= new SearchScreen();
}
public void SearchScreen(){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
public class EventSearch extends TabBuilder{
String userQuery;
String key = "ENTER";
KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
public EventSearch(){
btSearch.addActionListener(this);
txtSearch.getInputMap().put(keyStroke, key);
txtSearch.getActionMap().put(key, enterAction);
}
Action enterAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
try{
System.out.println("worked");
} catch (IOException e1) {
e1.printStackTrace(); //print failure
JOptionPane.showMessageDialog(null, "HTTP request failure.");
}
}
};
}
public class TabBuilder implements ActionListener {
protected JButton btSearch;
JMenuItem close, search;
protected JTextField txtSearch;
protected JFrame searchFrame = new JFrame();
public void TabBuilder(){
}
public void searchTab(){
JLabel lbSearch;
JPanel searchPane;
btSearch= new JButton("Search");
lbSearch= new JLabel("Type Keywords in english to be searched below:");
lbSearch.setHorizontalAlignment(SwingConstants.CENTER);
txtSearch= new JTextField();
searchPane=new JPanel();
searchPane.setBackground(Color.gray);
searchPane.add(lbSearch);
searchPane.add(txtSearch);
searchPane.add(btSearch);
searchPane.setLayout(new GridLayout(3,3));
btSearch.setEnabled(true);
searchFrame.add(searchPane);
searchFrame.setTitle("SHST");
searchFrame.setSize(400, 400);
searchFrame.setVisible(true);
searchFrame.setDefaultCloseOperation(1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
SearchScreen s = new SearchSreen();
}
}
}
答案 0 :(得分:3)
你写这个actionListener
public void actionPerformed(ActionEvent e){
if(e.getSource()==close){
System.exit(0);
}
if(e.getSource()==search){
TabBuilder tb = new TabBuilder();
tb.searchTab();
}
}
并且您添加到btnSearch.addActionListener(this)
,您的actionListener永远不会做任何事情。
如果您的KeyBinding
发生了类似情况,请将操作添加到txtSearch
,然后您会询问来源是e.getSource()==btSearch
对于KeyBindings
,您可以使用常量来指定何时必须绑定。
JComponent.WHEN_FOCUSED
,JComponent.WHEN_IN_FOCUSED_WINDOW
,JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
例如:
txtSearch.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);