How to print the user input on screen from a TextField using Java Swing

社会主义新天地 提交于 2019-12-02 07:00:20

问题


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.


回答1:


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();
}


来源:https://stackoverflow.com/questions/13171604/how-to-print-the-user-input-on-screen-from-a-textfield-using-java-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!