1 回答
TA贡献1条经验 获得超0个赞
以下是我按照我的理解写的。也是正在学GUI。所以有不足之处,共同学习。
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
/**
*
* @author 一生所爱_
*
*/
public class Text1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
login lo1=new login();
}
}
class login{
JFrame jf1;
JPanel jp1,jp2;
JTextField jt1;
JLabel jl1,jl2,jl3;
public login(){
jf1=new JFrame("文本变标签");
jt1=new JTextField(30);
jl1=new JLabel("文本:");
jl2=new JLabel("标签:");
jl3=new JLabel();
jp1=new JPanel();
jp2=new JPanel();
//添加组件到面板
jp1.add(jl1);
jp1.add(jt1);
jp1.setLayout(new FlowLayout());
jp2.add(jl2);
jp2.add(jl3);
jp2.setLayout(new FlowLayout());
//添加面板到窗口
jf1.add(jp1);
jf1.add(jp2);
//设置窗口
jf1.setSize(400, 300);
jf1.setLocation(300,200);
//网格布局,2行1列
jf1.setLayout(new FlowLayout());
jf1.setVisible(true);
//为文本框添加键盘监视器
jt1.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
//如果输入回车则将文本显示在标签上
if(e.getKeyChar()==KeyEvent.VK_ENTER){
jl3.setText(jt1.getText());
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
//将记录的文本写入文本框
int keyCode=e.getKeyCode();
String s=KeyEvent.getKeyText(keyCode);
}
});
}
}
添加回答
举报