java swing textfield,如何使用Java Swing从TextField在屏幕上打印用户输入

I am new with GUI in Java. However, I tried the program below but it won't work. It's a standalone application. I searched the web but couldn't find relevant answer. Please help.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class usernamepass extends JFrame implements ActionListener{

JTextField a;

public usernamepass(){

JFrame jp=new JFrame();

add(jp);

a=new JTextField(12);

jp.add(a);

a.addActionListener(this);

}

public void actionPerformed(ActionEvent ae){

this.repaint();

}

public static void main(String [] args){

usernamepass obj=new usernamepass();

obj.setSize(300,300);

obj.setVisible(true);

obj.setResizable(true);

obj.setTitle("HI") ;

}

public void paint(Graphics g){

g.drawString("Name "+a.getText(),10,70);

}

}

EDIT:Sorry I messed up the code(System crashed).

Well, The code is running with the changes however, I see that the print messages just overwrites the older one and does not get repainted.

解决方案

Instead of making a new usernamepass object in your actionPerformed method use this keyword for painting the current screen.

try this in your code and it should work.

public void actionPerformed(ActionEvent ae){

this.repaint();

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值