1

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.

  • Why do you say it isn't working? You need to give us more information. – Michael Nov 01 '12 at 05:50
  • 1
    Fix your tabs, and your code has obvious errors(JPanel stated and used but never instantiated?). You should tend to these before posting your question or most people will just ignore it. – calderonmluis Nov 01 '12 at 05:54
  • possibly that everytime actionPerformed is called, it creates a default usernamepass and changes it to the same thing – yuritsuki Nov 01 '12 at 05:54
  • `public class usernamepass extends JFrame implements ActionListener{ JTextField a; public usernamepass(){ JFrame jf=new JFrame();` Whoa there! Don't ever create more than one frame. Remove `extends JFrame` and just use an instance. See also [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/a/9554657/418556) – Andrew Thompson Nov 01 '12 at 06:05
  • `usernamepass` If that represents a `LoginScreen` with an username and password.. 1) Should be something like `UserNamePass`. 2) Should include a `JPasswordField` for the password. 3) Should probably be put into a `JPanel` that is displayed in a modal `JDialog` or a `JOptionPane`. 4) Should ***not require any custom rendering.*** .. – Andrew Thompson Nov 01 '12 at 06:09

1 Answers1

3

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();
}
Abubakkar
  • 15,488
  • 8
  • 55
  • 83