I seem to be having problems with my java gui code, and I have no idea why it's not working.
What needs to happen is when the mouse is clicked on the panel or frame - for now lets just say panel; as this is just a test eventually this code will be implemented for another gui component, but I'd like to get this working first - the popup menu needs to become visible and the focus needs to be set on the text field. Then when the user presses enter or the focus on the text field is lost then the popup menu needs to hide and the text reset to blank or whatever I need it to be.
So this is what I wrote:
public class Test {
private final JFrame frame = new JFrame();
private final JPanel panel = new JPanel();
private final JPopupMenu menu = new JPopupMenu();
private final JTextField field = new JTextField();
private final Obj obj;
//... constructor goes here
public void test(){
frame.setSize(new Dimension(200,200));
field.setColumns(10);
field.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
obj.method(field.getText());
menu.setVisible(false);
field.setText("");
}
});
field.addFocusListener(new FocusListener() {
public void focusLost(FocusEvent e) {
menu.setVisible(false);
field.setText("");
}
//... focus gained event goes here
});
panel.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
menu.setLocation(e.getX(), e.getY());
menu.setVisible(true);
field.requestFocusInWindow();
}
//... other mouse events go here
});
menu.add(field);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
With the code as it is written here the menu automatically hides right after I click. It just flashes on screen briefly and then hides without me doing anything else.
If I change the code to exclude any occurrences of menu.setVisible(false)
then the text field will never gain focus.
Is this due to a misuse of JPopupMenu? Where am I going wrong?
Also note that I left out main or Obj. They are in another file and most likely insignificant to this problem. Obj.method() does nothing and main only calls Test's constructor and test() method.