Aplicação
Código
@Override
public void keyPressed(KeyEvent e) {
String messageSent = "User: " + writingTextField.getText();
if(e.getKeyCode() == KeyEvent.VK_ENTER){
writingTextField.setText("");
readingTextArea.setText(readingTextArea.getText() + messageSent + "\n");
}
}
public class MessagePanel extends JPanel {
/**
*
*/
private static final long serialVersionUID = 1L;
JButton sendButton;
JTextField writingTextField;
JTextArea readingTextArea;
public MessagePanel() {
setLayout(new BorderLayout());
createWritingPanel();
createReadingPanel();
}
private void createReadingPanel() {
readingTextArea = new JTextArea();
readingTextArea.setEditable(false);
add(readingTextArea, BorderLayout.CENTER);
}
private void createWritingPanel() {
JPanel writingPanel = new JPanel();
writingPanel.setLayout(new BorderLayout());
writingTextField = new JTextField();
sendButton = new JButton("Send");
sendButton.addActionListener(new ButtonActionListener());
writingPanel.add(writingTextField, BorderLayout.CENTER);
writingPanel.add(sendButton, BorderLayout.EAST);
add(writingPanel, BorderLayout.SOUTH);
}
class ButtonActionListener implements ActionListener, KeyListener{
@Override
public void actionPerformed(ActionEvent e) {
String messageSent = "User: " + writingTextField.getText();
writingTextField.setText("");
readingTextArea.setText(readingTextArea.getText() + messageSent + "\n");
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
String messageSent = "User: " + writingTextField.getText();
if(e.getKeyCode() == KeyEvent.VK_ENTER){
writingTextField.setText("");
readingTextArea.setText(readingTextArea.getText() + messageSent + "\n");
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}