Solved

Java Swing: Simple Password Window?

Posted on 2004-08-27
13
406 Views
Last Modified: 2013-11-23
Hi,

Recently I decided to attempt to learn Swing b\c I was really bored. I wrote the following little ghetto IM client. I would like to add a window that will appear at start up and prompt the user for a password. If the user enters the incorrect password or attempts to close the window, the application would exit. If they enter the correct password, the application will work normally.

Also:

Is it possible to get the file into an .exe so I don't have to run it command line?

Thanks for any and all help!

*********************

/**
 * SeraphIM
 *
 * @author:   TkH
 * @modified: 08.26.2004
 *
 */

import java.awt.*;
import java.net.*;
import javax.swing.*;
import java.awt.event.*;

public class SeraphIM extends JFrame
{
  public SeraphIM()
  {
    super("SeraphIM");
   
    Container contentPane = getContentPane();
  }
 
  public static void main( String[] args )
  {
    try
    {
      final JFrame application = new SeraphIM();

      application.setBounds(100,100,530,375);
      application.setVisible(true);
      application.setResizable(false);
      application.setDefaultCloseOperation(EXIT_ON_CLOSE);

      application.addWindowListener( new WindowAdapter() { public void windowClose( WindowEvent e ) { System.exit(0); } } );
     
      application.getContentPane().setLayout( new FlowLayout( FlowLayout.LEFT ) );
     
      JLabel         label1     = new JLabel("Recipient:");
      JLabel         label2     = new JLabel(":");
      JLabel         label3     = new JLabel("SeraphIM                                    " );
      JLabel         label4     = new JLabel("  Alias:" );
      JLabel         label5     = new JLabel("                                           ");
      JTextField     textfield1 = new JTextField(15);
      JTextField     textfield2 = new JTextField(3);
      JTextField     textfield3 = new JTextField(10);
      JTextArea      textarea1  = new JTextArea(10,45);
      JScrollPane    scrollpane = new JScrollPane(textarea1);
      JTextArea      textarea2  = new JTextArea(5,44);
      JButtonCustom1 button1    = new JButtonCustom1("Send", textarea1, textarea2, textfield3, textfield1, textfield2 );
     
      label3.setFont( new Font( "Courier", Font.BOLD, 12 ) );
      textfield1.setBackground( new Color(255,255,255) );
      textfield1.requestFocus();
      textfield2.setBackground( new Color(255,255,255) );
      textfield2.setText("4509");
      textfield3.setBackground( new Color(255,255,255) );
      textfield3.setText("n00b");
      textarea1.setBackground( new Color(0,0,0) );
      textarea1.setEditable(false);
      textarea1.setForeground( new Color(0,236,255) );
      textarea1.setLineWrap(true);
      scrollpane.setVerticalScrollBarPolicy( JScrollPane.VERTICAL_SCROLLBAR_ALWAYS );
      scrollpane.setHorizontalScrollBarPolicy( JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
      textarea2.setBackground( new Color(255,255,255) );
      textarea2.setBorder( BorderFactory.createTitledBorder( BorderFactory.createEtchedBorder(), "Enter message here" ) );
      textarea2.setLineWrap(true);
      button1.setBackground( new Color(204,187,255) );
      button1.setToolTipText("Send your message!");
     
      application.getContentPane().add( label1     );
      application.getContentPane().add( textfield1 );
      application.getContentPane().add( label2     );
      application.getContentPane().add( textfield2 );
      application.getContentPane().add( label4     );
      application.getContentPane().add( textfield3 );
      application.getContentPane().add( scrollpane );
      application.getContentPane().add( textarea2  );
      application.getContentPane().add( label3     );
      application.getContentPane().add( label5     );
      application.getContentPane().add( button1    );
     
      PortListener listener = new PortListener( 4509, textarea1 );
     
      listener.start();
     
      UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
     
      SwingUtilities.updateComponentTreeUI( application.getContentPane() );
    }
    catch ( Exception e )
    {
      e.printStackTrace( System.out );
      System.exit(1);
    }
  }
 
  static class JButtonCustom1 extends JButton implements ActionListener
  {
    String     user  = "";
    String     host  = "";
    String     port  = "";
   
    JTextArea  area1 = null;
    JTextArea  area2 = null;
    JTextField text1 = null;
    JTextField text2 = null;
    JTextField text3 = null;
   
    JButtonCustom1( String label, JTextArea prmArea1, JTextArea prmArea2, JTextField prmText1, JTextField prmText2, JTextField prmText3 )
    {
      this.setText( label );
      this.area1 = prmArea1;
      this.area2 = prmArea2;
      this.text1 = prmText1;
      this.text2 = prmText2;
      this.text3 = prmText3;
      this.addActionListener(this);
    }
   
    public void actionPerformed( ActionEvent e )
    {
      host = text2.getText();
     
      if ( host.equals("") )
      {
        area1.insert( "[SeraphIM] info: You must enter a recipient!\n", 0 );
      }
      else
      {
        user = text1.getText();
        port = text3.getText();
       
        if ( user.equals("") )
          user = "n00b";
       
        if ( port.equals("") )
          port = "4509";

        if ( area2.getText().equals("") )
        {
          area1.insert( "[SeraphIM] info: You must enter a message to send.\n", 0 );
        }
        else
        {
          String  message = "[" + user + "]: ";
         
          message += area2.getText();
         
          message += "|"; /* eof char */
         
          boolean sent    = false;
         
          char[]  chars   = new char[message.length()];
          byte[]  bytes   = new byte[message.length()];

          message.getChars( 0, message.length(), chars, 0 );

          for ( int i = 0; i < chars.length; i++ )
            bytes[i] = (byte)chars[i];

          try
          {  
            DatagramSocket socket = new DatagramSocket();

            socket.connect( new InetSocketAddress( host, Integer.parseInt(port) ) );

            DatagramPacket packet = new DatagramPacket( bytes, message.length(), new InetSocketAddress( host, Integer.parseInt(port) ) );

            packet.setData( bytes );

            socket.send( packet );
           
            sent = true;
          }
          catch ( ConnectException ce )
          {
            area1.insert( "[SeraphIM] err:  Could not contact " + host + "...\n", 0 );
            sent = false;
          }
          catch ( NumberFormatException nfe )
          {
            area1.insert( "[SeraphIM] err:  Invalid port\n", 0 );
            sent = false;
          }
          catch ( Exception exception )
          {
            exception.printStackTrace();
            sent = false;
          }
         
          if ( sent == true )
          {
            area1.insert( "[" + user + "]: " + area2.getText() + "\n", 0 );
          }
          else
          {
            area1.insert( "[SeraphIM] err:  Could not send...\n", 0 );
          }
        }

        area2.setText("");

        area2.requestFocus();
      }
    }
  }
 
  static class PortListener extends Thread
  {
    int       port    = 0;
    JTextArea text1   = null;
    byte[]    bytes   = new byte[100];
    String    output = "";
   
    PortListener( int port, JTextArea area1 )
    {
      this.port  = port;
      this.text1 = area1;
    }
   
    public void run()
    {
      try
      {
        DatagramSocket socket = new DatagramSocket( port );

        socket.setSoTimeout( 10 );

        while ( socket.isBound() )
        {
          DatagramPacket packet = new DatagramPacket( bytes, 100 );

          try
          {
            socket.receive( packet );
          }
          catch ( SocketTimeoutException ste ) { continue; }

          byte[] message = packet.getData();

          for ( int i = 0; i < message.length; i++ )
            if ( new Character( (char)message[i] ).toString().equals( "|" ) )
              break;
            else
              output += new Character( (char)message[i] ).toString();
         
          text1.insert( output + "\n", 0 );

          /* reset our receiving packet and string */
         
          output = "";
         
          bytes = new byte[100];

          packet.setData( bytes );
        }
      }
      catch ( Exception exception )
      {
        exception.printStackTrace( System.out );
      }
    }
  }
}
0
Comment
Question by:NorCal1876
  • 5
  • 4
  • 2
  • +2
13 Comments
 
LVL 35

Assisted Solution

by:girionis
girionis earned 100 total points
Comment Utility
That's how you can do it:

http://java.sun.com/developer/technicalArticles/Security/pwordmask/

> Is it possible to get the file into an .exe so I don't have to run it command line?

Yes you can but you break up the concept of java. WHy don't you create a jar file instead with a manifest that you can execute with a double-click?
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
0
 

Author Comment

by:NorCal1876
Comment Utility
>>
Yes you can but you break up the concept of java. WHy don't you create a jar file instead with a manifest that you can execute with a double-click?
<<

yeah i'd like to do that

just do the normal

jar -cvf <file name>

??

I'll take a look at that link.
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
> yeah i'd like to do that
>
> just do the normal
>
> jar -cvf <file name>
>
> ??

Yes but you will also need to include a manifest file that indicates your main class. For more info take a look here:

http://java.sun.com/docs/books/tutorial/jar/
http://java.sun.com/docs/books/tutorial/jar/basics/manifest.html
0
 

Author Comment

by:NorCal1876
Comment Utility
jar cvf SeraphIM.jar *.class

when I double click....

--Java Virtual Machine Launcher--

"Failed to load Main-Class manifest attribute SeraphIM.jar"

Any idea?
0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
What does your manifest look like?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:NorCal1876
Comment Utility
Main-Class: SeraphIM
0
 

Author Comment

by:NorCal1876
Comment Utility
Now it says... Main class not found?

The classes created when I compile are...

SeraphIM.class
SeraphIM$1.class
SeraphIM$PortListener.class
SeraphIM$JButtonCustom1.class

0
 
LVL 92

Assisted Solution

by:objects
objects earned 50 total points
Comment Utility
add a couple of empty lines to the end of your manifest
0
 
LVL 3

Accepted Solution

by:
CI-Ia0s earned 150 total points
Comment Utility
Manifest should be:

Main-Class: SeraphIM
Java-Bean: false

Name it mainclass.txt
Then do this:
jar cfv jarName.jar *.class
jar umfv mainclass.txt jarName.jar

Then double-click and enjoy! :)

P.S. I'm assuming you want to include all the class files in the directory you're creating the jar in. If not, just change the "*.class" to a list of classes you want to include.
0
 

Author Comment

by:NorCal1876
Comment Utility
Thanks guys!
0
 
LVL 35

Expert Comment

by:girionis
Comment Utility
:)
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
glad we could help :)
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now