简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM