Reputation: 73
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?
}
Upvotes: 1
Views: 1008
Reputation: 12351
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);
}
...
}
Upvotes: 1