?
Solved

Java Swing: Simple Password Window?

Posted on 2004-08-27
13
Medium Priority
?
414 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 2
  • +2
13 Comments
 
LVL 35

Assisted Solution

by:girionis
girionis earned 400 total points
ID: 11916561
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
ID: 11916570
0
 

Author Comment

by:NorCal1876
ID: 11916642
>>
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
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 35

Expert Comment

by:girionis
ID: 11916720
> 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
ID: 11916746
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
ID: 11917044
What does your manifest look like?
0
 

Author Comment

by:NorCal1876
ID: 11917536
Main-Class: SeraphIM
0
 

Author Comment

by:NorCal1876
ID: 11917545
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 200 total points
ID: 11918307
add a couple of empty lines to the end of your manifest
0
 
LVL 3

Accepted Solution

by:
CI-Ia0s earned 600 total points
ID: 11921917
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
ID: 11932240
Thanks guys!
0
 
LVL 35

Expert Comment

by:girionis
ID: 11933125
:)
0
 
LVL 92

Expert Comment

by:objects
ID: 11937596
glad we could help :)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses
Course of the Month13 days, 23 hours left to enroll

801 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