JOptionPane.showMessageDialog not working

I have create an application in NetBeans IDE on windows XP, all things are going right on windows XP, but when I migrate this jar file to linux my application is hanged when executing this line....
JOptionPane.showMessageDialog(ConfigTab, "Configuration saved.");
Is this issue is due to java version?....on windows my java version is jre1.5.0_06 and on linux jre1.5.0_08.

Faisal_Ahmed wrote:
I have create an application in NetBeans IDE on windows XP, all things are going right on windows XP, but when I migrate this jar file to linux my application is hanged when executing this line....
JOptionPane.showMessageDialog(ConfigTab, "Configuration saved."); Is this called on the EDT? Or better still, can you provide an SSCCE that shows the behaviour?
Is this issue is due to java version?No. It is most likely due to broken code.

Similar Messages

  • JOptionPane not working outside contractor.

    Hello
    I have a problem with my JOptionPane�s. If I use them within the constructor, it works fine with the correct decoration, format and graphic. I have a couple in methods within the same class and when I try and use a JOptionPane with these they do not display correctly. (no �ok� button, detonation or body text�only the title)
    Does anyone have any idea why this is and any ways around it?
    Thanks,
    Harold

    Sorry about that guys, I wrote this post after a very late night of programming:
    Here is the code:
    import javax.swing.JOptionPane;
    import ...
    public class GeneticAlgorithm extends JFrame implements ActionListener, WindowListener, ItemListener
         public GeneticAlgorithm()
             super("GeneticAlgorithm v3");
              //Sort screen size and position
              Dimension screenSize =      Toolkit.getDefaultToolkit().getScreenSize();
              if (screenSize.width < 1024 && screenSize.height < 768)
                   String resError = "Please note that this applecation is desgined to run\n with the resolution of 1024x768";
                   //WORKS FINE
                   JOptionPane.showMessageDialog(null, resError, "Screen Resolution Error", JOptionPane.ERROR_MESSAGE);
                   setSize(1024, 768);
         ...other Methods
         private boolean verifyStartParameters()
              boolean startSim = true;
              if (populationSize == 0)
                   //DOES NOT WORK
                   JOptionPane.showMessageDialog(null, "ERROR: Population Size = 0", "Population Size Error", JOptionPane.ERROR_MESSAGE);
                   startSim = false;
              if (generationSize == 0)
                   //DOES NOT WORK
                   JOptionPane.showMessageDialog(null, "ERROR: Generation Size = 0", "Generation Size Error", JOptionPane.ERROR_MESSAGE);
                   startSim = false;
              //DOES NOT WORK
              if (mutationRate == 0) {JOptionPane.showMessageDialog(null, "WARNING: Mutation Rate = 0", "Mutation Rate Warning", JOptionPane.WARNING_MESSAGE);}
              return startSim;
    }

  • Looks like JOptionPane setLocation did not work??

    Hi,Sir:
    I hope to put following JOptionPane dialog box in any place I want, such as 100,100 from top left origin in window.
    but it Looks like that JOptionPane setLocation did not work at all.
    what is wrong here?? is it a bug??
    How to solve it?
    Thanks
    import javax.swing.JOptionPane;
    public class Main {
      public static void main(String args[]) {
         JOptionPane jo= new  JOptionPane();
         jo.setLocation(100,100);
        String response = jo.showInputDialog
          ( "What is your first name?????" );
            System.out.println(response);
              

    is it a bug??Yes, its a bug with your code.
    showInputDialog(...) is a static method. It does not use the instance of the Object.
    Read the JOptionPane API. It explains how to create and use a JOption pane directly. Search for the text "Direct Use".

  • Mouse click on OK is not recognised in JOptionPane.showMessageDialog

    JOptionPane.showMessageDialog(frame, longMessage,
    shortMessage,JOptionPane.ERROR_MESSAGE);
    Strangely, when the above dialog pops up, I am unable to click OK using the mouse. But pressing enter / space on OK works. Also closing the window works. Could some one please tell me why click on OK doesn't work. I am JRE 1.4.1.02. This seems to have worked in JRE 1.3.1
    Your help is much appreciated.

    just try this buddy
    hope it fits yr requirement
    int result = JOptionPane.showConfirmDialog(null,
    "Do you want to exit ",
    "Exit ?",
    JOptionPane.YES_NO_OPTION);
    if (result == JOptionPane.YES_OPTION)
    System.exit(0);
    rgds
    ASHWIN

  • ActionListener not working with JFrame

    Hi,
    I've just rehashed an old bit of code to work with a new application but for some reason the JButton ActionListeners aren't working. However if I extend JDialog they work ok. The current code for JDialog is:-
    * File:     GUI.java
    * @author           ODL 3xx Distributed Systems - Team x
    * @description      This class provides a means for the user to
    *                    interact with file server.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class GUI extends JDialog implements ActionListener, ApplicationConstants {
        private JLabel label1, label2, label3, label4, label5;
        private JTextField field1, field2, field3, field4, field5;
        private JButton button1, button2, button3, button4, button5;
        private Container container;
        private Message sendFile;
        private String id;
        private String defaultText = "Enter file name here";
        private ClientForGUI client;
        private long timeStart, timeEnd;
        public GUI(JFrame frame) {
            super(frame, "File Server Actions", true);
            client = new ClientForGUI(this);
            try{
                   InetAddress addr = InetAddress.getLocalHost();
                   id = addr.getHostName() + Long.toString((new java.util.Date()).getTime());
                   if(client.connectToServer())
                   initGUI();
                   else{
                        JOptionPane.showMessageDialog(this, "Unable to connect to server", "Error", JOptionPane.WARNING_MESSAGE);
                        System.exit(0);
              catch(UnknownHostException uhe){
                   System.out.println("Unknown Host Exception");
            initGUI();
         * Create the GUI
        private void initGUI() {
            container = this.getContentPane();
            container.setLayout(null);
            label1 = new JLabel("Upload File");
            label2 = new JLabel("Rename File");
            label3 = new JLabel("Delete File");
            label4 = new JLabel("Create File");
            label5 = new JLabel("Download File");
            field1 = new JTextField();
            field2 = new JTextField();
            field3 = new JTextField();
            field4 = new JTextField();
            field5 = new JTextField();
            button1 = new JButton("Upload");
            button2 = new JButton("Rename");
            button3 = new JButton("Delete");
            button4 = new JButton("Create");
            button5 = new JButton("Download");
            label1.setBounds(10,10,80,20);
            label2.setBounds(10,40,80,20);
            label3.setBounds(10,70,80,20);
            label4.setBounds(10,100,80,20);
            label5.setBounds(10,130,80,20);
            field1.setBounds(100,40,200,20);
            field1.setText("Old name");
            field2.setBounds(310,40,200,20);
            field2.setText("New name");
            field3.setBounds(100,70,410,20);
            field3.setText(defaultText);
            field4.setBounds(100,100,410,20);
            field4.setText(defaultText);
            field5.setBounds(100,130,410,20);
            field5.setText(defaultText);
            button1.setBounds(100,10,100,20);
            button1.addActionListener(this);
            button2.setBounds(520,40,100,20);
            button2.addActionListener(this);
            button3.setBounds(520,70,100,20);
            button3.addActionListener(this);
            button4.setBounds(520,100,100,20);
            button4.addActionListener(this);
            button5.setBounds(520,130,100,20);
            button5.addActionListener(this);
            container.add(label1);
            container.add(button1);
            container.add(label2);
            container.add(field1);
            container.add(field2);
            container.add(button2);
            container.add(label3);
            container.add(field3);
            container.add(button3);
            container.add(label4);
            container.add(field4);
            container.add(button4);
            container.add(label5);
            container.add(field5);
            container.add(button5);
            setSize(640,200);
            setResizable(false);
            //Centre on the screen
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
              int x = (int) ((d.getWidth() - getWidth()) / 2);
              int y = (int) ((d.getHeight() - getHeight()) / 2);
              setLocation(x,y);
            setVisible(true);
        private void sendMessageToServer(Message message){
             message.setId(id);
             timeStart = new java.util.Date().getTime();
             try{
                  client.sendMessageToServer(message);
             catch(IOException ioe){
                  System.out.println("Unable to send message to server");
          * Perform some action based on user interaction
          * @param ae - ActionEvent
        public void actionPerformed(ActionEvent e){
            Object o = e.getSource();
            String name;
            if(o == button1){
                 try{
                        JFileChooser fc = new JFileChooser();
                       fc.setVisible(true);
                      //return value is what the user presses in the open File dialog
                      int returnVal = fc.showOpenDialog(null);
                      //if they choose OK
                      if (returnVal == JFileChooser.APPROVE_OPTION) {
                             //file now references the selected
                             File file = fc.getSelectedFile();
                             //create a FileInputStream from file location
                             FileInputStream fis = new FileInputStream(file);
                             // Create the byte array to hold the data, the same size as the file
                             byte [] fileBytes = new byte[(int)file.length()];
                              // Read in the bytes from the file into the byte array
                              int offset = 0;
                              int numRead = 0;
                              while (offset < fileBytes.length &&
                             (numRead=fis.read(fileBytes, offset, fileBytes.length-offset)) >=
                             0) {
                                  offset += numRead;
                             // Ensure all the bytes have been read in
                             if (offset < fileBytes.length) {
                                  throw new IOException("Could not completely read file "+file.getName());
                             fis.close();
                             sendFile = new Message(SEND_FILE, fileBytes);
                             sendFile.setId(id);
                             sendFile.setFileName(file.getName());
                             byte [] myarray = ConvertData.messageToBytes(sendFile);
                             Message sendWarning = new Message(SEND_FILE_WARNING);
                               sendWarning.setFileName(file.getName());
                              sendWarning.setFileSize(myarray.length);
                              try{
                                    sendMessageToServer(sendWarning);
                               catch(Exception excep){
                                    System.out.println(excep);
                   catch(FileNotFoundException fnfe){
                        System.out.println("File Not Found Exception");
                   catch(java.io.IOException ioe){
                        System.out.println("IO Exception");
            else if(o == button2){
                   name = field1.getText();
                   String name2 = field2.getText();
                   Message renameMessage = new Message(RENAME_FILE);
                   renameMessage.setFileName(name);
                   renameMessage.setFileRename(name2);
                   sendMessageToServer(renameMessage);
                   field1.setText("Old name");
                   field2.setText("New name");
            else if(o == button3){
                   name = field3.getText();
                   Message deleteMessage = new Message(DELETE_FILE);
                   deleteMessage.setFileName(name);
                   sendMessageToServer(deleteMessage);
                   field3.setText(defaultText);
            else if(o == button4){
                   name = field4.getText();
                   Message createMessage = new Message(CREATE_FILE);
                   createMessage.setFileName(name);
                   sendMessageToServer(createMessage);     
                   field4.setText(defaultText);     
            else if(o == button5){
                   name = field5.getText();
                   Message downloadMessage = new Message(REQUEST_FILE);
                   downloadMessage.setFileName(name);
                   sendMessageToServer(downloadMessage);
                   field5.setText(defaultText);          
        public void processServerMessage(Message message){
             switch(message.getMessageHeader()){
                   case SEND_FILE_WARNING:
                   //change the download size to file size plus max message size
                   client.setDownload((int)message.getFileSize(),true);
                   //turn message back around with acknowledgement header
                   message.setMessageHeader(SEND_FILE_ACK);
                   //send the message
                   try{
                        sendMessageToServer(message);
                   catch(Exception e){
                        System.out.println(e);
                   break;
                   //server has acknowledged that the client wishes to send a message
                   //so send the message
                   case SEND_FILE_ACK:
                   //send the message
                   try{
                        sendMessageToServer(sendFile);
                   catch(Exception e){
                        System.out.println(e);
                   break;
                   //server is sending the file to the client.
                   case SEND_FILE:
                   //reset the download size to default
                   client.setDownload(DEFAULT_MESSAGE_SIZE,false);
                   //get the file name
                   File f = new File(message.getFileName());
                   //create the file chooser
                   JFileChooser fc = new JFileChooser();
                   //set selected file as thoe one downloaded
                   fc.setSelectedFile(f);
                   //get the button hit by the user
                 int returnVal = fc.showSaveDialog(null);
                 //if button is OK
                  if (returnVal == JFileChooser.APPROVE_OPTION){
                       File temp = fc.getCurrentDirectory();
                       String [] files = temp.list();
                       java.util.List alist = java.util.Arrays.asList(files);
                       f = fc.getSelectedFile();
                       if(alist.contains(message.getFileName())){
                            if(JOptionPane.showConfirmDialog(null,
                                       message.getFileName() + " already exists. Are you sure you want to overwrite this file?",
                                       "Instant Messenger: Quit Program",
                                       JOptionPane.YES_NO_OPTION,
                                       JOptionPane.QUESTION_MESSAGE,
                                       null) == JOptionPane.YES_OPTION) {
                                            //f = fc.getSelectedFile();
                                            System.out.println(f.toString());
                                           //this is where the file is copied
                                           try{
                                                FileOutputStream fs = new FileOutputStream(f);
                                                 fs.write(message.getFile());
                                                 fs.close();
                                           catch(IOException e){
                                                System.out.println(e);
                            else fc.hide();
                       else{
                            System.out.println("Here " + f.toString());
                            try{
                                 FileOutputStream fs = new FileOutputStream(f);
                                  fs.write(message.getFile());
                                  fs.close();
                            catch(IOException e){
                                 System.out.println(e);
                  else fc.hide();
                  break;
                  case INFORMATION:
                  timeEnd = new java.util.Date().getTime();
                  Long rtrip = timeEnd - timeStart;
                  String str = Long.toString(rtrip);
                  double d = Double.valueOf(str).doubleValue();
                  String fullMessage = message.getMessage();
                  fullMessage += " The total time taken for the last request was " +
                  rtrip + " milliseconds" + " or roughly " + d/1000 + " seconds";
                   JOptionPane.showMessageDialog(null,fullMessage,"Information",JOptionPane.INFORMATION_MESSAGE);
                   break;          
    class TestGUI{
        public static void main(String [] args){
             JFrame frame = new JFrame();
             GUI myGUI = new GUI(frame);
    }     If I change the GUI constructor to empty and extend JFrame instead of JDialog and change the call to super the ActionListener stops working. I've never known this problem before (i.e. I always use e.getSource()). I've even cast the object to a JButton to ensure that the right button is pressed and it is all ok.
    Is there something fundamentally wrong when I make those simple changes to JFrame?
    Regards,
    Chris

    I think rather the approach is your action handling in terms of the buttons. The giant actionPerformed method is difficult to read and maintain.
    I would recommend the following things:
    1. Split your ActionListener into multiple smaller listeners. There's not really even a reason for the GUI class to be an action listener. Instead of having GUI implement ActionListener and trying to keep all of the functionality in one place, use anonymous classes:
    button3.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)
            name = field3.getText();
            Message deleteMessage = new Message(DELETE_FILE);
            deleteMessage.setFileName(name);
            sendMessageToServer(deleteMessage);
            field3.setText(defaultText);
    button4.addActionListener(new ActionListener()
        public void actionPerformed(ActionEvent e)
            name = field4.getText();
            Message createMessage = new Message(CREATE_FILE);
            createMessage.setFileName(name);
            sendMessageToServer(createMessage);     
            field4.setText(defaultText);
    2. Only use the == operator on primitives. There are very few cases in which you can properly use the == operator on objects and, in every one of those cases I have experienced, the equals(Object) method produces the same result.
    3. Name your variables more descriptively. There is really very little reason for your buttons to be named button1, button2, and so on. Give them names that mean something. For example, button1 should be named something like uploadFileButton or buttonUpload. That will give us significant information about what it is expected to do, whereas button1 does not. You may be able to remember what button1 does, but you wrote the code. I keep having to refer back to the instantiation of the button to get a hint as to what it does and, in a few months' time, so will you. :) The same goes for your labels and fields, as well.
    I'm not sure why you aren't getting the behavior you want. However, have you checked to determine that the event source of the button click is actually the button when the whole thing is inside of a JFrame? I would expect it to be, but you never know. This is why I recommend using different ActionListeners for each button. That way, you can be sure of what caused the event.
    Just my 2c. Good luck to you. :)

  • Get Images from jar. getResource() not working

    I've read some of the posts in the forum and I've tried the solutions but still cant get the images in my program.
    I'll write all the things I've tried (All of them works fine when I run them from bluej):
    1- The code used in the jar files in demo folder of jdk:
    /** Inside the main class: */
    private static ResourceBundle resources;  
        static {
            try {
                resources = ResourceBundle.getBundle("resources.Recursos", Locale.getDefault());
            } catch (MissingResourceException mre) {
                JOptionPane.showMessageDialog(new JFrame(), "ResourceBundle not found","Error",JOptionPane.ERROR_MESSAGE);
                System.exit(1);
    public String getResourceString(String nm)
            String str;
            try {       
                str = resources.getString(nm);   
                  } catch (MissingResourceException mre) {       
                str = null;
            return str;
        public URL getResource(String key)
            String name = getResourceString(key);
            if (name != null)
                URL url = getClass().getResource(name); //  Here is the exception
                return url;  
            return null;
        public ImageIcon loadImage(String image_name)
            URL image_url = null;    
            try
                image_url = getResource(image_name);             
                if (image_url != null)
                    return new ImageIcon(image_url);
                else
                return null;                  
            }catch(Exception e)
                JOptionPane.showMessageDialog(new JFrame(), e.getMessage() + "In load Image","Error",JOptionPane.ERROR_MESSAGE);
                return null;
    /** Inside the constructor */
    abrirButton = new JButton(loadImage("open"));
    }//End of the class}
    The ResourceBundle is a file named: Recursos.properties and it's in a folder inside the folder of my *.class and *.java And have this information:
    Title=Recursos
    ElementTreeFrameTitle=Elements
    ViewportBackingStore=false
    open=resources/open24.gif
    save=resources/saveAs24.gif
    cut=resources/cut24.gif
    copy=resources/copy24.gif
    paste=resources/paste24.gif
    analisis=resources/bean24.gif
    This one, runs with the jar, but the images are not in the buttons and I get the Dialog message telling me that there was an error in loadImage. Check that method. I used this dialogs to track the error and the exception it's generated by:
    URL url = getClass().getResource(name);
    in public URL getResource(String key) method.
    2- I also tried to follow the instructions of this article that describes how to get resources from jars:
    http://www.javaworld.com/javaworld/jw-07-1998/jw-07-jar-p2.html
    This is the first page of the article:
    http://www.javaworld.com/javaworld/jw-07-1998/jw-07-jar.html
    And I did something like this:
    /** Inside constructor */
    abrirButton = new JButton(new ImageIcon(getImageFromJAR("Imagenes/open24.gif")));
    /** Inside of my main class */
    public Image getImageFromJAR(String fileName)
               try{
               if( fileName == null ) return null;          
               Image image = null;
               Toolkit toolkit = Toolkit.getDefaultToolkit();          
                image = toolkit.getImage( getClass().getResource(fileName) );           
                return image;
                }catch(Exception exc){
                    JOptionPane.showMessageDialog(new JFrame(), "Exception loading the image","Error",JOptionPane.ERROR_MESSAGE);
                    return null;
    ...The images in this one are in the folder Imagenes inside the folder of my *.class and *.java
    This one work fine in bluej too, but the jar... It doesn't even start.
    3- And the last one.
    abrirButton = new JButton(new ImageIcon(getClass().getResource("Imagenes/open24.gif"));Works fine in bluej, not running in jar.
    Am I doing something wrong? Please somebody help me.
    thanks in advance

    Are you putting the image files inside the jar? If you are, then use "jar tf jarfile.jar" to display the contents of the jar and make sure the files are there and inside the right directory. If you are not, then you can not use getClass().getResource() from a jar file because it will look inside the jar file.
    If you are getting an error message, please post it.

  • Command button not working

    Hi,
    I have a
    <h:panelGrid><td><h:commandButton id="aButton" value="Add" action="#{hubreceivingbean.createRecord}" /></td></h:panelGrid> this is not working, I'm not sure what wrong I'm doing, my code is
    ============ hubReceiving.jsp=======================
    <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
    <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
    <%@ taglib uri="http://jakarta.apache.org/struts/tags-tiles" prefix="tiles" %>
    <tiles:importAttribute scope="request"/>
    <f:view>
    <f:loadBundle basename="com.fcpa.him.columnheading" var="chdr"/>
    <f:loadBundle basename="com.fcpa.him.Messages" var="msg"/>
    <div id="location"></div>
    <div class="bfrm" style="width: 720px;" >
    <div style="height: 600px" class="cv_c">
    <h:form id="rcvTxn">
    <h:panelGroup>
    <h:panelGrid columns="1">
    <h:panelGrid>
    <h:dataTable >
    <h:column>
    <f:facet name="header">
    <td> <h:outputFormat style="width: 730px;" value="Receiving"/></td>
    </f:facet>
    </h:column>
    </h:dataTable>
    </h:panelGrid>
    <h:panelGrid columns="3">
    <h:panelGrid columns="5" style="width: 560px">
    <h:column>
    <h:panelGrid><td><h:outputText id="errorMessage" value="#{hubreceivingbean.errorMessage}" style="color: red; font-weight: bold;" /></td></h:panelGrid>
    </h:column>
    <h:column>
    <h:panelGrid>
    <h:panelGrid><td><h:outputText id="hRcvDate" value="Receiving Date:" style="width: 90px" /></td></h:panelGrid>
    <h:panelGrid><td><h:outputText id="hHubName" value="Receiving At:" style="width: 90px" /></td></h:panelGrid>
    <h:panelGrid><td><h:outputText id="hPackageType" value="Package Type:" style="width: 90px" /></td></h:panelGrid>
    <h:panelGrid><td><h:outputText id="hPackageValue" value="Scan / Enter:" style="width: 90px" /></td></h:panelGrid>
    </h:panelGrid>
    </h:column>
    <h:column>
    <h:panelGrid>
    <h:panelGrid><td><h:outputText id="vRcvDate" value="#{hubreceivingbean.date}" style="width: 130px"/></td></h:panelGrid>
    <h:panelGrid><td><h:selectOneMenu id="vHubName" value="#{hubreceivingbean.hubName}" style="width: 130px">
    <f:selectItems value="#{hubreceivingbean.hubList}"/>
    </h:selectOneMenu></td></h:panelGrid>
    <h:panelGrid><td><h:selectOneMenu id="vPackageType" value="#{hubreceivingbean.sourceType}" style="width: 130px" onchange="submit()" >
    <f:selectItems value="#{hubreceivingbean.sourceTypeList}" />
    </h:selectOneMenu></td></h:panelGrid>
    <h:panelGrid><td><h:inputText id="vPackageValue" value="#{hubreceivingbean.sourceValue}" style="width: 130px" /></td></h:panelGrid>
    </h:panelGrid>
    </h:column>
    <h:column>
    <h:panelGrid>
    <h:panelGrid><td><h:outputText style="width: 80px"/></td></h:panelGrid>
    <h:panelGrid><td><h:outputText id="hTxnNum" value="Txn ID:" style="width: 80px"/></td></h:panelGrid>
    <h:panelGrid><td><h:outputText id="hPartNumber" value="Part Number:" style="width: 80px; #{hubreceivingbean.componetEnableDisableStyle};"/></td></h:panelGrid>
    <h:panelGrid><td><h:outputText id="hQty" value="Quantity:" style="width: 80px; #{hubreceivingbean.componetEnableDisableStyle};"/></td></h:panelGrid>
    </h:panelGrid>
    </h:column>
    <h:column>
    <h:panelGrid>
    <h:panelGrid><td><h:outputText style="width: 130px" /></td></h:panelGrid>
    <h:panelGrid><td><h:inputText id="vTxnNum" value="#{hubreceivingbean.rcvTxnHeaderID}" style="width: 130px" /></td></h:panelGrid>
    <h:panelGrid><td><h:inputText id="vPartNum" value="#{hubreceivingbean.partNumber}" style="width: 130px; #{hubreceivingbean.componetEnableDisableStyle};" /></td></h:panelGrid>
    <h:panelGrid><td><h:inputText id="vQty" value="#{hubreceivingbean.quantity}" style="width: 130px; #{hubreceivingbean.componetEnableDisableStyle};" /></td></h:panelGrid>
    </h:panelGrid>
    </h:column>
    </h:panelGrid>
    <h:panelGrid>
    <f:subview id="rtMenu">
    <tiles:insert definition="mainMenu" flush="false"/>
    </f:subview>
    </h:panelGrid>
    </h:panelGrid>
    <h:panelGrid><td><h:commandButton id="aButton" value="Add" action="#{hubreceivingbean.createRecord}" /></td></h:panelGrid>
    <h:panelGrid>
    <h:dataTable styleClass="standard">
    <h:column >
    <f:facet name="header">
    <td> <h:outputFormat style="width: 70px; " value="#{chdr.rcvRefType}"/></td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 80px;" value="#{chdr.rcvRefTypeValue}"/> </td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 80px;" value="#{chdr.palletNumber}"/> </td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 175px;" value="#{chdr.partNumber}"/></td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 75px;" value="#{chdr.asnQty}"/> </td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 75px;" value="#{chdr.rcvQty}"/> </td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 100px;" value="#{chdr.remarks}"/> </td>
    </f:facet>
    </h:column>
    <h:column>
    <f:facet name="header">
    <td> <h:outputText style="width: 50px;" value="#{chdr.delete}"/> </td>
    </f:facet>
    </h:column>
    </h:dataTable>
    </h:panelGrid>
    <h:panelGrid styleClass="scrollPane" columns="1" style="width: 720px;">
    <h:panelGroup>
    <f:verbatim><DIV STYLE="overflow: auto; height: 170px;" styleClass="standard"></f:verbatim>
    <h:dataTable value="#{hubreceivingbean.rcvDataArray}" var="databean" styleClass="standard">
    <h:column>
    <h:outputText style="width: 70px;" value="#{databean.referenceType}"/>
    </h:column>
    <h:column>
    <h:outputText style="width: 80px;" value="#{databean.referenceValue}"/>
    </h:column>
    <h:column>
    <h:outputText style="width: 80px;" value="#{databean.palletNumber}"/>
    </h:column>
    <h:column>
    <h:outputText style="width: 175px;" value="#{databean.partNumber}"/>
    </h:column>
    <h:column>
    <h:outputText style="width: 75px;" value="#{databean.asnQuantity}" />
    </h:column>
    <h:column>
    <h:inputText id="rcvQty" style="width: 75px;" value="#{databean.rcvQuantity}" required="true"/>
    <h:message for="rcvQty" errorClass="errors" />
    <f:attribute name="rcvQty" value="Please Enter" />
    </h:column>
    <h:column>
    <h:inputText style="width: 100px;" value="#{databean.rcvComments}" />
    </h:column>
    </h:dataTable>
    <f:verbatim></DIV></f:verbatim>
    </h:panelGroup>
    </h:panelGrid>
    </h:panelGrid>
    </h:panelGroup>
    </h:form>
    </div>
    </div>
    </f:view>
    ====================HubReceivingBean.java=================
    * HubReceivingBean.java
    * Created on February 1, 2006, 6:09 PM
    * To change this template, choose Tools | Options and locate the template under
    * the Source Creation and Management node. Right-click the template and choose
    * Open. You can then make changes to the template in the Source Editor.
    package com.fcpa.him;
    * @author vburla
    import java.sql.*;
    import java.util.*;
    import java.text.*;
    import java.io.*;
    import java.util.Date;
    import javax.faces.model.SelectItem;
    import javax.faces.application.*;
    import javax.faces.context.FacesContext;
    import java.util.Locale;
    import javax.servlet.jsp.jstl.sql.ResultSupport;
    import javax.servlet.jsp.jstl.sql.Result;
    import javax.faces.component.UIComponent;
    import javax.faces.component.UIComponentBase;
    import javax.faces.component.UIInput;
    import javax.faces.component.UIViewRoot;
    import javax.faces.validator.*;
    import javax.faces.el.ValueBinding;
    import java.io.Serializable;
    import javax.swing.JOptionPane;
    import java.net.*;
    import com.fcpa.reportal.*;
    import com.fcpa.eapps.*;
    public class HubReceivingBean {
    private String sourceType;
    private String sourceValue;
    private String rcvTxnHeaderID;
    private Date date = new Date();
    private static ArrayList sourceList;
    private static ArrayList hubList;
    private SysLogger log;
    private JDBCConnPool db;
    private String hubName;
    private boolean hubNameEditable =true;
    private ArrayList rcvDataArray = new ArrayList();
    private String componetEnableDisableStyle = "display:none";
    private String txnRefEnableDisable = "display:none";
    private String partNumber;
    private String quantity;
    private String useDataSource = "Y";
    private String errorMessage;
    //private static final String[] SOURCE_TYPE = { "CARTON", "PALLET", "INVOICE","IO"};
    //private static final String[] COLUMN_NAMES = {"Ref_Type","Ref_Value","Part_Number","ASN_Qty","RCV_Qty","Notes"};
    /**Create connection */
    public void setJdbcConnPoolClass(JDBCConnPool j) {
    this.db = j;
    public JDBCConnPool getJdbcConnPoolClass() {
    return this.db;
    public void setSysLoggerClass(SysLogger s) {
    this.log = s;
    public SysLogger getSysLoggerClass() {
    return this.log;
    /** Creates a new instance of HubReceivingBean */
    public HubReceivingBean(){
    private void fillRcvDataArray() throws Exception{
    if ( (getRcvTxnHeaderID()!="") && (getRcvTxnHeaderID()!=null) ){
    String strSQLstr = "SELECT lines.txn_line_id Txn_Line_ID, lines.reference_type Ref_Type,lines.reference_value Ref_Value,"+
    " lines.pallet_number Pallet_Number, lines.part_number Part_Number,lines.asn_quantity ASN_Qty,"+
    " lines.received_quantity RCV_Qty,lines.comments Notes "+
    " FROM hif_rcv_txn_headers headers, hif_rcv_txn_lines lines "+
    " WHERE headers.txn_header_id = lines.txn_header_id "+
    " AND headers.txn_header_id = "+getRcvTxnHeaderID()+
    " AND nvl(headers.txn_complete_flag,'N') = 'N' "+
    " ORDER BY lines.txn_line_id desc";
    System.out.println("Inside fill data-strSQLstr: "+strSQLstr);
    ResultSet rs = db.getResultSet(strSQLstr);
    while (rs.next()){
    RcvTableDataBean bean = new RcvTableDataBean();
    bean.setTxnLineID(rs.getString("Txn_Line_ID"));
    bean.setReferenceType(rs.getString("Ref_Type"));
    bean.setReferenceValue(rs.getString("Ref_Value"));
    bean.setPalletNumber(rs.getString("Pallet_Number"));
    bean.setPartNumber(rs.getString("Part_Number"));
    bean.setAsnQuantity(rs.getString("ASN_Qty"));
    bean.setRcvQuantity(rs.getString("RCV_Qty"));
    bean.setRcvComments(rs.getString("Notes"));
    rcvDataArray.add(bean);
    public ArrayList getRcvDataArray()throws Exception {
    rcvDataArray.clear();
    fillRcvDataArray();
    return rcvDataArray;
    // PROPERTY: current date
    public void setDate(Date newValue) { date = newValue; }
    public String getDate() {
    Date now = new Date();
    DateFormat df = DateFormat.getDateInstance();
    String s = df.format(now);
    System.out.println("Today is " + s);
    return s;
    // PROPERTY: Hub Name
    public void setHubName(String newValue) {
    // System.out.println("Inside setSourceType");
    hubName = newValue; }
    public String getHubName() {
    //System.out.println("Inside getSourceType");
    return hubName; }
    // PROPERTY: source type
    public void setSourceType(String newValue) {
    // System.out.println("Inside setSourceType");
    sourceType = newValue; }
    public String getSourceType() {
    //System.out.println("Inside getSourceType");
    return sourceType; }
    // PROPERTY: source value
    public void setSourceValue(String newValue) {
    //System.out.println("Inside setSourceValue");
    sourceValue = newValue; }
    public String getSourceValue() {
    //System.out.println("Inside getSourceValue");
    return sourceValue; }
    // PROPERTY: source type
    public void setRcvTxnHeaderID(String newValue) {
    // System.out.println("Inside setSourceType");
    rcvTxnHeaderID = newValue; }
    public String getRcvTxnHeaderID() {
    //System.out.println("Inside getSourceType");
    return rcvTxnHeaderID; }
    // PROPERTY: Enable Disable
    public void setComponetEnableDisableStyle(String newValue) {
    // System.out.println("Inside setSourceType");
    componetEnableDisableStyle = newValue; }
    public String getComponetEnableDisableStyle() {
    //System.out.println("Inside getSourceType");
    return componetEnableDisableStyle; }
    // PROPERTY: Enable Disable Txn Ref
    public void setTxnRefEnableDisable(String newValue) {
    // System.out.println("Inside setSourceType");
    txnRefEnableDisable = newValue; }
    public String getTxnRefEnableDisable() {
    //System.out.println("Inside getSourceType");
    return txnRefEnableDisable; }
    // PROPERTY: part Number
    public void setPartNumber(String newValue) {
    // System.out.println("Inside setSourceType");
    partNumber = newValue; }
    public String getPartNumber() {
    //System.out.println("Inside getSourceType");
    return partNumber; }
    // PROPERTY: Quantity
    public void setQuantity(String newValue) {
    // System.out.println("Inside setSourceType");
    quantity = newValue; }
    public String getQuantity() {
    //System.out.println("Inside getSourceType");
    return quantity; }
    // PROPERTY: UseData Source
    public void setUseDataSource(String newValue) {
    // System.out.println("Inside setSourceType");
    useDataSource = newValue; }
    public String getUseDataSource() {
    //System.out.println("Inside getSourceType");
    return useDataSource; }
    // PROPERTY: Error Message
    public void setErrorMessage(String newValue) {
    // System.out.println("Inside setSourceType");
    errorMessage = newValue; }
    public String getErrorMessage() {
    //System.out.println("Inside getSourceType");
    return errorMessage; }
    // PROPERTY: User ID
    public String getUserID() {
    // System.out.println("Inside setSourceType");
    return("1048"); }
    // PROPERTY: Hub Name Editable
    public boolean isHubNameEditable() {
    return hubNameEditable; }
    public void setHubNameEditable(boolean newValue) {
    hubNameEditable = newValue; }
    //PROPERTY: Hub List
    public Collection getHubList() throws Exception {
    log.general("Inside getSourceTypeList");
    String strSQLstr = " SELECT hub_name hubName "+
    " FROM eaf_hub_master "+
    " WHERE nvl(enabled_flag,'N') = 'Y' "+
    " AND nvl(end_date_active,sysdate+1) > sysdate";
    ResultSet sl = db.getResultSet(strSQLstr);
    hubList = new ArrayList();
    int hubCt = 0;
    while (sl.next()){
    hubCt = hubCt + 1;
    hubList.add(new SelectItem(sl.getString("hubName")));
    //System.out.println("hubCt: "+hubCt);
    if (hubCt > 1) {
    setHubNameEditable(true);
    // System.out.println("Setting setHubNameEditable as true");
    } else{
    setHubNameEditable(false);
    // System.out.println("Setting setHubNameEditable as false");
    setHubName("One Hub");
    return(hubList);
    //PROPERTY: source List
    public Collection getSourceTypeList() throws Exception {
    System.out.println("Inside getSourceType:"+getSourceType());
    String sourceType = getSourceType();
    System.out.println("sourceType:"+sourceType);
    if (sourceType != null){
    if (sourceType.equals("OTHERS")){
    System.out.println("Inside getSourceType for OTHERS");
    setComponetEnableDisableStyle("");
    setUseDataSource("N");
    }else {
    System.out.println("Inside getSourceType for not OTHERS");
    setComponetEnableDisableStyle("display:none");
    setUseDataSource("Y");
    }else{
    System.out.println("Source Type is null");
    setComponetEnableDisableStyle("display:none");
    setUseDataSource("Y");
    setErrorMessage(null);
    log.general("Inside getSourceTypeList");
    String strSQLstr =" SELECT lookup_code sourceType "+
    " FROM hif_lookup_values "+
    " WHERE lookup_type = 'RCV_SOURCE_TYPE' "+
    " AND nvl(enabled_flag,'N') = 'Y' "+
    " AND nvl(end_date_active,sysdate+1) > sysdate ";
    ResultSet sl = db.getResultSet(strSQLstr);
    sourceList = new ArrayList();
    while (sl.next()){
    sourceList.add(new SelectItem(sl.getString("sourceType")));
    return(sourceList);
    //PROPERTY: validate and insert data
    public void createRecord() throws Exception{
    updateTxn();
    System.out.println("Inside createRecord");
    System.out.println("getSourceValue()"+getSourceValue());
    if ( !(getSourceValue()!="")){
    System.out.println("getSourceValue()"+getSourceValue());
    //JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Please Scan / Enter value for "+getSourceType());
    } else if ((getUseDataSource()=="N") &&
    (!(getPartNumber()!="")||!(getQuantity()!=""))) {
    System.out.println( "Please Enter Part Number and Quantity");
    //JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Please Enter Part Number and Quantity" );
    else{
    Connection con = db.getConnection();
    try{
    try{
    System.out.println("SourceValue: "+sourceValue);
    System.out.println("Hub Name"+getHubName());
    String insertQuery = "begin "+
    " hif_rcv_pkg.create_record(?,?,?,?,?,?,?,?,?,?,?);"+
    "end; ";
    CallableStatement cs = con.prepareCall(insertQuery);
    cs.registerOutParameter(1,Types.VARCHAR);
    cs.registerOutParameter(2,Types.VARCHAR);
    cs.registerOutParameter(3,Types.VARCHAR);
    cs.setString(3,getRcvTxnHeaderID());
    cs.setString(4,getIP());
    cs.setString(5,getUserID());
    cs.setString(6,getHubName());
    cs.setString(7,getSourceType());
    cs.setString(8, getSourceValue());
    cs.setString(9,getUseDataSource());
    cs.setString(10,getPartNumber());
    cs.setString(11,getQuantity());
    cs.execute();
    con.commit();
    String txnHeaderID = cs.getString(3);
    String errorCode = cs.getString(1);
    String errorMessage = cs.getString(2);
    if (errorMessage != null) {
    setErrorMessage(errorMessage);
    } else{
    if (txnHeaderID != null ){
    setRcvTxnHeaderID(txnHeaderID);
    txnRefEnableDisable= " ";
    setComponetEnableDisableStyle("display:none");
    setUseDataSource("Y");
    setSourceValue(null);
    setPartNumber(null);
    setQuantity(null);
    }catch (Exception e) {
    System.out.println("Error "+ e);
    } finally {
    con.close();
    public void updateRcvQty() throws Exception{
    System.out.println("Inside updateRcvQty");
    //System.out.println("RcvRecord: "+rcvRecord.toString());
    updateTxn();
    Connection con = db.getConnection();
    try{
    try{
    System.out.println("SourceValue: "+sourceValue);
    System.out.println("getRcvTxnHeaderID: "+getRcvTxnHeaderID());
    System.out.println("");
    String insertQuery = "begin "+
    " hif_rcv_pkg.update_rcv_qty (?,?,?,?,?,?,?);"+
    "end; ";
    CallableStatement cs = con.prepareCall(insertQuery);
    cs.registerOutParameter(1,Types.VARCHAR);
    cs.registerOutParameter(2,Types.VARCHAR);
    cs.setString(3,getRcvTxnHeaderID());
    cs.setString(4,getIP());
    cs.setString(5,getUserID());
    cs.setString(6,getSourceType());
    cs.setString(7,getSourceValue());
    cs.executeUpdate();
    con.commit();
    //setSourceValue(null);
    }catch (Exception e) {
    System.out.println("Error "+ e);
    } finally {
    con.close();
    public void deleteRecord() throws Exception{
    updateTxn();
    System.out.println("Inside deleteRecord");
    //System.out.println("RcvRecord: "+rcvRecord.toString());
    Connection con = db.getConnection();
    try{
    try{
    System.out.println("SourceValue: "+sourceValue);
    System.out.println("");
    String insertQuery = "begin "+
    " hif_rcv_pkg.delete_record (?,?,?,?,?,?,?);"+
    "end; ";
    CallableStatement cs = con.prepareCall(insertQuery);
    cs.registerOutParameter(1,Types.VARCHAR);
    cs.registerOutParameter(2,Types.VARCHAR);
    cs.setString(3,getRcvTxnHeaderID());
    cs.setString(4,getIP());
    cs.setString(5,getUserID());
    cs.setString(6,getSourceType());
    cs.setString(7, getSourceValue());
    cs.executeUpdate();
    con.commit();
    setSourceValue(null);
    }catch (Exception e) {
    System.out.println("Error "+ e);
    } finally {
    con.close();
    public void updateTxn()throws Exception{
    System.out.println("Inside updateTxn");
    int len = rcvDataArray.size();
    Connection con = db.getConnection();
    try{
    for (int i = 0; i < len; i++) {
    RcvTableDataBean bean = (RcvTableDataBean)rcvDataArray.get(i);
    try{
    System.out.println("Updateing Reference Value: "+ bean.getReferenceValue());
    System.out.println("Updateing Comment Value: "+ bean.getRcvComments());
    System.out.println("Updateing Receiving Qty: "+ bean.getRcvQuantity());
    System.out.println("Updateing Receiving Qty: "+ bean.getRcvQuantity());
    String updateQuery = "begin "+
    " hif_rcv_pkg.update_txn(?,?,?,?,?,?,?,?,?);"+
    "end; ";
    CallableStatement cs = con.prepareCall(updateQuery);
    cs.registerOutParameter(1,Types.VARCHAR);
    cs.registerOutParameter(2,Types.VARCHAR);
    cs.setString(3,getIP());
    cs.setString(4,getUserID());
    cs.setString(5,getRcvTxnHeaderID());
    cs.setString(6,bean.getTxnLineID());
    cs.setString(7,bean.getReferenceValue());
    cs.setString(8,bean.getRcvQuantity());
    cs.setString(9,bean.getRcvComments());
    cs.execute();
    con.commit();
    }catch (Exception e) {
    System.out.println("Error "+ e

    1) Please use code tags in the future. Lengthy, unformatted code isn't likely to read be most people here who are trying to help you for free.
    2) Next time, please use a short, compilable example that demonstrates your problem. Again, that is a lot of code to expect a volunteer to debug.
    3) This does not appear to be a Swing question. Perhaps you should have posted this in one of the web-based forums.
    Good luck.

  • ActionPerformed method not working when applet is loaded in browser window.

    Hey there guys. I need urgent help from anybody who has experience in deploying websites whose code is in java.
    I am having two problems as mentioned below...
    first, I have made a simple login screen using java swing and JApplet. there is a single button to login. the action performed for this button accesses a private method to check the username and password which are there in atext file. the applet is working perfectly in appletviewer but when i load the applet in a Internet Explorer window using HTML's Applet tag, the button is giving no response at all even when i enter the correct username and password.
    I guess it is either not calling the private function that is checking the username and password from the tes=xt file or it can not access the file. Please help as soon as possible as this is related to my college project.
    I am attaching the code herewith. Suggestions to improve the coding are also welcome.
    the second problem is that while writing my second program for generating a form which registers a user the html is not at all loading the applet into the browser and also if im trying to access a file to write all the details into the console is showing numerous amount of error after i press the button which i can't not understand. the only thing i can understand is that it is related to file access permissions. If anybody could put some light on the working of worker threads and thread safe activities of SwingUtilities.invokeandWait method it would be really appreciable.
    import java.io.*;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.plaf.*;
    <applet code = "UserLogin" width = 300 height = 150>
    </applet>
    public class UserLogin extends JApplet implements ActionListener, KeyListener {
         private JLabel lTitle;
         private JLabel lUsername, lPassword;
         private JTextField tUsername;
         private JPasswordField tPassword;
         private JButton bLogin;
         private JLabel lLinkRegister, lLinkForgot;
         private JLabel lEmpty = new JLabel(" ", JLabel.CENTER);
         private JPanel panel1, panel2;
         public void init() {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                   SwingUtilities.invokeAndWait(new Runnable() {
                        public void run() {
                             LoginGUI();
              catch(Exception e) {
                   e.printStackTrace();
         public void start() {
              setVisible(true);
         public void stop() {
              setVisible(false);
         private void LoginGUI() {
              super.setSize(300, 150);
              super.setBackground(Color.white);
              lTitle = new JLabel("<HTML><BODY><FONT FACE = \"COURIER NEW\" SIZE = 6 COLOR = BLUE>Login</FONT></BODY></HTML>", JLabel.CENTER);
              lUsername = new JLabel("Username : ", JLabel.CENTER);
              lPassword = new JLabel("Password : ", JLabel.CENTER);
              tUsername = new JTextField(15);
              tPassword = new JPasswordField(15);
              bLogin = new JButton("LOGIN");
    //          bLogin.setEnabled(false);
              bLogin.addActionListener(this);
              bLogin.addKeyListener(this);
              panel2 = new JPanel();
              GridBagLayout gbag = new GridBagLayout();
              GridBagConstraints gbc = new GridBagConstraints();
              panel2.setLayout(gbag);
              panel2.addKeyListener(this);
              gbc.anchor = GridBagConstraints.CENTER;
              panel2.setMinimumSize(new Dimension(300, 200));
              panel2.setMaximumSize(panel2.getMinimumSize());
              panel2.setPreferredSize(panel2.getMinimumSize());
              gbc.gridx = 1;
              gbc.gridy = 1;
              gbag.setConstraints(lUsername,gbc);
              panel2.add(lUsername);
              gbc.gridx = 2;
              gbc.gridy = 1;
              gbag.setConstraints(tUsername,gbc);
              panel2.add(tUsername);
              gbc.gridx = 1;
              gbc.gridy = 2;
              gbag.setConstraints(lPassword,gbc);
              panel2.add(lPassword);
              gbc.gridx = 2;
              gbc.gridy = 2;
              gbag.setConstraints(tPassword,gbc);
              panel2.add(tPassword);
              gbc.gridx = 2;
              gbc.gridy = 3;
              gbag.setConstraints(lEmpty,gbc);
              panel2.add(lEmpty);
              gbc.gridx = 2;
              gbc.gridy = 4;
              gbag.setConstraints(bLogin,gbc);
              panel2.add(bLogin);
              panel1 = new JPanel(new BorderLayout());
              panel1.add(lTitle, BorderLayout.NORTH);
              panel1.add(panel2, BorderLayout.CENTER);
              add(panel1);
              setVisible(true);
         public void keyReleased(KeyEvent ke) {}
         public void keyTyped(KeyEvent ke) {}
         public void keyPressed(KeyEvent ke) {
              if(ke.getKeyCode() == KeyEvent.VK_ENTER){
                   String username = tUsername.getText();
                   String password = new String(tPassword.getPassword());
                   if(username.length() == 0 || password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(),"You must enter a username and password to login", "Error", JOptionPane.ERROR_MESSAGE);
                   else {
                        boolean flag = checkUsernamePassword(username, password);
                        if(flag)
                             JOptionPane.showMessageDialog(new JFrame(),"Username and Password Accepted", "Access Granted", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(new JFrame(),"Username or password Incorrect", "Access Denied", JOptionPane.INFORMATION_MESSAGE);
         public void actionPerformed(ActionEvent ae) {
              String gotCommand = ae.getActionCommand();
              if(gotCommand.equals("LOGIN")) {
                   String username = tUsername.getText();
                   String password = new String(tPassword.getPassword());
                   if(username.length() == 0 || password.length() == 0) {
                        JOptionPane.showMessageDialog(new JFrame(),"You must enter a username and password to login", "Error", JOptionPane.ERROR_MESSAGE);
                   else {
                        boolean flag = checkUsernamePassword(username, password);
                        if(flag)
                             JOptionPane.showMessageDialog(new JFrame(),"Username and Password Accepted", "Access Granted", JOptionPane.INFORMATION_MESSAGE);
                        else
                             JOptionPane.showMessageDialog(new JFrame(),"Username or password Incorrect", "Access Denied", JOptionPane.INFORMATION_MESSAGE);
         private boolean checkUsernamePassword(String username, String password) {
              String user = null, pswd = null;
              try {
                   FileInputStream fin = new FileInputStream("@data\\userpass.txt");
                   DataInputStream din = new DataInputStream(fin);
                   BufferedReader brin = new BufferedReader(new InputStreamReader(din));
                   user = (String) brin.readLine();
                   pswd = (String) brin.readLine();
              catch(IOException ioe) {
                   ioe.printStackTrace();
              if(username.equals(user) && password.equals(pswd))
                   return true;
              else
                   return false;
    }PLEASE HELP ME GUYS......

    RockAsh wrote:
    Hey Andrew, first of all sorry for that shout, it was un-intentional as i am new to posting topics on forums and didn't new that this kind of writing is meant as shouting. Cool.
    Secondly thank you for taking interest in my concern.No worries.
    Thirdly, as i mentioned before, I am reading i file for checking of username and password. the file is named as "userpass.txt" and is saved in the directory named "@data" which is kept in the same directory in which my class file resides.OK - server-side. That makes some sense, and makes things easier. The problem with your current code is that the applet will be looking for that directory on the end user's local file system. Of course the file does not exist there, so the applet will fail unless the the end user is using the same machine as the server is coming from.
    To get access to a resource on the server - the place the applet lives - requires an URL. In applets, URLs are relatively easy to form. It might be something along the lines of
    URL urlToPswrd = new URL(getCodeBase(), "@data/userpass.txt");
    InputStream is = urlToPswrd.openStream();
    DataInputStream din = new DataInputStream(is);
    So the problem is that it is reading the file and showing the specific output dialog box when i run it through appletviewer.. Huhh. What version of the SDK are you using? More recent applet viewers should report security exceptions if the File exists.
    ..but the same is not happening when i launch the applet in my browser window using the code as written belowHave you discovered how to open the Java Console in the browser yet? It is important.
    Also the answer to your second question
    Also, the entire approach to storing/restoring the password is potentially wrong. For instance, where is it supposed to be stored, on the server, or on the client?is that, as of now it is just my college project so all the data files and the username and password wiles will be stored on my laptop only i.e. on the client only. no server involved.OK, but understand that an applet ultimately does not make much sense unless deployed through a server. And the entire server/client distinction becomes very important, since that code would be searching for a non-existent file on the computer of the end user.

  • If condtion  not working  in blank text field

    I want that when the text field is blank it should go to the else if portion of the code below:
    JTextField tf1=new JTextField(15);
    if (tf1.getText() != null)
    JOptionPane.showMessageDialog(tf1, "insert value in the range of a-z,A-Z,0-9");
    }                          else if (tf1.getText() == null)
                             System.out.println("fdsafasdfasdfsdf");
    System.out.println("1234");
                                                      JOptionPane.showMessageDialog(tf1,"Enter SmartTextID");
    but control never goes to ==null,even i have initilaized textField with a text then also when i chk with tf1.getText() == "assigned text", its not working.
    plz send me the correct code for this
    thanx..

    if ( textField.getText().trim().equals("") );

  • Writing to file not working, might be 1.4 problem

    Hi:
    I am trying to writing the content of a JTextArea onto a file. The content is pretty big, has newlines. I have been struggling with this in 1.4 and it just doesn't write to the file I specified. In 1.3, it works great. Here is the rough code:
    public void loadDisplayFrame()
         JMenuItem save = new JMenuItem("Save");
         //Save Action Listener
         save.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
               String filePath;
               //Save the  gsgl sample file
               if(filePath!=null && filePath.length()>0)
                  try
                  int state = saveChooser.showSaveDialog(null);
                  File f;
                  f = saveChooser.getSelectedFile();
                  if(f!=null && state==JFileChooser.APPROVE_OPTION)
                        savedName = f.getPath();
                        if(!savedName.endsWith(".gsgl"))
                           JOptionPane.showMessageDialog(null, "Invalid file name", "error", JOptionPane.ERROR_MESSAGE);
                        }else
                           processSaving();
                        }catch(Exception e)
                            e.printStackTrace();
                    }else
                        JOptionPane.showMessageDialog(null, "Please load a file first", "error",
                            JOptionPane.ERROR_MESSAGE);
              myMenu.add(save);
              JMenuBar displayMenu = new JMenuBar();
              displayMenu.add(myMenu);
      public void processSaving()
             try
                 System.out.println("Saved Name is " + savedName);
               PrintWriter out
               = new PrintWriter(new BufferedWriter(new FileWriter(savedName)));
               //name of TextArea is <display>
               String saveCode = display.getText();
              System.out.println(saveCode);                 
                 out.print(saveCode);
              out.close();
            }catch(Exception e)
              System.out.println("Exception in writing" + e.toString());
         Anyone knows what is going on? I am hoping to use 1.4 for my project. But this thing is not working. Any way around it? Thanx

    Try putting in this line before your close:
    out.flush();
    PrintWriter buffers the data and won't send it until you exit or enough data gets into the buffer to cause a flush. I assume that you are getting a zero byte file. You can also construct a PrintWriter with a boolean to indicate if it should auto flush the buffer.
    Hope that it helps.
    Paul

  • F2 key not working with custom JTable Column

    I have a custom JTable Column (which is a JPanel with a JTextfield and JButton). Everything works as expected, except when the user presses "F2" to start editing the custom column cell. When the user presses F2, the custom cell goes into editing mode, but I am unable to type anything in it.
    Below is the SSCCE.
    Steps to Reproduce problem:
    1) Run the Program
    2) Select any cell in first Column.
    3) Press "F2" and try to type into the cell. Can't type anything.
    package com.ns;
    import java.awt.BorderLayout;
    import java.awt.Component;
    import java.awt.Dimension;
    import java.awt.Point;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyEvent;
    import java.util.EventObject;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    import javax.swing.WindowConstants;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableCellRenderer;
    public class TextButtonCellFrame extends javax.swing.JFrame {
        // Variables declaration - do not modify                    
        private JTextField inputText;
        private JScrollPane jScrollPane1;
        private JPanel testPanel;
        private JTable testTable;
        // End of variables declaration                  
        public TextButtonCellFrame() {
            initComponents();
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                         
        private void initComponents() {
            testPanel = new JPanel();
            jScrollPane1 = new JScrollPane();
            testTable = new JTable();
            inputText = new JTextField();
            setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            testTable.setModel(new DefaultTableModel(
                new Object [][] {
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null},
                    {null, null, null, null}
                new String [] {
                    "Title 1", "Title 2", "Title 3", "Title 4"
            testTable.setCellSelectionEnabled(true);
            testTable.setRowHeight(52);
            testTable.setSurrendersFocusOnKeystroke(true);
            testTable.getColumnModel().getColumn(0).setCellRenderer(new MyTableCellRenderer());
            testTable.getColumnModel().getColumn(0).setCellEditor(new MyTableCellEditor(new JTextField()));
            testTable.getColumnModel().getColumn(0).setPreferredWidth(200);
            jScrollPane1.setViewportView(testTable);
            testPanel.add(jScrollPane1);
            inputText.setPreferredSize(new Dimension(50, 20));
            testPanel.add(inputText);
            getContentPane().add(testPanel, BorderLayout.CENTER);
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
            setBounds((screenSize.width-576)/2, (screenSize.height-417)/2, 576, 417);
        }// </editor-fold>                       
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new TextButtonCellFrame().setVisible(true);
        public class MyTableCellRenderer extends JPanel implements TableCellRenderer {
            Point point;
            JButton button1 = new JButton("Test 1");
            JTextField txtField = new JTextField();
            public MyTableCellRenderer() {
                setLayout(new BorderLayout());
                this.add(button1, BorderLayout.EAST);
                this.add(txtField,BorderLayout.CENTER);
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int rowIndex, int vColIndex) {
                if (isSelected) {
                    txtField.setBackground(testTable.getSelectionBackground());
                    txtField.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
                else {
                    txtField.setBackground(testTable.getBackground());
                    txtField.setBorder(null);
                return this;
        public class MyTableCellEditor extends DefaultCellEditor {
            JPanel panel = new JPanel();
            JButton button1 = new JButton ("Test 1");
            JTextField txtField;
            MyTableCellEditor(JTextField txtField) {
                super (txtField);
                this.txtField = txtField;
                panel.setLayout(new BorderLayout());
                panel.add(button1, BorderLayout.EAST);
                panel.add(txtField,BorderLayout.CENTER);
            public void actionPerformed(ActionEvent e) {
                if (e.getSource() == button1)
                    JOptionPane.showMessageDialog(null, "Action One Successful");
            public Component getTableCellEditorComponent(JTable table, Object value,
                                        boolean isSelected, int row, int column) {
                return panel;
           public boolean isCellEditable(final EventObject anEvent) {
              if (anEvent instanceof KeyEvent) {
                 final KeyEvent keyEvent = (KeyEvent) anEvent;
                 SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                       if (!Character.isIdentifierIgnorable(keyEvent.getKeyChar())) {
                          txtField.setText(txtField.getText() + keyEvent.getKeyChar());
                       txtField.setCaretPosition(txtField.getText().length());
                       txtField.requestFocusInWindow();
                return super.isCellEditable(anEvent);
    }The code for isCellEditable(final EventObject anEvent) which is needed to edit the cell using keyboard was provided by DarrylBurke here
    regards,
    nirvan.

    The F2 key when pressed generates an action event (either JTable generates it or some other component). I am not sure how to handle the action event in the isCellEditable() method. Also, F(X) range of keys other than F2 dump some junk character in the JTextfield when pressed. I am now stuck at this point and don't know how handle F(X) range of keys.
    regards,
    nirvan.

  • Why id this not working? Please Help...

    This part in my action performed is not working. the buttons on my second form is not responding at all!!! Please help ...
         public void actionPerformed(ActionEvent ae)
              if(ae.getSource() == itmAddD)
                   frmAddDriver.setVisible(true);
                   String name;
                   String surname;
                   String work;
                   int age = 0;
                   if(ae.getSource() == btnAddAD)
                   if(!((txtAgeAD.getText().equals("")) && (txtSurnameAD.getText().equals("")) && (txtNameAD.getText().equals(""))))
                             name = txtNameAD.getText();
                             surname = txtSurnameAD.getText();
                             try
                                  age = Integer.parseInt(txtAgeAD.getText());
                                  addDriver.add(new MyDriver(name, surname, age, cboWorkAD.getSelectedItem()));
                                  cboDriver.addItem(name);
                                  for(int i = 0; i < addDriver.size(); i++)
                                       System.out.println(addDriver.elementAt(i));
                             catch(NumberFormatException err)
                                  JOptionPane.showMessageDialog(frmMyGUI, "Age should be numeric","Error", JOptionPane.ERROR_MESSAGE);
                   else if(ae.getSource() == btnCancelAD)
                        frmMyGUI.dispose();

    You're a crazy maniac. The reason none of your buttons (bar one) are working is because you nested all the if statements....
    if(ae.getSource() == itmAddD)
        if(ae.getSource() == btnAddAD)
            // how is this ever going to be true?Un-nest them.
    Cheers,
    Radish21

  • Need a little help with a Jbutton not working out the way I planned

    The following code is to fulfill an assignment I am working on. The problem I am having is with the btnCalc. For some reason when the button is used, the results I get is from another button. I think the variables are set right for the program to function properly but I am really hung up on this. Do anyone have any suggestions?
    import java.awt.*;                     //Contains classes for creating GUI
    import java.awt.event.*;                //For listener events
    import javax.swing.*;                     // Imports the Main Swing Package
    import javax.swing.event.*;
    import javax.swing.text.*;           // Positions text box
    import java.text.NumberFormat;          // For number format such as currency
    import java.text.*;                     // Imports the Main Text Package
    import java.util.*;                     // Utility Package
    public class MPC extends JFrame implements ActionListener           //Creates Class for MPC
    //double dblLoanAmount, dblInterestRate, dblMonthlyPayment;
    TextField txtTotalMort;
         //JButton fixRates = new JButton("Choose Fixed Rates");
         JLabel lblTotalMort = new JLabel("How much is the loan?"); // Label for dblLoanAmount amount
         JTextField txtYears = new JTextField(10);
         JLabel lblPayment = new JLabel("Your monthly payment is "); // Label for Payment
         JTextField txtPayment = new JTextField(10);
         JLabel lblYears = new JLabel("How many years?");
                             // add(lblYears);
                   JTextField txtYearsInput = new JTextField(10);
                             //a dd(txtYears);
         JLabel lblInterestRate = new JLabel("What is the interest rate?");
                             //add(lblInterestRate);
                   JTextField txtInterestRate = new JTextField(10);
                             //add(txtInterestRate);
         //JLabel lblPayment = new JLabel("Your monthly payment is:");
                             //add(lblPayment);
                   //JTextField txtPayment = new JTextField(10);
                             //txtPayment.setEditable(false);
                                  //add(txtPayment);
         JButton btnCalc = new JButton("Calculate");
                             //add(btnCalc);
                             //btnCalc.addActionListener(this);
    JButton year7InterestRateBtn = new JButton("7 years at 5.35%");     // Mortgage Term and Interest Rate
    JButton year15InterestRateBtn = new JButton("15 years at 5.50%");
    JButton year30InterestRateBtn = new JButton("30 years at 5.75%");
    JButton reset = new JButton("Clear All");
    JTextArea boxSpace = new JTextArea(100,200);          // Morgtage table size
    JScrollPane scroll = new JScrollPane(boxSpace);     // ScrollPane
              public MPC()     // Method
         super("MPC");     // Frame Title
              JMenuBar mb = new JMenuBar();     // Menu Bar
    setJMenuBar(mb);
                        setSize(325, 500);          // Frame Size
                        JPanel pane = new JPanel();
                        pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS)); //Grid box configuration
                        Container grid = getContentPane();
                        grid.setLayout(new GridLayout(8,2,8,8));     // Grid Layout
                        pane.add(grid);                                        // Adds grid
                        pane.add(scroll);                                   // Adds scrollPane
                   grid.setBackground(Color.white);
                        Setting color of text and backgrounds
                   txtYears.setBackground(Color.white);
              txtYears.setForeground(Color.black);
                   txtYears.setFont(new Font("Arial", Font.PLAIN, 10));
                        txtPayment.setBackground(Color.white);
                   txtPayment.setForeground(Color.black);
              txtPayment.setFont(new Font("Arial", Font.PLAIN, 10));
                   boxSpace.setBackground(Color.white);
                   boxSpace.setForeground(Color.black);
                   boxSpace.setFont(new Font("Arial", Font.PLAIN, 10));
              grid.add(lblYears);
              grid.add(txtYearsInput);
              grid.add(lblInterestRate);
              grid.add (txtInterestRate);
              grid.add(lblTotalMort);          // Adds the Mortgage Amount Label
              grid.add(txtYears);               // Adds the Mortgage Amount Text Field
              grid.add(lblPayment);           // Adds the Payment Label
              grid.add(txtPayment);           // Adds the Monthly Payment Text Field
                   txtPayment.setEditable(false);          // Disables editing in this Text Field
              grid.add(btnCalc);
         grid.add(year7InterestRateBtn);               // Adds 1st Loan and Rate Button
              grid.add(year15InterestRateBtn);          // Adds 2nd Loan and Rate Button
              grid.add(year30InterestRateBtn);          // Adds the Exit Button
              grid.add(reset);                               // Adds the New Calc Button
              setContentPane(pane);                          // Enables the Content Pane
              setVisible(true);                               // Sets JPanel to be Visable
              reset.addActionListener(this);                          // Adds Action Listener to the New Calc Button
              txtYearsInput.addActionListener(this);
              txtInterestRate.addActionListener(this);
              btnCalc.addActionListener(this);
         year7InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
              year15InterestRateBtn.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
              year30InterestRateBtn.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
              txtYears.addActionListener(this);                              // Adds Action Listener to the Mortgage Amount Text Field
              txtPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
              public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
         Object command = e.getSource(); // Enables command to get data
         int intYears = 0;          // Declares intYears
                   double dblLoanAmount, dblInterestRate, interestRate, intRate;
         if (command == year7InterestRateBtn)                                   // Activates the 1st Loan Button
    intYears = 0;                                        // Sets 1st value of Array
         if (command == year15InterestRateBtn)                                   // Activates the 2nd Loan Button
         intYears = 1;                                        // Sets 2nd value of Array
              if (command == year30InterestRateBtn)                                   // Activates the 3rd Loan Button
                   intYears = 2;                                        // Sets 3rd value of Array
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    dblLoanAmount = 0;                                   // Declares and Initializes dblLoanAmount
                   dblInterestRate = 0;                                        // Declares and Initializes dblInterestRate
              double [][] dblTrmLoanRate = {{7, 5.35}, {15, 5.50}, {30, 5.75},};           // Array Data for Calculation
    try
    dblLoanAmount = Double.parseDouble(txtYears.getText()); // Gets user input from txtYears Text Field
    catch (NumberFormatException nfe)                          // Checks for correct user input
                             JOptionPane.showMessageDialog(null, "You must enter a valid number.", "MPC", JOptionPane.INFORMATION_MESSAGE);
    return;
              interestRate = dblTrmLoanRate [intYears][1];
                   //dblInterestRate=interestRate;
                   intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate
         double intYearsMonths = dblTrmLoanRate [intYears] [0];                    // Calculates Loan Term in Months
    int months = (int)intYearsMonths * 12;                          // Devides by months
    double interestRateMonthly = (intRate / 12); // Devides Rate
              double payment = dblLoanAmount * intRate / (1 - (Math.pow(1/(1 + intRate), months))); // Calculates monthly payment
         double dblRmnLoan = dblLoanAmount;                              //Left over balance
         double txtPaymentInterest = 0;                                   // Payment
         double txtPaymentPrincipal = 0;                                   // Payment of principal
    NumberFormat currency = NumberFormat.getCurrencyInstance(Locale.US); // Curreny format
         txtPayment.setText(currency.format(payment));
              boxSpace.setText("Month\tPrincipal\tInterest\tBalance Left\n");
              for (;months > 0 ; months -- )
              txtPaymentInterest = (dblRmnLoan * intRate);
                        txtPaymentPrincipal = (payment - txtPaymentInterest);          // Calculates monthly payment
                   dblRmnLoan = (dblRmnLoan - txtPaymentPrincipal);
                        boxSpace.setCaret (new DefaultCaret());                    // Scroll position
                        boxSpace.append(String.valueOf(months) + "\t" +               // Table data
                        currency.format(txtPaymentPrincipal) + "\t" +
                   currency.format(txtPaymentInterest) + "\t" +
                   currency.format(dblRmnLoan) + "\n");
    if(command == reset)
                             Clears fields
                        txtYearsInput.setText(null);
                        txtInterestRate.setText(null);
              txtYears.setText(null);
                        txtPayment.setText(null);
         boxSpace.setText(null);
                        public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
              new MPC();
    }

    This portion to be exact. All the buttons work for me except this one. I need to calculate user input and also use the fixed data that can be found in the dblTrmLoanRate array. When I choos to use user input instead, the program either crashes or for some reason uses the year7InterestRateBtn instead.
                   if (command == btnCalc)
                        //dblLoanAmount = Double.parseDouble(txtTotalMort.getText() ); // Loan amount
                        //interestRate = Double.parseDouble(txtInterestRate.getText() ); // /100 )/ 12; // Devides rate
                        intRate = (Double.parseDouble(txtInterestRate.getText() )/100 )/ 12;
                        //int intYearsMonths = Integer.parseInt(txtYearsInput.getText() );// * 12; //Multiplies loan length
                        int months = Integer.parseInt(txtYearsInput.getText() )* 12;
    I was going to leave out the remed portion but thought it might help you with the navigation. I am sorry I did not use code tags, but I am going to go find out what those are and use them in the future.

  • Finding on which line the error has occured! still not working~ desperate!

    I have a problem with error handling when transforming XML with XSL file.
    If I have XSLT file like below
    <xsl:template match="/">
    <html><body>
    <xsl:apply-templates/>
    </body></html>
    </xsl:template>
    and I just change the last line "</xsl:template>" to "</xsl:template" to allow the exception return the line number of where error is occurred (in this case error is missing '>' bracket)
    What I want to find is the exact line number where the error has occured.
    part of my java code looks like below
    catch( TransformerConfigurationException tce )
    // Error generated
    JOptionPane.showMessageDialog( null, "ERROR1"+tce.getLocator().getLineNumber());
    The above code does not work properly because getLocator() method returns a null value...
    I also checked whether getLocator() really returns null so I did this
    if( tce.getLocator() == null )
    System.out.println( "it is null indeed" );
    and found out it DOES return 'null'.
    Could you please tell me why it is returning null and how I can get around to get the line number of where error has occurred? PLEASE!!!!!!!!!!!!!!!

    The reason is probably that your exception
    is TransformerConfigurationException i.e.
    the transforming process has never been started
    because your transformer is not configured properly.
    That means that no SourceLocator exists...
    Check what
          System.out.println(tce.getMessage());
       says.
    Kullervo

  • Applet not Working.Why???

    I have written an applet program but it does not work
    It works when i did it as an application.
    I have installed JAVA plug in.The HTML and Applet codes
    are in the same directory as JDK
    The web browser comes up with a grey area & the following messages:
    Exception:java.lang.ClassNotFoundException:testing4.class
    (on the grey area)
    Applet testing4 not loaded (at the bottom of the browser)
    Why is this so?
    The code i have used are as follows:
    HTML CODE
    <html>
    <title>LPC
    </title>
    <applet code="testing4.class"  width=400 height=110>
    </applet>
    </html>APPLET PROGRAM CODE
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    //import java.lang.Object;
    public class testing4 extends JApplet
    { private JTextArea display;
      private JScrollPane scrollPane2;
      private JButton paste;
      private JPanel P2;
      private File fileName;
      public void init()
        paste=new JButton("paste");
        paste.setMinimumSize(new Dimension(90,20));
        paste.setPreferredSize(new Dimension(90,20));
        paste.setMaximumSize(new Dimension(90,20));
        copyhandler pa=new copyhandler();
        paste.addActionListener(pa);
        display=new JTextArea();
        scrollPane2=new JScrollPane(display);
        scrollPane2.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane2.setMinimumSize(new Dimension(200,58));
        scrollPane2.setPreferredSize(new Dimension(200,58));
        scrollPane2.setMaximumSize(new Dimension(200,58));
        P2=new JPanel();
        P2.setMinimumSize(new Dimension(200,80));
        P2.setPreferredSize(new Dimension(200,80));
        P2.setMaximumSize(new Dimension(200,80));
        P2.setLayout(new BoxLayout(P2,BoxLayout.Y_AXIS));
        scrollPane2.setAlignmentX (Component.LEFT_ALIGNMENT);
        P2.add(scrollPane2);
        paste.setAlignmentX(Component.LEFT_ALIGNMENT);
        P2.add(paste);
       Container c=getContentPane();
        c.add(P2);
       //COPIES TEXT FROM FILE ON MY DISK TO THE TEXTAREA
       private class copyhandler implements ActionListener
       { public void actionPerformed(ActionEvent event)
         { JFileChooser fileChooser = new JFileChooser();
           fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY );
           int result = fileChooser.showOpenDialog(testing4.this);
           // user clicked Cancel button on dialog
           if ( result == JFileChooser.CANCEL_OPTION )
             return;
           fileName = fileChooser.getSelectedFile();
           if ( fileName == null ||
              fileName.getName().equals( "" ) )
           JOptionPane.showMessageDialog( null,"Invalid File Name",
                                            "Invalid File Name",
                                          JOptionPane.ERROR_MESSAGE );
           else
           { try
             { FileReader in = new FileReader(fileName);
               BufferedReader reading= new BufferedReader(in);
               String store="";
               while (reading.ready())
               { StringTokenizer st = new StringTokenizer(reading.readLine());
                 store=store+st.nextToken()+"\n";
               display.setText(store);
             catch ( IOException e )
             { JOptionPane.showMessageDialog( null,
                                          "Error Opening File", "Error",
                                          JOptionPane.ERROR_MESSAGE );
      public static void main (String [] args)
      { testing4 done =new testing4();
        JFrame frame = new JFrame("testing");
        frame.addWindowListener(new WindowAdapter()
                                 public void windowClosing(WindowEvent e)
                                   System.exit(0);
        done.init();
        frame.getContentPane().add(done);
        frame.pack();
        frame.setSize(205,110);
        frame.setVisible(true);
    }

    It Still giving a blank page.
    New Code
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    //import java.lang.Object;
    public class testing4 extends JApplet
    { private JTextArea display;
      private JScrollPane scrollPane2;
      private JButton paste;
      private JPanel P2;
      private File fileName;
      public void init()
        paste=new JButton("paste");
        paste.setMinimumSize(new Dimension(90,20));
        paste.setPreferredSize(new Dimension(90,20));
        paste.setMaximumSize(new Dimension(90,20));
        copyhandler pa=new copyhandler();
        paste.addActionListener(pa);
        display=new JTextArea();
        scrollPane2=new JScrollPane(display);
        scrollPane2.setVerticalScrollBarPolicy(
                            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane2.setMinimumSize(new Dimension(200,58));
        scrollPane2.setPreferredSize(new Dimension(200,58));
        scrollPane2.setMaximumSize(new Dimension(200,58));
        P2=new JPanel();
        P2.setMinimumSize(new Dimension(200,80));
        P2.setPreferredSize(new Dimension(200,80));
        P2.setMaximumSize(new Dimension(200,80));
        P2.setLayout(new BoxLayout(P2,BoxLayout.Y_AXIS));
        scrollPane2.setAlignmentX (Component.LEFT_ALIGNMENT);
        P2.add(scrollPane2);
        paste.setAlignmentX(Component.LEFT_ALIGNMENT);
        P2.add(paste);
       Container c=getContentPane();
        c.add(P2);
       //COPIES TEXT FROM FILE ON MY DISK TO THE TEXTAREA
       private class copyhandler implements ActionListener
       { public void actionPerformed(ActionEvent event)
         { JFileChooser fileChooser = new JFileChooser();
           fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY );
           int result = fileChooser.showOpenDialog(testing4.this);
           // user clicked Cancel button on dialog
           if ( result == JFileChooser.CANCEL_OPTION )
             return;
           fileName = fileChooser.getSelectedFile();
           if ( fileName == null ||
              fileName.getName().equals( "" ) )
           JOptionPane.showMessageDialog( null,"Invalid File Name",
                                            "Invalid File Name",
                                          JOptionPane.ERROR_MESSAGE );
           else
           { try
             { FileReader in = new FileReader(fileName);
               BufferedReader reading= new BufferedReader(in);
               String store="";
               while (reading.ready())
               { StringTokenizer st = new StringTokenizer(reading.readLine());
                 store=store+st.nextToken()+"\n";
               display.setText(store);
             catch ( IOException e )
             { JOptionPane.showMessageDialog( null,
                                          "Error Opening File", "Error",
                                          JOptionPane.ERROR_MESSAGE );
      public static void main (String [] args)
      { testing4 done =new testing4();
        //you did not set applet's width and height:
        //applet is a container too
        done.setWidth(205);
        done.setHeight(110);
        JFrame frame = new JFrame("testing");
        frame.addWindowListener(new WindowAdapter()
                                  public void windowClosing(WindowEvent e)
                                  { System.exit(0);
        done.init();
        frame.getContentPane().add(done);
        frame.pack();
        frame.setSize(205,110);
        frame.setVisible(true);
    }

Maybe you are looking for