I have a JFrame which looks like a typical chat box. To connect and disconnect from the server I implemented a JPopupMenu and added a MouseListener to the main window.
However the popup menu does not appear.
Various JComponents in the main window:
JTextArea within a JScrollPane JTextField to enter the message Send button JScrollPane and an ArrayList to display the users
The popup is supposed to appear no matter where you right click. Be it on the JTextArea or the field to enter your message.
To which all components do I add listeners and what listener do I add ?
Code
Variables:
private static A_Chat_Client chatClient;
public static String userName = "Anonymous";
//------------------------------------------------------------------------------
public static JFrame mainFrame = new JFrame();
public static JTextArea textArea = new JTextArea(30,30);
public static JScrollPane pane = new JScrollPane(textArea);
public static JTextField message = new JTextField(10);
public static JButton send = new JButton("Send");
public static JPopupMenu popup = new JPopupMenu();
public static JMenuItem connect = new JMenuItem("Connect");
public static JMenuItem disconnect = new JMenuItem("Disconnect");
public static JMenuItem help = new JMenuItem("Help");
public static JList usersOnline = new JList();
public static JScrollPane userPane = new JScrollPane(usersOnline);
Main method
public static void main(String[] args) {
buildMainWindow();
initialize();
addListeners();
popup.show(mainFrame, 0, 0); //forcefully popup
}
addListeners()
public static void addListeners(){
mainFrame.addMouseListener(new MouseHandler());
send.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
actionSend();
}
});
connect.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
actionConnect();
}
});
disconnect.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
actionDisconnect();
}
});
help.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
actionHelp();
}
});
}
class MouseHandler
private static class MouseHandler extends MouseAdapter{
@Override
public void mouseClicked(MouseEvent e){
if(e.isPopupTrigger()){
popup.show(mainFrame, e.getX(), e.getY());
}
}
}
You could attach an
AWTEventListenerto the main event queue usingToolkit#addAWTEventListenerYou would then need to check the type of event your are receiving and check to see if it’s popup event.