Swing 使用JMS的简单聊天客户端

Swing 使用JMS的简单聊天客户端,swing,jakarta-ee,netbeans,jms,chat,Swing,Jakarta Ee,Netbeans,Jms,Chat,我正在使用Swing、Java消息服务和GlassFish4.1服务器从一个Jpanel构建一个聊天盒,这样我就可以将它添加到我的Jframe应用程序中;但我似乎在建立联系方面有问题 在运行期间,程序在以下行停止: TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn"); 我以前在一个企业应用程序上使用了这个客户机代码,但现在我正试图将它添加到一个常规的Java项目中,这让我很为难 非常感谢在这方面的

我正在使用Swing、Java消息服务和GlassFish4.1服务器从一个Jpanel构建一个聊天盒,这样我就可以将它添加到我的Jframe应用程序中;但我似乎在建立联系方面有问题

在运行期间,程序在以下行停止:

TopicConnectionFactory tcf = (TopicConnectionFactory) ctx.lookup("BJconn");
我以前在一个企业应用程序上使用了这个客户机代码,但现在我正试图将它添加到一个常规的Java项目中,这让我很为难

非常感谢在这方面的任何帮助,我对JMS非常陌生,所以请尽可能地保留答案。谢谢

import java.awt.event.KeyEvent;
import javax.jms.*;
import javax.naming.*;
import javax.swing.*;
import javax.swing.text.DefaultCaret;

public class ChatPanel extends javax.swing.JPanel implements Runnable{

private Thread t = null;
private TopicConnection tpConnection = null;
private TopicPublisher tpPublisher = null;
private TopicSession tpSession = null;
private TopicSubscriber tpSubscriber = null;
private final String name;


/**
 * Creates new form chatFrame
 * @param nickName
 */
public ChatPanel(String nickName) 
{
  initComponents();
  DefaultCaret caret = (DefaultCaret) gameInfoTextArea.getCaret();
  caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  name = nickName;
  connect();
}

/**
 * This method is called from within the constructor to initialise the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
// </editor-fold>                        

public JTextArea getTextArea()
{
  return gameInfoTextArea;
}        

public void setText(String textString)
{
  String s = gameInfoTextArea.getText() + "\n" + textString; 
  gameInfoTextArea.setText(s);
}        

private void connect()
{
 try
    {
      Context ctx = new InitialContext();
      TopicConnectionFactory tcf = (TopicConnectionFactory) 
              ctx.lookup("BJconn");
      tpConnection = tcf.createTopicConnection();
      tpConnection.setClientID(name);
      tpSession = tpConnection.createTopicSession(false, 
              TopicSession.AUTO_ACKNOWLEDGE);
      Topic topic = (Topic) ctx.lookup("BJDest");
      tpPublisher = tpSession.createPublisher(topic);
      tpSubscriber = tpSession.createDurableSubscriber(topic, name);
      tpConnection.start();
      t = new Thread(this);
      t.start();
    }
    catch (Exception e)
    {
       JOptionPane.showMessageDialog(null, "Chat cannot connect");
       System.out.println(e.getMessage());
    }
}        

/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
    try 
    {
      tpConnection.close();
    }
    catch (Exception e)
    {
      JOptionPane.showMessageDialog(null, e.getMessage() );
    }        
} */                                                                                       



private void sendMessage()
{
  try
  {
    TextMessage tx = tpSession.createTextMessage();
    tx.setText(name + ": " + this.chatField.getText());
    tpPublisher.send(tx);
    this.chatField.setText("");
  }
  catch (Exception e)
  {
    JOptionPane.showMessageDialog(null, "Cannot send message");
  }    
}        

@Override
public void run()
{
  try
  {
    while (true)
    {
      TextMessage tx = (TextMessage) tpSubscriber.receive();
      if (tx != null)
      {
        String content = "";
        content += this.gameInfoTextArea.getText() + "\n" + tx.getText();
        this.gameInfoTextArea.setText(content);
        Thread.sleep(100);
      }    
    }    
  }
  catch (Exception e)
  {
    System.out.println(e.getMessage());
  }        
}        

/**
 * This method is called from within the constructor to initialise the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    chatField = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    gameInfoTextArea = new javax.swing.JTextArea();

    setBackground(new java.awt.Color(0, 102, 0));

    chatField.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            chatFieldActionPerformed(evt);
        }
    });
    chatField.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyReleased(java.awt.event.KeyEvent evt) {
            chatFieldKeyReleased(evt);
        }
    });

    gameInfoTextArea.setEditable(false);
    gameInfoTextArea.setColumns(20);
    gameInfoTextArea.setRows(5);
    jScrollPane1.setViewportView(gameInfoTextArea);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
         layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(chatField)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 358, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(chatField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    );
}// </editor-fold>                        

private void chatFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
}                                         

private void chatFieldKeyReleased(java.awt.event.KeyEvent evt) {                                      
    if (evt.getKeyCode() == KeyEvent.VK_ENTER)
    {
      sendMessage();
    } 
}                                     


// Variables declaration - do not modify                     
private javax.swing.JTextField chatField;
private javax.swing.JTextArea gameInfoTextArea;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration                   
import java.awt.event.KeyEvent;
导入javax.jms.*;
导入javax.naming.*;
导入javax.swing.*;
导入javax.swing.text.DefaultCaret;
公共类ChatPanel扩展javax.swing.JPanel实现可运行{
私有线程t=null;
私有TopicConnection tpConnection=null;
私有TopicPublisher tpPublisher=null;
private TopicSession tpSession=null;
私有TopicSubscriber tpSubscriber=null;
私有最终字符串名;
/**
*创建新表单框架
*@param昵称
*/
公共聊天面板(字符串昵称)
{
初始化组件();
DefaultCaret插入符号=(DefaultCaret)gameInfoTextArea.getCaret();
插入符号setUpdatePolicy(DefaultCaret.ALWAYS\u UPDATE);
姓名=昵称;
connect();
}
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
//                         
公共JTextArea getTextArea()
{
返回gameInfoTextArea;
}        
公共void setText(字符串textString)
{
字符串s=gameInfoTextArea.getText()+“\n”+textString;
gameInfoTextArea.setText;
}        
专用void connect()
{
尝试
{
Context ctx=新的InitialContext();
TopicConnectionFactory tcf=(TopicConnectionFactory)
ctx.lookup(“BJCON”);
tpConnection=tcf.createTopicConnection();
tpConnection.setClientID(名称);
tpSession=tpConnection.createTopicSession(false,
TopicSession.AUTO_ACKNOWLEDGE);
Topic=(Topic)ctx.lookup(“BJDest”);
tpPublisher=tpSession.createPublisher(主题);
tpSubscriber=tpSession.createDurableSubscriber(主题、名称);
tpConnection.start();
t=新螺纹(本螺纹);
t、 start();
}
捕获(例外e)
{
showMessageDialog(null,“聊天室无法连接”);
System.out.println(e.getMessage());
}
}        
/*private void closeButtonActionPerformed(java.awt.event.ActionEvent evt){
尝试
{
tpConnection.close();
}
捕获(例外e)
{
showMessageDialog(null,e.getMessage());
}        
} */                                                                                       
私有void sendMessage()
{
尝试
{
TextMessage tx=tpSession.createTextMessage();
tx.setText(name+”:“+this.chatField.getText());
tpPublisher.send(tx);
this.chatField.setText(“”);
}
捕获(例外e)
{
showMessageDialog(null,“无法发送消息”);
}    
}        
@凌驾
公开募捐
{
尝试
{
while(true)
{
TextMessage tx=(TextMessage)tpSubscriber.receive();
如果(tx!=null)
{
字符串内容=”;
content+=this.gameInfoTextArea.getText()+“\n”+tx.getText();
这个.gameInfoTextArea.setText(content);
睡眠(100);
}    
}    
}
捕获(例外e)
{
System.out.println(e.getMessage());
}        
}        
/**
*从构造函数中调用此方法来初始化表单。
*警告:不要修改此代码。此方法的内容始终为
*由表单编辑器重新生成。
*/
@抑制警告(“未选中”)
//                           
私有组件(){
chatField=newjavax.swing.JTextField();
jScrollPane1=newjavax.swing.JScrollPane();
gameInfoTextArea=newjavax.swing.JTextArea();
setBackground(新java.awt.Color(0,102,0));
addActionListener(新java.awt.event.ActionListener(){
public void actionPerformed(java.awt.event.ActionEvent evt){
已执行的行动(evt);
}
});
addKeyListener(新java.awt.event.KeyAdapter(){
public void keyReleased(java.awt.event.KeyEvent evt){
查特菲尔德密钥释放(evt);
}
});
gameInfoTextArea.setEditable(false);
gameInfoTextArea.setColumns(20);
gameInfoTextArea.setRows(5);
jScrollPane1.setViewportView(gameInfoTextArea);
javax.swing.GroupLayout=newjavax.swing.GroupLayout(this);
这个.setLayout(布局);
layout.setHorizontalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(查特菲尔德)
.addComponent(jScrollPane1,javax.swing.GroupLayout.Alignment.TRAILING,javax.swing.GroupLayout.DEFAULT\u SIZE,358,Short.MAX\u值)
);
layout.setVerticalGroup(
createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1,javax.swing.GroupLayout.DEFAULT\u SIZE,107,Short.MAX\u值)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(chatField,javax.swing.GroupLayout.PREFERRED\u SIZE,javax.swing.GroupLayout.DEFAULT\u SIZE,javax.swing.GroupLayout.PREFERRED\u SIZE))
);
}//                         
private void chatFieldActionPerformed(java.awt.event.ActionEvent evt){
//TODO在此处添加您的处理代码:
}                                         
private void chatFieldKeyReleased(java.awt.event.KeyEvent evt){
if(evt.getKeyCode()==KeyEvent.VK_ENTER)
{
sendMessage();
} 
}