我有一个JFrame
看起来像一个典型的聊天框。为了连接和断开与服务器的连接,我实现了 aJPopupMenu
并将 a 添加MouseListener
到主窗口。
但是弹出菜单不会出现。
主窗口中的各种 JComponents:
JTextArea
在一个JScrollPane
JTextField
输入消息Send
按钮JScrollPane
并ArrayList
显示用户无论您右键单击何处,都应该出现弹出窗口。无论是在
JTextArea
输入消息的字段上还是字段上。我要向哪些所有组件添加侦听器,我要添加什么侦听器?
代码
变量:
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);
主要方法
public static void main(String[] args) {
buildMainWindow();
initialize();
addListeners();
popup.show(mainFrame, 0, 0); //forcefully popup
}
添加监听器()
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();
}
});
}
类 MouseHandler
private static class MouseHandler extends MouseAdapter{
@Override
public void mouseClicked(MouseEvent e){
if(e.isPopupTrigger()){
popup.show(mainFrame, e.getX(), e.getY());
}
}
}