Netty and GUI for Java

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

I created a simple Netty Application with a server and client to interact through the console. Now I am trying to add a GUI so the client can view/and enter their messages w/o the console.

I decided it would not be wise to create the GUI in the same class that is used to create the channel.

Here is an example of my Main Client Class.

public void run() throws Exception {     EventLoopGroup group = new NioEventLoopGroup();      try {         Bootstrap bootstrap = new Bootstrap()             .group(group)             .channel(NioSocketChannel.class)             .handler(new ChatClientInitializer());          Channel channel = bootstrap.connect(host, port).sync().channel();          BufferedReader in = new BufferedReader(new InputStreamReader(System.in));          while (true) {             channel.writeAndFlush((in.readLine() + "\r\n"));         }      } finally {         group.shutdownGracefully();     } } 

How do I create the GUI so that when the user enters a message in the JTextField it will be passed to the channel.writeAndFlush method?

Do I create an instance of the GUI in the .run method.

Also the second part of my question, in my handler class (code below) how do I pass an incoming message to the JTextArea in my GUI?

Here is a sample of the the very basic Handler Class right now.

protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {     System.out.println(msg);  } 

And for reference here is my GUI class.

public ClientGUI(){      enterField = new JTextField();     enterField.setEditable(true);     enterField.addActionListener(             new ActionListener(){                 public void actionPerformed(ActionEvent event){                     sendMessage(event.getActionCommand());                     enterField.setText("");                 }             });     add(enterField,BorderLayout.NORTH);      displayArea = new JTextArea();     add (new JScrollPane(displayArea), BorderLayout.CENTER);     setSize(300,150);     setVisible(true);    }  public void sendMessage(String message){ //      what to do here?         } 

回答1:

ClientGUI class must have a reference to the Channel to communicate via. Assuming that you also have a reference to the ClientGUI instance somewhere and the Channel is created after GUI is initialized, you could add some setter to ClientGUI:

public class ClientGUI {     private volatile Channel channel;      public void setChannel(Channel channel) {         this.channel = channel;     }      public void sentMessage(String msg) {         channel.writeAndFlush(msg);     }     ... } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!