lunes, 27 de febrero de 2012

gridbagLayout chat actionListener, KeyListener


package ejercicios;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Capitulo31KeyListener extends JFrame implements ActionListener,KeyListener{
private JTextArea area;
private JScrollPane scroll;
private JTextField texto;
private JButton boton;

public Capitulo31KeyListener()
{
super("GRidBagLayout");
this.setSize(400,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new GridBagLayout());
GridBagConstraints gbc=new GridBagConstraints();

area=new JTextArea();
scroll=new JScrollPane(area);
texto=new JTextField(20);
boton=new JButton("Enviar");

gbc.gridx=0;//define la columna
gbc.gridy=0;//la fila
gbc.gridwidth=2;//cantidad de columnas
gbc.gridheight=1;//cantidad de filas
gbc.weightx=1.0;//cuanto cresca en ancho
gbc.weighty=1.0;//cuanto creasca en alto
gbc.fill=GridBagConstraints.BOTH;//como quiere que crezca, para ambos lados
add(scroll,gbc);

gbc.gridx=0;
gbc.gridy=1;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1.0;
gbc.weighty=0.0;
gbc.fill=GridBagConstraints.HORIZONTAL;
add(texto,gbc);

gbc.gridx=1;//define la columna
gbc.gridy=1;//la fila
gbc.gridwidth=1;//cantidad de columnas
gbc.gridheight=1;//cantidad de filas
gbc.weightx=0.0;//cuanto cresca en ancho
gbc.weighty=0.0;//cuanto creasca en alto
gbc.fill=GridBagConstraints.NONE;
add(boton,gbc);

boton.addActionListener(this);
texto.addKeyListener(this);
this.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==boton){
area.append(texto.getText()+"\n");
texto.setText("");
}
}

@Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_ENTER:
area.append(texto.getText()+"\n");
texto.setText("");
break;
}
}

@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub

}

@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub

}

 public static void main(String[] args) {
new Capitulo31KeyListener();
}
}

No hay comentarios:

Publicar un comentario