JOptionPane in Synchronised Method

Hi,
I'm having a bit of trouble using JOptionPane in a synchronised method. The GUI maintains a list of allowed and blocked sites.
Many threads access these lists to check if an access to a site should be allowed or not. If the new access does not match an entry in either list then a JOptionPane is displayed to ask the user for the action to take.
The lists need to be synchronised so the GUI class looks like this:
public class Console extends JFrame{
     private JTextArea allowedHosts;     
     private JTextArea blockedHosts;
     public Console()
     {...creates and displays GUI...     }
     public synchronized boolean isRequestAllowed(Request request)
     { ...//code to check if the request is in allowed or blocked list
          else
//Pop up a JDialog to ask the user for the next action to take
          return promptForAction(request);     
     private boolean promptForAction(Request request)
          ...//creates options for JOptionPane          
          try
               SwingUtilities.invokeAndWait( new Runnable() {
     public void run()
     actionCode[0] = JOptionPane.showOptionDialog(frame, message, "Access Attempt",
                         JOptionPane.DEFAULT_OPTION,
                         JOptionPane.QUESTION_MESSAGE,
                         null, options, options[0]);
          catch (InterruptedException ignore){}
          catch (InvocationTargetException ignore) {}     
...//checks actionCode[0] to specify next action
The need for synchronisation is that I don't want one thread checking the allowed or blocked lists while the user is being prompted for input about a previous request.
The JOptionPane works fine for first request and will return. A second request is then attempted and the JOptionPane displays but will not respond to any inputs or clicks on buttons.
My experience of Java is very limited and I might be making alot of mistakes but I have read the tutorials on the java website and any other related sites.
Any help would be much appreciated,
Mark

moc02 wrote:
The class doesn't really need to extend JFrame. Just the way I done it. I'll change it round and see if that sorts it.Even if it doesn't, it's almost always better to avoid inheritance unless it is necessary. In other words, I agree with Darryl: don't extend JFrame.
On the other point, I'm not really sure what you are talking about, showing my lack of knowledge there. I don't know what you mean by separating model from view so if you could explain a little more I'd really appreciate it. The model is the data and the non-GUI code necessary to manipulate the data. The view is the graphical representation of it.
I have to wonder if you may be trying to bite more than you can chew here.

Similar Messages

  • Synchronisation methods in same class

    I have three methods in same class A,B,C IN which A,B synchronised and c not.
    my question is if one thread is in A.another thread cann access B OR C?

    jverd wrote:
    Syncing a block on the object pointed to by X
    synchronized (X) { /* do stuff */}simply waits until no other thread is synced on that object, and then enters the block.
    Declaring a non-static method synchronized is the same as doing synchronized (this) { /* do stuff */ }Calling a non-synced method or executing a non-synced block or statement does not wait for the lock.Duke-wh0ring?? :)

  • JOptionPane works once in synchronized method

    Hi,
    I'm having a bit of trouble using JOptionPane in a synchronised method. The GUI maintains a list of allowed and blocked sites.
    Many threads access these lists to check if an access to a site should be allowed or not. If the new access does not match an entry in either list then a JOptionPane is displayed to ask the user for the action to take.
    The lists need to be synchronised so the GUI class looks like this:
    public class Console extends JFrame{
    private JTextArea allowedHosts;
    private JTextArea blockedHosts;
    public Console()
    {...creates and displays GUI... }
    public synchronized boolean isRequestAllowed(Request request)
    { ...//code to check if the request is in allowed or blocked list
    else
    //Pop up a JDialog to ask the user for the next action to take
    return promptForAction(request);
    private boolean promptForAction(Request request)
    ...//creates options for JOptionPane
    try
    SwingUtilities.invokeAndWait( new Runnable() {
    public void run()
    actionCode[0] = JOptionPane.showOptionDialog(frame, message, "Access Attempt",
    JOptionPane.DEFAULT_OPTION,
    JOptionPane.QUESTION_MESSAGE,
    null, options, options[0]);
    catch (InterruptedException ignore){}
    catch (InvocationTargetException ignore) {}
    ...//checks actionCode[0] to specify next action
    The need for synchronisation is that I don't want one thread checking the allowed or blocked lists while the user is being prompted for input about a previous request.
    The JOptionPane works fine for first request and will return. A second request is then attempted and the JOptionPane displays but will not respond to any inputs or clicks on buttons.
    My experience of Java is very limited and I might be making alot of mistakes but I have read the tutorials on the java website and any other related sites.
    Any help would be much appreciated,
    Mark

    Double post, duplicate of [5291829|http://forum.java.sun.com/thread.jspa?threadID=5291829]
    db

  • Use of synchronisation with the SUN DAO Pattern

    With reference to the design pattern Core J2EE Patterns Data Access Object: http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html
    I am writing a DAO package to handle access to multiple datasources at a record level (e.g. user records may be located at datasource A, but customer records at datasource B). The role of the package is to provide DAO objects to clients (e.g. business objects in an application package to come later). Nothing too unusual. I have digested the SUN design pattern for DAO.
    As I understand it, it can be summarised as: client code calls on an abstract DAOFactory to provide the appropriate concrete DAOFactory . The concrete factory can then supply the correct DAO object. The concrete DAOFactory is also responsible for providing the connection services (such as pooling). So far so good. I have pasted the concrete DAOFactory code form the design pattern page:
    // Cloudscape concrete DAO Factory implementation
    import java.sql.*;
    public class CloudscapeDAOFactory extends DAOFactory {
    public static final String DRIVER=
    "COM.cloudscape.core.RmiJdbcDriver";
    public static final String DBURL=
    "jdbc:cloudscape:rmi://localhost:1099/CoreJ2EEDB";
    // method to create Cloudscape connections
    public static Connection createConnection() {
    // Use DRIVER and DBURL to create a connection
    // Recommend connection pool implementation/usage
    *** can a connection pool be implemented in a static method? ***
    public CustomerDAO getCustomerDAO() {
    // CloudscapeCustomerDAO implements CustomerDAO
    return new CloudscapeCustomerDAO();
    public AccountDAO getAccountDAO() {
    // CloudscapeAccountDAO implements AccountDAO
    return new CloudscapeAccountDAO();
    public OrderDAO getOrderDAO() {
    // CloudscapeOrderDAO implements OrderDAO
    return new CloudscapeOrderDAO();
    I have some questions on this overall design.
    1)     The design for the factories as given looks inelegant and requires upgrading each time a new DAO is added ? much better surely to dynamically generate the DAOs using reflection. If I implement a mapping of data type to data source using a properties file (typical entry, Key = Role, Value = Oracle), the use of abstract and concrete factories can be reduced to a single factory. The single factory reads in the mapping on initialisation and provides a method getDAO to client code. The method takes the data type, looks up the data source and returns the correct DAO class using reflection (e.g. the client passes ?Role? to getDAO and the factory returns Oracle + DAO + Role = OracleDAORole.class). This also has the advantage that the client code does not need to specify the data source to use. I have read some forums and note that performance is an issue with reflection; however I have not seen any significant difference in performance between using reflection to generate a class name and using a factory pattern (e.g. testing just the code paths, for 10 million operations, both reflection and factory took 2.5 seconds each). Does anyone have any opinions on the pros and cons of this approach?
    2)     If we go with the original DAO design (ignoring 1 above) I have marked the part of the concrete factory code that I have a problem with: using a connection pool in the concrete factory. As the factory?s createConnection method is static, you cannot use NotifyAll or Wait methods here, and therefore you cannot synchronise access to the pool (correct?). I have therefore created a separate connection pool class (which uses the singleton pattern and uses synchronised methods to manage the pool). Is this a sensible way to approach this or is there a clever way to synchronise access to static methods?
    Thanks in advance - Alan

    These resources may be helpful:
    http://daoexamples.sourceforge.net/related.html
    http://daoexamples.sourceforge.net/index.html

  • JOptionPane show Message Dialog always on top found a Solution

    just thought of a solution for the age old java problem with message boxes / dialogs / input .
    It's funny when you google it you'll find like a million people asking for a solution but none or very few that gives an answer that works.
    this is probly not a new solution but i came up with this yesterday and thought i would "share".
    dunno why the java developers hasnt made a always on top function for this since there seems to be a very high demand for it.
    this hax will hopefully work at all times.
    hope google will find this thread, i searched for a solution yesterday and found none? which is surprising and im a pro googler too.
    import javax.swing.*;
    public class main{
         public static void main(String args[]){
              JFrame j=new JFrame();
              j.setAlwaysOnTop(true);
              j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              j.setVisible(true);
              j.setVisible(false);
              JOptionPane.showMessageDialog(j,"hi");
              System.exit(0);
    }

    I didn't realize it was an "age old problem." The JOptionPane's showXXX methods just show an ordinary modal dialog. If you want to set the alwaysOnTop property of said dialog then you just need to obtain a reference and call the method in question.
    JOptionPane op = new JOptionPane("hi",JOptionPane.INFORMATION_MESSAGE);
    JDialog dialog = op.createDialog("Message Dialog");
    dialog.setAlwaysOnTop(true); //<-- this line
    dialog.setModal(true);
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);No need for an intermediate frame.

  • Can I call an object with synchronized methods from an EJB

    I have a need for multiple threads (e.g. Message Driven Beans) to access a shared object, lets say a singleton, I'm aware of the "you can't have a singleton in the EJB world" issues) for read/write operations, so the operations will need to be synchronised.
    I've seen various statements such as you can't use read/write static fields in EJBs and you can't use synchronisation primitives in EJBs but I've also seen statements that say its okay to access utility classes such as Vector (which has synchronised methods) from an EJB.
    Does anyone know if there is a definitive answer on this? What are the implications of accessing a shared object with synchronised methods from multiple EJBs? Is it just that the EJB's thread may block which limits the ability of the container to manage the EJBs? In the Vector example above (from Professional Java Server Programming) did they mean its okay to use these utility classes provided they aren't shared across threads?
    If I can't use a plain old Java Object does anyone know if there are other potential solutions for sharing objects across EJBs?
    In my problem, I have an operation that I want to run in a multi-threaded way. Each thread will add information to the shared object, and this info may be used by the other threads. There's no lengthy blocking as such other than the fact that only one thread can be adding/reading information from the shared object at a time.
    I've trawled through this forum looking for similar questions of which there seem to be many, but there doesn't seem to be any definitive answers (sorry if there was and I missed it).
    Thanks
    Martin

    You can share objects among EJB's or among objects used by one or more EJB's. You can use synchronization primitives - nothing will prevent you from doing that.
    After all, the container classes, JVM-provides classes, JDBC, JCA, JNDI and other such classes do all of this with impunity. You can too. You can use file and socket I/O as well, presuming you configure the security profile to allow it. Should you? Well it depends on what you need to accomplish and if there is another practical alternative.
    Yes the specification warns you not to, but you cannot be responsible for the interior hidden implementation of classes provided to you by the JVM or third parties so you can never truly know if your are breaking these written rules.
    But when you do these things, you are taking over some part of the role of the container. For short running methods that only block while another thread is using the method or code block and no I/O or use of other potentially blocking operations are contained in the method/block, you will be fine. If you don't watch out and create deadlocks, you will harm the container and its managed thread pool.
    You should not define EJB methods as synchronized.
    Also, if you share objects between EJB's, you need to realize that the container is free to isolate pools of your EJB in separate classloaders or JVM's. It's behavior can be influenced by your packaging choices (use of .ear, multiple separate .jar's, etc.) and the configuration of the server esp. use of clustering. This will cause duplicate sets of shared classes - so singletons will not necessarily be singleton across the entire server/cluster, but no single EJB instance will see more than one of them. You design needs to be tolerant of that fact in order to work correctly.
    This isn't the definitive answer you asked for - I'll leave that to the language/spec lawyers out there. But in my experience I have run across a number of occasions where I had to go outside of the written rules and ave yet to be burned for it.
    Chuck

  • Repeating a method

    I have a program that is a guessing game, but it only gets 1 guess and decides if its right or not, I would like to use a loop and get it to keep asking for numbers until the user gets it right heres the program
    import java.util.*;
    import javax.swing.JOptionPane;
    public class method
         public static void main (String [ ] args)
              int number = 0;
              String numberString = null;
              int randomNumber = new Random().nextInt(100) + 1;
              get (randomNumber);
              guess (number, numberString);
              answer (number, randomNumber);
         public static int get(int randomNumber)
              return (randomNumber);
         public static int guess (int number, String numberString)
              numberString = JOptionPane.showInputDialog("Choose a number 1-100");
              number = Integer.parseInt(numberString);
              return (number);
         public static void answer (int number, int randomNumber)
              if (number == randomNumber)
                   System.out.println("You Win! The random number was " + randomNumber);
              if (number > randomNumber)
                   System.out.println("Too High, guess again);
              if (number < randomnumber)
                   System.out.println("Too Low, guess again);
              System.exit(0);
    }

    okay i fixed the code a little bit but im getting an error saying unreachable statement
    if (number == randomNumber){
    //and
    missing return statement
    //for one of the last lines of code
    here is the code
    import java.util.*;
    import javax.swing.JOptionPane;
    public class method
         public static void main (String [ ] args)
              int number = 0;
              String numberString = null;
              int randomNumber = new Random().nextInt(100) + 1;
              boolean correctanswer = false;
              get (randomNumber);
              guess (number, numberString, randomNumber, correctanswer);
         public static int get(int randomNumber)
              return (randomNumber);
         public static int guess (int number, String numberString, int randomNumber, boolean correctanswer)
              correctanswer = false;
              while(!correctanswer)
                   numberString = JOptionPane.showInputDialog("Choose a number 1-100");
                   number = Integer.parseInt(numberString);
                   return (number);
                   if (number == randomNumber){
                        correctanswer = true;
                        System.out.println("You Win! The random number was " + randomNumber);
                   if (number > randomNumber)
                        System.out.println("Too High, guess again");
                   if (number < randomNumber)
                        System.out.println("Too Low, guess again");
              System.exit(0);
    }//thanks

  • A beginner in socket programming

    Ok I am been stuck on this program for the whole day trying to figure out why I cannot connect to my server computer using sockets and threads.
    I am trying to implement a instant messenger program where each user acts has both client/server. Each client creates a listening socket and all use a common port number, (in this case port 4444).
    If client 1 wants to interact with client 2, client 1 query�s my MySQL database for their status. Now if their status is online, retrieve their current ip address. So far so good. My program does not with no problem.
    Now comes the painful part. Now that client 1 knows client 2 is online and has his/hers ip, the next step is to connect to client 2�s listening socket using their ip and the port number 4444. Now after connecting to that socket, a new chat dialog gui is suppose to open from the client 2�s side. This new chat dialog gui (jframe) is a thread so that if other users wishes to interact with client 2, another new chat dialog thread will appear!
    But in my case nope! Has soon as client 1 tries to establish a connection with client 2, boom. Error, connection refused: connect!!
    Now I been searching through Google trying to understand what this means and so far I found null� now I posted before asking what that means and someone told me it means that I forgot to close the sockets and input, output streams. But how can I close it when I cannot even establish a connection with client 2??
    Things I have tried:
    I tried inputting myself, the actual ip of client 2 and guess what� no luck
    I tried the client 2�s computer name, and same thing!
    I tried to create a whole new main class just so that I can open and close the sockets and input/output stream and nope, no luck at all..
    Now that you have a good understanding of my program. Here comes the code:
    I�l start with the user_window, which is the main menu as you call it: this jframe once opened, is suppose to create a server socket to listen for connections. If a connection is made, load the chatdialog gui thread�
    * user_window.java
    * Created on 10 February 2006, 11:50
    package icomm;
    import java.sql.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    * @author jonathan
    public class user_window extends javax.swing.JFrame implements WindowListener {
    protected String crnt_user;
    protected String crnt_ip;
    protected String dummy = "";
    /** Creates new form user_window */
    public user_window() {
    initComponents();
    listeningSocket();
    addWindowListener( this );
    public user_window(String users_name)
    initComponents();
    addWindowListener( this );
    this.crnt_user = users_name;
    private void exit()
    MySQL_queries offline = new MySQL_queries();
    offline.off_status(crnt_user);
    JOptionPane.showMessageDialog(null, "you are about to close the program " + crnt_user, null, JOptionPane.ERROR_MESSAGE);
    MySQL_queries query = new MySQL_queries();
    query.off_status(crnt_user);
    query.reset_ip(crnt_user);
    System.exit(0);
    public void windowClosing(WindowEvent e)
         exit();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    try {
    Buddie_list =(javax.swing.JTree)java.beans.Beans.instantiate(getClass().getClassLoader(), "icomm.user_window_Buddie_list");
    } catch (ClassNotFoundException e) {
    e.printStackTrace();
    } catch (java.io.IOException e) {
    e.printStackTrace();
    label = new javax.swing.JLabel();
    demo = new javax.swing.JButton();
    jMenuBar1 = new javax.swing.JMenuBar();
    jMenu1 = new javax.swing.JMenu();
    Close = new javax.swing.JMenuItem();
    jMenu2 = new javax.swing.JMenu();
    profile = new javax.swing.JMenuItem();
    jMenu3 = new javax.swing.JMenu();
    getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    getContentPane().add(Buddie_list, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 30, 230, 310));
    getContentPane().add(label, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 390, -1, -1));
    demo.setText("talk to shienna");
    demo.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    demoActionPerformed(evt);
    getContentPane().add(demo, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 360, -1, -1));
    jMenu1.setText("File");
    jMenu1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jMenu1ActionPerformed(evt);
    Close.setLabel("Close");
    Close.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    CloseActionPerformed(evt);
    jMenu1.add(Close);
    jMenuBar1.add(jMenu1);
    jMenu2.setText("Option");
    profile.setText("Edit Profile");
    profile.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    profileActionPerformed(evt);
    jMenu2.add(profile);
    jMenuBar1.add(jMenu2);
    jMenu3.setText("Help");
    jMenuBar1.add(jMenu3);
    setJMenuBar(jMenuBar1);
    pack();
    // </editor-fold>
    private void demoActionPerformed(java.awt.event.ActionEvent evt) {                                    
    // TODO add your handling code here:
    ChatDialog_c chatting = new ChatDialog_c(crnt_user, dummy);
    chatting.setTitle("I-comm");
    chatting.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chatting.setSize(360, 500);
    chatting.getSize();
    chatting.setLocation(420,200);
    chatting.setVisible(true);
    private void CloseActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void demo1ActionPerformed(java.awt.event.ActionEvent evt) {                                     
    // TODO add your handling code here:
    private void show_chat_window()
    ChatDialog chat_gui = new ChatDialog();
    chat_gui.setTitle("chat");
    chat_gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    chat_gui.setSize(366, 480);
    chat_gui.getSize();
    chat_gui.setLocation(420,200);
    chat_gui.setVisible(true);// TODO add your handling code here:
    private void log_offActionPerformed(java.awt.event.ActionEvent evt) {                                       
    private void locate_ip()
    try
    InetAddress a;
    a = InetAddress.getLocalHost(); //get ip addrees
    this.crnt_ip = a.getHostAddress(); //then store it in this variable
    catch(UnknownHostException e)
    JOptionPane.showMessageDialog(null, "Error, cant detect localhost", null, JOptionPane.ERROR_MESSAGE);
    public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {}
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
         public void windowOpened(WindowEvent e)
    locate_ip();
    MySQL_queries new_ip = new MySQL_queries();
    new_ip.update_ip(crnt_user, crnt_ip);
    JOptionPane.showMessageDialog(null,"hello " + crnt_user + " your ip is" + crnt_ip, null, JOptionPane.ERROR_MESSAGE);
    private void listeningSocket()
    ServerSocket serverSocket = null;
    boolean listening = true;
    try
    //listen in port 4444;
    serverSocket = new ServerSocket(4444);
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "cannot listen to port 4444", null, JOptionPane.ERROR_MESSAGE);
    while(listening)
    try
    ChatDialog chat = new ChatDialog(serverSocket.accept());
    catch(IOException x)
    JOptionPane.showMessageDialog(null, "could not open chat window", null, JOptionPane.ERROR_MESSAGE);
    private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
    private void profileActionPerformed(java.awt.event.ActionEvent evt) {                                       
    // TODO add your handling code here:
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new user_window().setVisible(true);
    Now for the chatdialog class: I forgot to mention that I have two versions of this class. One that is a thread and the other makes a connection to a thread, hope that makes sence�
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog_c extends javax.swing.JFrame implements WindowListener {
        protected String messege;
        private Socket socket = null;
        protected String ip2;
        private PrintWriter out = null;
        private BufferedReader in = null;
        private String user_name;
        private String status;
        /** Creates new form ChatDialog_c */
        public ChatDialog_c()
            initComponents();
            addWindowListener( this );
         public ChatDialog_c(String ip1)
            initComponents();
            addWindowListener( this );
            this.ip2 = ip1;
            //OptionPane.showMessageDialog(null, "error in closing sockdswdset " + ip2, null, JOptionPane.ERROR_MESSAGE);
         public ChatDialog_c(String user, String status)
            initComponents();
            addWindowListener( this );
            this.user_name = user;
        public void windowClosing(WindowEvent e)
            public void windowActivated(WindowEvent e) {}
         public void windowClosed(WindowEvent e) {
                try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
         public void windowDeactivated(WindowEvent e) {}
         public void windowDeiconified(WindowEvent e) {}
         public void windowIconified(WindowEvent e) {}
          public void windowOpened(WindowEvent e)
              MySQL_queries get_ip = new MySQL_queries();
              this.ip2 = get_ip.find_client(user_name);
               JOptionPane.showMessageDialog(null, user_name + ip2, null, JOptionPane.ERROR_MESSAGE);
                //create socket connection
                try
                    socket = new Socket ("Shienna", 4444);
                    out = new PrintWriter(socket.getOutputStream(), true);
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                catch(UnknownHostException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "unknown  " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "2 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
                 try
                    in.close();
                    out.close();
                    socket.close();
                catch(IOException x)
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(null, "error in closing socket " + x.getMessage() + ip2, null, JOptionPane.ERROR_MESSAGE);
                while(true)
                    try
                        String line = in.readLine();
                        convo_txt.append(line);
                    catch(IOException x)
                        x.printStackTrace();
                        JOptionPane.showMessageDialog(null, "3 " + x.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        /** This method is called from within the constructor to
         * initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is
         * always regenerated by the Form Editor.
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">                         
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            convo_txt = new javax.swing.JTextArea();
            jScrollPane2 = new javax.swing.JScrollPane();
            txt_messege = new javax.swing.JTextArea();
            send = new javax.swing.JButton();
            jMenuBar1 = new javax.swing.JMenuBar();
            jMenu1 = new javax.swing.JMenu();
            jMenu2 = new javax.swing.JMenu();
            getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jScrollPane1.setViewportView(convo_txt);
            getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 220, 280));
            txt_messege.setLineWrap(true);
            jScrollPane2.setViewportView(txt_messege);
            getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 330, 220, 70));
            send.setText("Send");
            send.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    sendActionPerformed(evt);
            getContentPane().add(send, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 420, -1, -1));
            jMenu1.setText("File");
            jMenu1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jMenu1ActionPerformed(evt);
            jMenuBar1.add(jMenu1);
            jMenu2.setText("Option");
            jMenuBar1.add(jMenu2);
            setJMenuBar(jMenuBar1);
            pack();
        // </editor-fold>                       
        private void sendActionPerformed(java.awt.event.ActionEvent evt) {                                    
            String text = txt_messege.getText();
            out.println();
            txt_messege.setText(new String(""));
            convo_txt.append(text);
        private void jMenu1ActionPerformed(java.awt.event.ActionEvent evt) {                                      
    // TODO add your handling code here:
         * @param args the command line arguments
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ChatDialog_c().setVisible(true);
        }///////////////////////chat dialog thread/////////////////////
    package icomm;
    import java.net.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    public class ChatDialog extends javax.swing.JFrame implements WindowListener, Runnable {
        protected String messege;
        private Socket client_user = null;
        /** Creates new form ChatDialog */
        public ChatDialog()
            initComponents();
            addWindowListener( this );
        public ChatDialog(String txt_messege)
            initComponents();
            addWindowListener( this );
            this.messege = txt_messege;
         public ChatDialog(Socket user)
             initComponents();
             addWindowListener( this );
             this.client_user = user;
        public void run()
            BufferedReader in = null;
            PrintWriter out = null;
            String error = "error has occured ";
            String messege = null;
             try
                //create input and output streams
                in = new BufferedReader(new InputStreamReader (client_user.getInputStream()));
                out = new PrintWriter(client_user.getOutputStream(), true);
                while(true)
                   //read messege sent by user
                   messege = in.readLine();
                   //send data back to user
                   out.println(messege);
                   //append data on the text field
                   convo_txt.append(messege + "\n");
                   //chat_gui.setVisible(true);
                   //-=inputs = new ChatDialog(messege);
               //out.close();
                //in.close();
                //client_user.close();
            catch (IOException e)
                //error messege
                e.printStackTrace();
                JOptionPane.showMessageDialog(null, error + e.getMessage(), null, JOptionPane.ERROR_MESSAGE);
        }If I can sort this problem out I would of completed the main part of my program. I have spent days on this and hope that anyone of you guys can take the time out and help me with my current situation. Thanks

    update:
    i have managed to sort out the connection refused
    i know have anotehr problem: both client2 program freezes as soon as client 1 tries to initiate a connection to client 2!!!!!!!!
    when client 2 logs into teh system. it freezes as soon as i press the button! but when client 1 attempts to conenct to client 2, client 2's program stops freezing and the chatdialog comes up showing nothing and freezes! my chadialog is suppose to show a file menu i made but it doesnt,. both clients freezes at this point. no error messeges occur...

  • Can I please get a Debug code compiles

    The code below is supposed to use threads to get the checksum of two files chosen for Jfilechoosers and then compare there checksums and tell whether they are equal or not. I have all working but the values for the files individual checksums are not showing correctly because the threads are not completing before they are displayed. I have tried everything and I have even tried to implement code given to me from this forum but to no evail I have 15 Duke bucks left and they will go to the person who can give me a answer in code and where it is supposed to go plus a little explanation on why so I am not feeling as dumb as I do right now.
    Along with the duke bucks a great apprecaition will come with this for you will have saved my but and my GPA.
    here it is and THANKS to all.....
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class EFile extends JFrame
         private JButton buttons [];
         private JLabel labels [];
         private JTextField text[];
         private JPanel buttonPanel, labelPanel;
         private String bNames []= {"file1", "file2", "compare"};
         private String lNames []= {"1st file name", "2nd file name", "Checksum1", "Checksum2"};
         private File fileName, fileName2;
         private RandomAccessFile input;
         Checksums cksum1 = new Checksums();
         Checksums cksum2 = new Checksums();
         public EFile()
              super( " Eric's File Comparison " );
              Container c = getContentPane();
              c.setLayout(new BorderLayout(25,25));
              buttons = new JButton[3];
              labels = new JLabel[4];
              text = new JTextField[4];
              buttonPanel = new JPanel();
              buttonPanel.setLayout(new GridLayout(buttons.length,1));
              for ( int count = 0; count < buttons.length; count++)
                   buttons[count]= new JButton(bNames[count]);
                   buttonPanel.add(buttons[count]);
              labelPanel = new JPanel();
              labelPanel.setLayout(new GridLayout(labels.length,1));
              for (int count = 0; count < labels.length; count++)
                   labels[count]=new JLabel(lNames[count]);
                   text[count]=new JTextField(count);
                   labelPanel.add(labels[count]);
                   labelPanel.add(text[count]);
              buttons[0].addActionListener(
    // anonymous inner class to handle openButton event
    new ActionListener() {
    // call openFile when button pressed
    public void actionPerformed( ActionEvent event )
    openFile();
    } // end anonymous inner class
    ); // end call to addActionListener
         buttons[1].addActionListener(
    // anonymous inner class to handle openButton event
    new ActionListener() {
    // call openFile when button pressed
    public void actionPerformed( ActionEvent event )
    openFile2();
    } // end anonymous inner class
         buttons[2].addActionListener(
    // anonymous inner class to handle openButton event
    new ActionListener() {
    // call openFile when button pressed
    public void actionPerformed( ActionEvent event )
              //Checksums c1 = new Checksums();
                             cksum1.setFileName(fileName);
                             cksum2.setFileName(fileName2);
                             Thread t1 = new Thread(cksum1);
                             Thread t2 = new Thread(cksum2);
                             Thread t3 = new Thread();
                             t1.start();
                             t2.start();
                             t3.start();
                             int d = cksum1.getChecksum();
                             int e = cksum2.getChecksum();
                             text[2].setText("" + d);     
                             text[3].setText("" + e);
                             testChecksums(d,e);
    } // end anonymous inner class
              c.add(buttonPanel, BorderLayout.WEST);
              c.add(labelPanel, BorderLayout.CENTER);
              setSize(600,400);
              setVisible(true);
         public void testChecksums(int d, int e)
              if (d == e)
                   JOptionPane.showMessageDialog( this, "The checksums ARE equal",
                   "Equal", JOptionPane.ERROR_MESSAGE);
              else
                   JOptionPane.showMessageDialog( this, "The checksums are NOT equal",
                   "Not Equal", JOptionPane.ERROR_MESSAGE);
         private void openFile()
    // display file dialog so user can select file
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(
    JFileChooser.FILES_ONLY );
    int result = fileChooser.showOpenDialog( this );
    // if user clicked Cancel button on dialog, return
    if ( result == JFileChooser.CANCEL_OPTION )
    return;
    // obtain selected file
    fileName = fileChooser.getSelectedFile();
    // display error is file name invalid
    if ( fileName == null ||
    fileName.getName().equals( "" ) )
    JOptionPane.showMessageDialog( this,
    "Invalid File Name", "Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    else {
    // open file
    try {
    input = new RandomAccessFile( fileName, "r" );
                   text[0].setText(fileName.getName());
    buttons[0].setEnabled( false );
    buttons[1].setEnabled( true );
                   buttons[2].setEnabled(true);
    // catch exception while opening file
    catch ( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "File does not exist", "Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    } // end method openFile
    private void openFile2()
    // display file dialog so user can select file
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(
    JFileChooser.FILES_ONLY );
    int result = fileChooser.showOpenDialog( this );
    // if user clicked Cancel button on dialog, return
    if ( result == JFileChooser.CANCEL_OPTION )
    return;
    // obtain selected file
    fileName2 = fileChooser.getSelectedFile();
    // display error is file name invalid
    if ( fileName2 == null ||
    fileName2.getName().equals( "" ) )
    JOptionPane.showMessageDialog( this,
    "Invalid File Name", "Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    else {
    // open file
    try {
    input = new RandomAccessFile( fileName2, "r" );
                   text[1].setText(fileName2.getName());
    buttons[0].setEnabled( false );
    buttons[1].setEnabled( false );
                   buttons[2].setEnabled(true);
    // catch exception while opening file
    catch ( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "File does not exist", "Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    } // end method openFile
    private void closeFile()
    // close file and exit
    try {
    input.close();
    System.exit( 0 );
    // process exception while closing file
    catch ( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "Error closing file",
    "Error", JOptionPane.ERROR_MESSAGE );
    System.exit( 1 );
         public static void main(String args[])
              EFile e = new EFile();
              e.setDefaultCloseOperation(2);
    class Checksums extends JFrame implements Runnable
         //Thread runner;
         public File fileName;
         public RandomAccessFile input;
         public int checkSum ;
         Checksums()
              super();
         public void setFileName(File name)
              fileName = name;          
         public int getChecksum()
              return checkSum;
         public void run()
              try
                        input = new RandomAccessFile( fileName, "r" );
                        byte[] chunk = new byte[100000];
                        int readFile;
                        while ((readFile = input.read(chunk)) != -1)
                             checkSum = (checkSum + readFile)%65535;
                   catch ( IOException ioException)
                        JOptionPane.showMessageDialog( this, "Error opening file",
                        "Error", JOptionPane.ERROR_MESSAGE);
         } //end run
    } // end Checksums

    looking at the code below :
    public void actionPerformed( ActionEvent event )
    //Checksums c1 = new Checksums();
    cksum1.setFileName(fileName);
    cksum2.setFileName(fileName2);
    Thread t1 = new Thread(cksum1);
    Thread t2 = new Thread(cksum2);
    // this thread appears redundant.  why is it here?
    // Thread t3 = new Thread();
    t1.start();
    t2.start();
    // t3.start();
    int d = cksum1.getChecksum();
    int e = cksum2.getChecksum();
    text[2].setText("" + d);
    text[3].setText("" + e);
    testChecksums(d,e);what is happening, as you have stated, is a race condition when you are trying to get d and e. So, something like this might be in order:
    public void actionPerformed( ActionEvent event )
    //Checksums c1 = new Checksums();
    cksum1.setFileName(fileName);
    cksum2.setFileName(fileName2);
    Thread t1 = new Thread(cksum1);
    Thread t2 = new Thread(cksum2);
    t1.start();
    t2.start();
    int d = 0;
    int e = 0;
    try {
      t1.join();
      d = cksum1.getChecksum();
    } catch (InterruptedException e) {
      e.printStackTrace();
    try {
      t2.join();
      e = cksum2.getChecksum();
    } catch (InterruptedException e) {
      e.printStackTrace();
    text[2].setText("" + d);
    text[3].setText("" + e);
    testChecksums(d,e);for information on Thread.join(), I point you to the Thread javadoc.
    for what its worth, the design of your program is not ideal - an ideal design would remove any likelihood of this sort of race condition by not allowing access to the "checksums" before they'd been set by the threads, either through a synchronized() block or object, or through the use of the Observer / Observable pattern. Thread.join() is messy.
    hope this helps
    McFinnigan

  • Why does this class not read and write at same time???

    I had another thread where i was trying to combine two class files together
    http://forum.java.sun.com/thread.jspa?threadID=5146796
    I managed to do it myself but when i run the file it does not work right. If i write a file then try and open the file it says there are no records in the file, but if i close the gui down and open the file everything get read in as normal can anybody tell me why?
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class testing extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton SaveToFile, SaveAs, Exit; //////////savetofile also saves to store need to split up and have 2 buttons
       //private Store store; MIGHT BE SOMETHING TO DO WITH THIS AS I HAD TO COMMENT THIS STORE OUT TO GET IT WORKING AS STORE IS USED BELOW
       private Employee record;
    //////////////////////////////////////from read
    private ObjectInputStream input;
       private JButton nextButton, openButton, nextRecordButton ;
       private Store store = new Store(100);
         private Employee employeeList[] = new Employee[100];
         private int count = 0, next = 0;
    /////////////////////////////////////////////from read end
       // set up GUI
       public testing()
          super( "Employee Data" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  // nine textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // configure button doTask1 for use in this program
          SaveAs = userInterface.getSaveAsButton();
          SaveAs.setText( "Save as.." );
    //////////////////from read
    openButton = userInterface.getOpenFileButton();
          openButton.setText( "Open File" );
    openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // close file and terminate application
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // close file and terminate application
                public void windowClosing( WindowEvent event )
                   if ( input != null )
                             closeFile();
                   System.exit( 0 );
             } // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 from BankUI
          nextButton = userInterface.getDoTask2Button();
          nextButton.setText( "Next Record" );
          nextButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   readRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    //get reference to generic task button do Task3 from BankUI
          // get reference to generic task button doTask3 from BankUI
          nextRecordButton = userInterface.getDoTask3Button();
          nextRecordButton.setText( "Get Next Record" );
          nextRecordButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextRecordButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   getNextRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    ///////////from read end
          // register listener to call openFile when button pressed
          SaveAs.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   SaveLocation();
             } // end anonymous inner class
          ); // end call to addActionListener
          // configure button doTask2 for use in this program
          SaveToFile = userInterface.getSaveStoreToFileButton();
          SaveToFile.setText( "Save to store and to file need to split this task up" );
          SaveToFile.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          SaveToFile.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // NEED TO SPLIT UP SO DONT DO BOTH
             } // end anonymous inner class
          ); // end call to addActionListener
    Exit = userInterface.getExitAndSaveButton();
          Exit.setText( "Exit " );
          Exit.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          Exit.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord(); // adds record to to file
                   closeFile(); // closes everything
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
    ////////////////from read
      // enable user to select file to open
       private void openFile()
          // display file dialog so user can select file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                input = new ObjectInputStream(
                   new FileInputStream( fileName ) );
                openButton.setEnabled( false );
                nextButton.setEnabled( true );
             // process exceptions opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
    public void readRecord() // need to merger with next record
          Employee record;
          // input the values from the file
          try {
         record = ( Employee ) input.readObject();
                   employeeList[count++]= record;
                   store.add(record);/////////ADDS record to Store
              store.displayAll();
              System.out.println("Count is " + store.getCount());
             // create array of Strings to display in GUI
             String values[] = {
                        String.valueOf(record.getName()),
                            String.valueOf(record.getGender()),
                        String.valueOf( record.getDateOfBirth()),
                        String.valueOf( record.getID()),
                             String.valueOf( record.getStartDate()),
                        String.valueOf( record.getSalary()),
                        String.valueOf( record.getAddress()),
                           String.valueOf( record.getNatInsNo()),
                        String.valueOf( record.getPhone())
    // i added all those bits above split onto one line to look neater
             // display record contents
             userInterface.setFieldValues( values );
          // display message when end-of-file reached
          catch ( EOFException endOfFileException ) {
             nextButton.setEnabled( false );
          nextRecordButton.setEnabled( true );
             JOptionPane.showMessageDialog( this, "No more records in file",
                "End of File", JOptionPane.ERROR_MESSAGE );
          // display error message if class is not found
          catch ( ClassNotFoundException classNotFoundException ) {
             JOptionPane.showMessageDialog( this, "Unable to create object",
                "Class Not Found", JOptionPane.ERROR_MESSAGE );
          // display error message if cannot read due to problem with file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error during read from file",
                "Read Error", JOptionPane.ERROR_MESSAGE );
       } // end method readRecord
       private void getNextRecord()
               Employee record = employeeList[next++%count];//cycles throught accounts
          //create aray of string to display in GUI
          String values[] = {String.valueOf(record.getName()),
             String.valueOf(record.getGender()),
              String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
         String.valueOf( record.getNatInsNo()),
         String.valueOf( record.getPhone()),
             String.valueOf( record.getID() ),
               String.valueOf( record.getDateOfBirth() ),
         String.valueOf( record.getSalary() ) };
         //display record contents
         userInterface.setFieldValues(values);
         //display record content
    ///////////////////////////////////from read end
    private void SaveLocation()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                SaveAs.setEnabled( false );
                SaveToFile.setEnabled( true );
              Exit.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // close file and terminate application
    private void closeFile()
          // close file
          try {
              //you want to cycle through each recordand add them to store here.
                                            int storeSize = store.getCount();
                                            for (int i = 0; i<storeSize;i++)
                                            output.writeObject(store.elementAt(i));
             output.close();
    input.close();// from read!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0)); // check if m or f prob check in employee
    if ( employeeNumber >= 0 ) {
                  /* create new record =String name, char gender, Date dob, String add, String nin, String phone, String id, Date start, float salary*/
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                                  // output record and flush buffer
                                  //output.writeObject( record );
                   output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth\nPlease enter like: 01-01-2001",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new testing();
    } // end class CreateSequentialFile

    Sure you can read and write at the same time. But normally you would be reading from one place and writing to another place.
    I rather regret avoiding the OP's earlier post asking how to combine two classes. I looked at the two classes posted and realized the best thing to do was actually to break them into more classes. But I also realized it was going to be a big job explaining why and how, and I just don't have the patience for that sort of thing.
    So now we have a Big Ball Of Tar&trade; and I feel partly responsible.

  • Need help merging these two files togehter

    I have the following class files one reads in a file another creates a file, Can somebody help me put the two class files together so i have one file which creates a file and reads it in, as i am stuck as to which bits need to be copied and which bits i only need once.
    /////////////////////////////////////////////////Code to create and save data in to file////////////////
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class CreateSequentialFile extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton enterButton, openButton;
       private Store store;
       private Employee record;
       // set up GUI
       public CreateSequentialFile()
          super( "Creating a Sequential File of Objects" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  // number of textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // configure button doTask1 for use in this program
          openButton = userInterface.getDoTask1Button();
          openButton.setText( "Save to file" );
          // register listener to call openFile when button pressed
          openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // configure button doTask2 for use in this program
          enterButton = userInterface.getDoTask2Button();
          enterButton.setText( "Save to file..." );
          enterButton.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          enterButton.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
       private void openFile()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                openButton.setEnabled( false );
                enterButton.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // close file and terminate application
       private void closeFile()
          // close file
          try {
    int storeSize = store.getCount();
    for (int i = 0; i<storeSize;i++)
    output.writeObject(store.elementAt(i));
             output.close();
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-"); // what used to put between number
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0));
    if ( employeeNumber >= 0 ) {
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                                  // output record and flush buffer
                        //should be written to fuile in the close file method.
                   output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new CreateSequentialFile();
    } // end class CreateSequentialFile
    /////////////////////////////Code to read and cycle through the file created above///////////
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.*;
    public class ReadSequentialFile extends JFrame {
       private ObjectInputStream input;
       private BankUI userInterface;
       private JButton nextButton, openButton, nextRecordButton ;
       private Store store = new Store(100);
         private Employee employeeList[] = new Employee[100];
         private int count = 0, next = 0;
       // Constructor -- initialize the Frame
       public ReadSequentialFile()
          super( "Add Employee" );
          // create instance of reusable user interface
          userInterface = new BankUI( 9 ); 
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // get reference to generic task button doTask1 from BankUI
          openButton = userInterface.getDoTask1Button();
          openButton.setText( "Open File" );
          // register listener to call openFile when button pressed
          openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // close file and terminate application
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // close file and terminate application
                public void windowClosing( WindowEvent event )
                   if ( input != null )
                             closeFile();
                   System.exit( 0 );
             } // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 from BankUI
          nextButton = userInterface.getDoTask2Button();
          nextButton.setText( "Next Record" );
          nextButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   readRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
          //get reference to generic task button do Task3 from BankUI
          // get reference to generic task button doTask3 from BankUI
          nextRecordButton = userInterface.getDoTask3Button();
          nextRecordButton.setText( "Get Next Record" );
          nextRecordButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextRecordButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   getNextRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
          pack();
          setSize( 600, 300 );
          setVisible( true );
       } // end ReadSequentialFile constructor
       // enable user to select file to open
       private void openFile()
          // display file dialog so user can select file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                input = new ObjectInputStream(
                   new FileInputStream( fileName ) );
                openButton.setEnabled( false );
                nextButton.setEnabled( true );
             // process exceptions opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // read record from file
       public void readRecord()
          Employee record;
          // input the values from the file
          try {
                  record = ( Employee ) input.readObject();
                   employeeList[count++]= record;
                   store.add(record);
              store.displayAll();
              System.out.println("Count is " + store.getCount());
             // create array of Strings to display in GUI
             String values[] = {
                        String.valueOf(record.getName()),
                            String.valueOf(record.getGender()),
                        String.valueOf( record.getDateOfBirth()),
                        String.valueOf( record.getID()),
                             String.valueOf( record.getStartDate()),
                        String.valueOf( record.getSalary()),
                        String.valueOf( record.getAddress()),
                           String.valueOf( record.getNatInsNo()),
                        String.valueOf( record.getPhone())
    // i added all those bits above split onto one line to look neater
             // display record contents
             userInterface.setFieldValues( values );
          // display message when end-of-file reached
          catch ( EOFException endOfFileException ) {
             nextButton.setEnabled( false );
          nextRecordButton.setEnabled( true );
             JOptionPane.showMessageDialog( this, "No more records in file",
                "End of File", JOptionPane.ERROR_MESSAGE );
          // display error message if class is not found
          catch ( ClassNotFoundException classNotFoundException ) {
             JOptionPane.showMessageDialog( this, "Unable to create object",
                "Class Not Found", JOptionPane.ERROR_MESSAGE );
          // display error message if cannot read due to problem with file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error during read from file",
                "Read Error", JOptionPane.ERROR_MESSAGE );
       } // end method readRecord
       private void getNextRecord()
               Employee record = employeeList[next++%count];//cycles throught accounts
          //create aray of string to display in GUI
          String values[] = {String.valueOf(record.getName()),
             String.valueOf(record.getGender()),
              String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
         String.valueOf( record.getNatInsNo()),
         String.valueOf( record.getPhone()),
             String.valueOf( record.getID() ),
               String.valueOf( record.getDateOfBirth() ),
         String.valueOf( record.getSalary() ) };
         //display record contents
         userInterface.setFieldValues(values);
         //display record contents
      // again i nicked these write them on one line
      // close file and terminate application
       private void closeFile()
          // close file and exit
          try {
             input.close();
             System.exit( 0 );
          // process exception while closing file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       public static void main( String args[] )
          new ReadSequentialFile();
    } // end class ReadSequentialFile

    I tired putting both codes together and got this, it runs but does not do what i want can anybody help me put the above two codes together as one
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class togehter extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton enterButton, openButton;
       //private Store store; wont work if i un comment this
       private Employee record;
    // from read
         private ObjectInputStream input;
         private JButton nextButton, openButton2, nextRecordButton ;
            private Store store = new Store(100);
         private Employee employeeList[] = new Employee[100];
         private int count = 0, next = 0;
    // end of read
       // set up GUI
       public togehter()
          super( "Creating a Sequential File of Objects" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  //  textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          // configure button doTask1 for use in this program
          openButton = userInterface.getDoTask1Button();
          openButton.setText( "Save to file" );
          // register listener to call openFile when button pressed
          openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
    // from read
          // get reference to generic task button doTask1 from BankUI
          openButton2 = userInterface.getDoTask1Button();
          openButton2.setText( "Open File" );
          // register listener to call openFile when button pressed
          openButton2.addActionListener(
             // anonymous inner class to handle openButton2 event
             new ActionListener() {
                // close file and terminate application
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
    // from read end
    // from read
    // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // close file and terminate application
                public void windowClosing( WindowEvent event )
                   if ( input != null )
                             closeFile();
                   System.exit( 0 );
             } // end anonymous inner class
          ); // end call to addWindowListener
    //from read end
    // from read
       // get reference to generic task button doTask2 from BankUI
          nextButton = userInterface.getDoTask2Button();
          nextButton.setText( "Next Record" );
          nextButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   readRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
          //get reference to generic task button do Task3 from BankUI
          // get reference to generic task button doTask3 from BankUI
          nextRecordButton = userInterface.getDoTask3Button();
          nextRecordButton.setText( "Get Next Record" );
          nextRecordButton.setEnabled( false );
          // register listener to call readRecord when button pressed
          nextRecordButton.addActionListener(
             // anonymous inner class to handle nextRecord event
             new ActionListener() {
                // call readRecord when user clicks nextRecord
                public void actionPerformed( ActionEvent event )
                   getNextRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
    // from read end
          // configure button doTask2 for use in this program
          enterButton = userInterface.getDoTask2Button();
          enterButton.setText( "Save to file..." );
          enterButton.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          enterButton.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
       private void openFile()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                openButton.setEnabled( false );
                enterButton.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
    // from read
    public void readRecord()
          Employee record;
          // input the values from the file
          try {
                  record = ( Employee ) input.readObject();
                   employeeList[count++]= record;
                   store.add(record);/////////ADDS record to Store
              store.displayAll();
              System.out.println("Count is " + store.getCount());
             // create array of Strings to display in GUI
             String values[] = {
                        String.valueOf(record.getName()),
                            String.valueOf(record.getGender()),
                        String.valueOf( record.getDateOfBirth()),
                        String.valueOf( record.getID()),
                             String.valueOf( record.getStartDate()),
                        String.valueOf( record.getSalary()),
                        String.valueOf( record.getAddress()),
                           String.valueOf( record.getNatInsNo()),
                        String.valueOf( record.getPhone())
             // display record contents
             userInterface.setFieldValues( values );
          // display message when end-of-file reached
          catch ( EOFException endOfFileException ) {
             nextButton.setEnabled( false );
          nextRecordButton.setEnabled( true );
             JOptionPane.showMessageDialog( this, "No more records in file",
                "End of File", JOptionPane.ERROR_MESSAGE );
          // display error message if class is not found
          catch ( ClassNotFoundException classNotFoundException ) {
             JOptionPane.showMessageDialog( this, "Unable to create object",
                "Class Not Found", JOptionPane.ERROR_MESSAGE );
          // display error message if cannot read due to problem with file
          catch ( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error during read from file",
                "Read Error", JOptionPane.ERROR_MESSAGE );
       } // end method readRecord
    //from read end
    // from read
    private void getNextRecord()
               Employee record = employeeList[next++%count];//cycles throught accounts
          //create aray of string to display in GUI
          String values[] = {String.valueOf(record.getName()),
             String.valueOf(record.getGender()),
              String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
         String.valueOf( record.getNatInsNo()),
         String.valueOf( record.getPhone()),
             String.valueOf( record.getID() ),
               String.valueOf( record.getDateOfBirth() ),
         String.valueOf( record.getSalary() ) };
         //display record contents
         userInterface.setFieldValues(values);
         //display record contents
    // from read end
       // close file and terminate application
       private void closeFile()
          // close file
          try {
                                            int storeSize = store.getCount();
                                            for (int i = 0; i<storeSize;i++)
                                            output.writeObject(store.elementAt(i));
             output.close();
    input.close(); // from read
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0)); // check if m or f prob check in employee
    if ( employeeNumber >= 0 ) {
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                             output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new togehter();
    } // end class CreateSequentialFileI GOT IT WORKING BUT THERE WAS A WEIRD ERROR I GET WHEN TRYING TO READ A FILE I JUST WROTE THE THREAD FOR THAT CAN BE FOUND:
    http://forum.java.sun.com/thread.jspa?threadID=5147209
    Message was edited by:
    ajrobson

  • Random access files

    This program is supposed to retrieve data from TelephoneUI's JTextFields, store the data in a RandomAccessRecord class object record and call the write method of class RandomAccessRecord to output the data.
    Two questions
    Is there any way to check if the data was actually written to the file without writing a new class to read the file?
    How can I make it so that the file-position pointer for object output start from byte 0 for the first record and move 94 bytes after each read? Right now the file-position pointer moves 94 bytes after each read but starts from 94.
    public class WriteRandomFile extends JFrame {  
       private RandomAccessFile output;
       private TelephoneUI userInterface;
       private JButton enterButton, openButton;
       // set up GUI
       public WriteRandomFile()
          super( "Write to random access file" );
          // create instance of reusable user interface TelephoneUI
          userInterface = new TelephoneUI(4);  // four textfields
          getContentPane().add( userInterface,
             BorderLayout.CENTER );
          // get reference to generic task button doTask1 in TelephoneUI
          openButton = userInterface.getDoTask1Button();
          openButton.setText( "Open..." );
          // register listener to call openFile when button pressed
          openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // allow user to select file to open
                public void actionPerformed( ActionEvent event )
                   openFile();
             }  // end anonymous inner class
          ); // end call to addActionListener
          // register window listener for window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add record in TelephoneUI, then close file
                public void windowClosing( WindowEvent event )
                   if ( output != null )
                      addRecord();
                   closeFile();
             }  // end anonymous inner class
          ); // end call to addWindowListener
          // get reference to generic task button doTask2 in TelephoneUI
          enterButton = userInterface.getDoTask2Button();
          enterButton.setText( "Enter" );
          enterButton.setEnabled( false );
          // register listener to call addRecord when button pressed
          enterButton.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // add record to file
                public void actionPerformed( ActionEvent event )
                   addRecord();
             }  // end anonymous inner class
          ); // end call to addActionListener
          setSize( 300, 150 );
          show(); 
       // enable user to choose file to open
       private void openFile()
          // display file dialog so user can select file
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode(
             JFileChooser.FILES_ONLY );
          int result = fileChooser.showOpenDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          // obtain selected file
          File fileName = fileChooser.getSelectedFile();
          // display error if file name invalid
          if ( fileName == null ||
               fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this,
                "Invalid File Name", "Invalid File Name",
                JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new RandomAccessFile( fileName, "rw" );
                enterButton.setEnabled( true );
                openButton.setEnabled( false );
             // process exception while opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this,
                   "File does not exist",
                   "Invalid File Name",
                   JOptionPane.ERROR_MESSAGE );
       }  // end method openFile
       // close file and terminate application
       private void closeFile()
          // close file and exit
          try {
             if ( output != null )
                output.close();
               System.exit( 0 );
          // process exception while closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this,
                "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       // add one record to file
       public void addRecord()
          String fields[] = userInterface.getFieldValues();
          RandomAccessRecord record =
             new RandomAccessRecord();
          int count = 1;
          // ensure field has a value
          if ( ! fields[ TelephoneUI.LASTNAME ].equals( "" ) ) {
             // output values to file
             try {
                   record.setFirstName( fields[ TelephoneUI.FIRSTNAME ] );
                   record.setLastName( fields[ TelephoneUI.LASTNAME ] );
                   record.setAddress( fields[ TelephoneUI.ADDRESS ] );
                   record.setPhone( Integer.parseInt( fields[ TelephoneUI.PHONENUMBER ] ) );
                             count = count * 94;
                             output.seek( count );
                   record.write( output );
                userInterface.clearFields();  // clear TextFields
             // process improper account number or balance format
             catch ( NumberFormatException formatException ) {
                    JOptionPane.showMessageDialog( this,
                       "Bad account number or balance",
                       "Invalid Number Format",
                       JOptionPane.ERROR_MESSAGE );
             // process exceptions while writing to file
             catch ( IOException ioException ) {
                closeFile();
       }  // end method addRecord
       // execute application
       public static void main( String args[] )
          new WriteRandomFile();
    }  // end class WriteRandomFile

    This program is supposed to retrieve data from
    TelephoneUI's JTextFields, store the data in a
    RandomAccessRecord class object record and call the
    write method of class RandomAccessRecord to output
    the data.
    Two questions
    Is there any way to check if the data was actually
    written to the file without writing a new class to
    read the file? Why? If the io operations are not working (and not throwing exceptions) then you might as well give up.
    >
    How can I make it so that the file-position pointer
    for object output start from byte 0 for the first
    record and move 94 bytes after each read? Right now
    the file-position pointer moves 94 bytes after each
    read but starts from 94.Huh? It moves 94 and you want it to move 94?
    Perhaps you are just looking for the getFilePointer() and seek() methods?
    >
    public class WriteRandomFile extends JFrame {
    private RandomAccessFile output;
    private TelephoneUI userInterface;
    private JButton enterButton, openButton;
    // set up GUI
    public WriteRandomFile()
    super( "Write to random access file" );
    // create instance of reusable user interface
    erface TelephoneUI
    userInterface = new TelephoneUI(4);  // four
    / four textfields
    getContentPane().add( userInterface,
    BorderLayout.CENTER );
    // get reference to generic task button doTask1
    oTask1 in TelephoneUI
    openButton = userInterface.getDoTask1Button();
    openButton.setText( "Open..." );
    // register listener to call openFile when
    e when button pressed
    openButton.addActionListener(
    // anonymous inner class to handle
    to handle openButton event
    new ActionListener() {
    // allow user to select file to open
    public void actionPerformed( ActionEvent
    ActionEvent event )
    openFile();
    }  // end anonymous inner class
    ); // end call to addActionListener
    // register window listener for window closing
    losing event
    addWindowListener(
    // anonymous inner class to handle
    to handle windowClosing event
    new WindowAdapter() {
    // add record in TelephoneUI, then close
    , then close file
    public void windowClosing( WindowEvent
    WindowEvent event )
    if ( output != null )
    addRecord();
    closeFile();
    }  // end anonymous inner class
    ); // end call to addWindowListener
    // get reference to generic task button doTask2
    oTask2 in TelephoneUI
    enterButton =
    tton = userInterface.getDoTask2Button();
    enterButton.setText( "Enter" );
    enterButton.setEnabled( false );
    // register listener to call addRecord when
    d when button pressed
    enterButton.addActionListener(
    // anonymous inner class to handle
    to handle enterButton event
    new ActionListener() {
    // add record to file
    public void actionPerformed( ActionEvent
    ActionEvent event )
    addRecord();
    }  // end anonymous inner class
    ); // end call to addActionListener
    setSize( 300, 150 );
    show(); 
    // enable user to choose file to open
    private void openFile()
    // display file dialog so user can select file
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setFileSelectionMode(
    JFileChooser.FILES_ONLY );
    int result = fileChooser.showOpenDialog( this
    ( this );
    // if user clicked Cancel button on dialog,
    ialog, return
    if ( result == JFileChooser.CANCEL_OPTION )
    return;
    // obtain selected file
    File fileName = fileChooser.getSelectedFile();
    // display error if file name invalid
    if ( fileName == null ||
    fileName.getName().equals( "" ) )
    JOptionPane.showMessageDialog( this,
    "Invalid File Name", "Invalid File
    Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    else {
    // open file
    try {
    output = new RandomAccessFile( fileName,
    e( fileName, "rw" );
    enterButton.setEnabled( true );
    openButton.setEnabled( false );
    // process exception while opening file
    catch ( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "File does not exist",
    "Invalid File Name",
    JOptionPane.ERROR_MESSAGE );
    }  // end method openFile
    // close file and terminate application
    private void closeFile()
    // close file and exit
    try {
    if ( output != null )
    output.close();
               System.exit( 0 );
    // process exception while closing file
    catch( IOException ioException ) {
    JOptionPane.showMessageDialog( this,
    "Error closing file",
    "Error", JOptionPane.ERROR_MESSAGE );
    System.exit( 1 );
    // add one record to file
    public void addRecord()
    String fields[] =
    ds[] = userInterface.getFieldValues();
    RandomAccessRecord record =
    new RandomAccessRecord();
    int count = 1;
    // ensure field has a value
    if ( ! fields[ TelephoneUI.LASTNAME ].equals(
    quals( "" ) ) {
    // output values to file
    try {
    record.setFirstName( fields[
    stName( fields[ TelephoneUI.FIRSTNAME ] );
    record.setLastName( fields[
    stName( fields[ TelephoneUI.LASTNAME ] );
    record.setAddress( fields[
    ddress( fields[ TelephoneUI.ADDRESS ] );
    record.setPhone( Integer.parseInt(
    teger.parseInt( fields[ TelephoneUI.PHONENUMBER ] )
                             count = count * 94;
                             output.seek( count );
    record.write( output );
    userInterface.clearFields();  // clear
    );  // clear TextFields
    // process improper account number or
    number or balance format
    catch ( NumberFormatException
    Exception formatException ) {
    JOptionPane.showMessageDialog( this,
    "Bad account number or balance",
    "Invalid Number Format",
    JOptionPane.ERROR_MESSAGE );
    // process exceptions while writing to file
    catch ( IOException ioException ) {
    closeFile();
    }  // end method addRecord
    // execute application
    public static void main( String args[] )
    new WriteRandomFile();
    }  // end class WriteRandomFile

  • Facing problem inside the implementation of ActionListener

    Hi, I don't understand what the problem is. Please go through the following code. The explanation of the problem is documented.
    Any kind of help is appreciated.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    * Class Test is intended for receiving a String input from the user and
    * manipulating the input string later in some other methods. So the input
    * string has to be stored for later use.
    * Whenever an action takes place in JTextField or JButton (OK button) component,
    * the corresponding ActionListener's actionPerformed() method assigns the
    * user input to 'userInput' referene variable. This was assured when I placed
    *              JOptionPane.showMessageDialog(frame, userInput);
    * right after the assignment statement. But when I cut and pasted the above
    * statement right after the getUserInput() method call (in constructor's body)
    * it showed null string.
    * WHY & HOW this happens?
    * I could have implemented this application with the help of JOptionPane's
    * showInputDialog() method. But I just want to know what the problem is if
    * I have tried in this way.
    public class Test {
         * String that the user types
        private String userInput;
         * Text field that contains the user input.
        private JTextField inputTextField;
         * Frame that contains all other components
        private JFrame frame;
        public Test() {
            prepareFrame();
            getUserInput();
            // shows null, why?????
            JOptionPane.showMessageDialog(frame, userInput);
            // some other methods goes here that uses the input string....
            // methodA();
            // methodB();
         * Creates the frame and sets some of its properties.
        private void prepareFrame() {
            frame = new JFrame("Experiment with ActionListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setVisible(false);
         * Receives user input and stores the reference to user input in userInput.
        private void getUserInput() {
            // Create sub-components
            JLabel promptLabel = new JLabel("Enter a string: ");
            inputTextField = new JTextField(20);
            JButton okButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            // Add listeners
            inputTextField.addActionListener(new TextFieldHandler());
            okButton.addActionListener(new OkButtonHandler());
            cancelButton.addActionListener(new CancelButtonHandler());
            // Create a panel to contain the sub-components
            JPanel panel = new JPanel();
            // Add the sub-components to the panel
            panel.add(promptLabel);
            panel.add(inputTextField);
            panel.add(okButton);
            panel.add(cancelButton);
            frame.add(panel, BorderLayout.NORTH);
            frame.validate();
            frame.setVisible(true);
         * Event handler for text field that contains user input.
        private class TextFieldHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                userInput = event.getActionCommand();
                // works fine if the user input is shown here.
                // JOptionPane.showMessageDialog(frame, userInput);
         * Event handler for OK button
        private class OkButtonHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                userInput = inputTextField.getText();
                // works fine if the user input is shown here.
                // JOptionPane.showMessageDialog(frame, userInput);
         * Event handler for Cancel button
        private class CancelButtonHandler
                implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
        public static void main(String[] args) {
            new Test();
    }

    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.JButton;
    import java.awt.BorderLayout;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.JOptionPane;
    public class T {
        private String userInput;
        private JTextField inputTextField;
        private JFrame frame;
        public T() {
            prepareFrame();
            getUserInput();
            // shows null, why?????
            // userInput is null because it has not been given a value
            // you can give it a value in the declaration as a member
            // variable above or here in your class constructor
            System.out.println("userInput = " + userInput);
            JOptionPane.showMessageDialog(frame, userInput);
            // some other methods goes here that uses the input string....
            // methodA();
            // methodB();
        private void prepareFrame() {
            frame = new JFrame("Experiment with ActionListener");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setSize(500, 300);
            frame.setVisible(false);
        private void getUserInput() {
            // Create sub-components
            JLabel promptLabel = new JLabel("Enter a string: ");
            inputTextField = new JTextField(20);
            JButton okButton = new JButton("OK");
            JButton cancelButton = new JButton("Cancel");
            // Add listeners
            inputTextField.addActionListener(new TextFieldHandler());
            okButton.addActionListener(new OkButtonHandler());
            cancelButton.addActionListener(new CancelButtonHandler());
            // Create a panel to contain the sub-components
            JPanel panel = new JPanel();
            // Add the sub-components to the panel
            panel.add(promptLabel);
            panel.add(inputTextField);
            panel.add(okButton);
            panel.add(cancelButton);
            frame.add(panel, BorderLayout.NORTH);
            frame.validate();
            frame.setVisible(true);
        private class TextFieldHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                // userInput is given a value here so it is no longer null
                userInput = event.getActionCommand();
                // works fine if the user input is shown here.
                System.out.println("userInput = " + userInput);
                JOptionPane.showMessageDialog(frame, userInput);
        private class OkButtonHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                // userInput is given a value here so it is no longer null
                userInput = inputTextField.getText();
                // works fine if the user input is shown here.
                System.out.println("userInput = " + userInput);
                JOptionPane.showMessageDialog(frame, userInput);
        private class CancelButtonHandler implements ActionListener {
            public void actionPerformed(ActionEvent event) {
                System.exit(0);
        public static void main(String[] args) {
            new T();
    }

  • JFrame which does not allow resizing (maximizing, minimizng)

    I want to develop a login frame which does not allow resizing (maximizing, minimizing as this does not make sense) and with 2 fields, JTextField and JPasswordField.
    The frame is developed but has the usual resizing handles.
    How to do?
    Many tks for any information.
    John Pashley

    Don't use a JFrame. Also, don't expect code like this again; I did it for fun.
    It requires your modification.
    * Title:        Login Screen<p>
    * Description:  Login Screen<p>
    * Class:        Login ScreenLoginScreen<p>
    * Copyright:    who cares<p>
    * Company:      who cares<p>
    * @author who cares
    * @version who cares
    import java.awt.*;
    import java.awt.event.*;
    import java.net.URL;
    import java.util.Vector;
    import java.io.File;
    import javax.swing.*;
    public class LoginScreen extends JDialog implements ActionListener, FocusListener
       private JTextField      name;
       private JPasswordField  password;
       private JButton         loginButton;
       private JButton         cancelButton;
       private JDialog         thisDialog = this;
       private ImageIcon       splashImage;
       private String          appTitle;
       private int             logCounter;
       public LoginScreen()
          super();
          this.toFront();
          setTitle("Login");
          addWindowListener(new WindowAdapter()
             public void windowClosing(WindowEvent e)
                    System.exit(0);
          getContentPane().setLayout(new BorderLayout());
          splashImage = new ImageIcon( getClass().getResource("images" + File.separator + "image.jpg")) );
          getContentPane().add(new JLabel(splashImage), "North");
          getContentPane().add(makeLoginPanel(), "Center");
          getContentPane().add(makeButtonPanel(), "South");
          pack();
          setResizable(false);
          setLocationRelativeTo(null);
          setVisible(true);
        * make login panel
       private JPanel makeLoginPanel()
          JPanel loginPanel = new JPanel();
          JLabel label;
          loginPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20));
          GridBagLayout gbl = new GridBagLayout();
          GridBagConstraints gbc = new GridBagConstraints();
          loginPanel.setLayout(gbl);
          gbc.weightx = 1.0;
          gbc.fill = GridBagConstraints.HORIZONTAL;
          gbc.insets = new Insets(0, 5, 10, 5);
          gbc.gridx = 0;
          gbc.gridy = 0;
          label = new JLabel("Login Name:", SwingConstants.LEFT);
          gbl.setConstraints(label, gbc);
          loginPanel.add(label);
          gbc.gridx = 1;
          name = new JTextField("insider", 10);
          name.addFocusListener(this);
          gbl.setConstraints(name, gbc);
          loginPanel.add(name);
          gbc.gridx = 0;
          gbc.gridy = 1;
          label = new JLabel("Password:", SwingConstants.LEFT);
          gbl.setConstraints(label, gbc);
          loginPanel.add(label);
          gbc.gridx = 1;
          password = new JPasswordField("insider",10);
          password.addFocusListener(this);
          gbl.setConstraints(password, gbc);
          loginPanel.add(password);
          return loginPanel;
        * make button panel
       private JPanel makeButtonPanel()
          JPanel buttonPanel = new JPanel();
          buttonPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
          //make LogIn button
          loginButton = new JButton("Login");
          loginButton.setActionCommand("Login");
          buttonPanel.add(loginButton);
          rootPane.setDefaultButton(loginButton);
          loginButton.addActionListener(this);
          this.getRootPane().setDefaultButton(loginButton);
          //make Cancel button
          cancelButton = new JButton("Cancel");
          cancelButton.setActionCommand("Cancel");
          buttonPanel.add(cancelButton);
          cancelButton.addActionListener(this);
          this.addKeyListener(new KeyAdapter()
             public void keyReleased(KeyEvent e)
                if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
                   cancelButton.doClick();
             return buttonPanel;
        * Action handler for login and cancel buttons
       public void actionPerformed(ActionEvent e)
          JButton btn = (JButton) e.getSource();
          if (btn.getActionCommand().equals("Login"))
             // Because login() process happens before swing process (above),
             // force it to happen "later"
             SwingUtilities.invokeLater(new Runnable()
                public void run()
                   login(); //create this method, okay?!
          else if (btn.getActionCommand().equals("Cancel"))
             System.exit(0);
        * Focus gained handler for username and password buttons
       public void focusGained(FocusEvent e)
          JTextField tf = (JTextField) e.getSource();
          tf.selectAll();
        * Focus lost handler for username and password buttons
       public void focusLost(FocusEvent e) {}
       private void showErrorMessage(String message, String header)
          JOptionPane.showMessageDialog(getContentPane(),
                                        message, header,
                                        JOptionPane.ERROR_MESSAGE);
        * This method controls the cursor for login window. If isWait is set to
        * true, dialog's cursor is set to Cursor.WAIT_CURSOR. If isWait is set
        * to false, the cursor is set ta Deafult.
        * While the window is in WAIT mode, this method will also disable Login
        * and Cancel buttons to ensure the user does not accidently request
        * a cancel while loging in or launching a second login.
       private void setWaitCursor(boolean isWait)
          /* In order to disable login and cancel buttons while logging in to the
             application, this method will temporarely change action commands and
             reset them when login process failed to give user another chance.
             Note: Disabling the buttons by calling setEnabled(false) did not work
             since login() method is called from an action event handler and the
             process will not be released to AWT until login method is complete.
          if (isWait)
             this.getGlassPane().setCursor(new Cursor(Cursor.WAIT_CURSOR));
             this.getGlassPane().setVisible(true);
             loginButton.setActionCommand("none");
             cancelButton.setActionCommand("none");
          else
             this.getGlassPane().setCursor(Cursor.getDefaultCursor());
             this.getGlassPane().setVisible(false);
             loginButton.setActionCommand("Login");
             cancelButton.setActionCommand("Cancel");
    } //end loginscreen

  • Problems displaying deserialized components

    I'm trying to save the state of some objects which extend JComponent and JLayeredPane, and they don't all redisplay on deserializing, although they seem to be in the containment tree.
    Basically, I have a class GamePanel which extends JLayeredPane. Also classes Square and Region both of which extend JComponent and use 2D graphics for painting themselves. It seems to serialize OK (but how does one tell?). But when I deserialize, only the lower level of the GamePanel is painted. However, the higher level is populated.
    Does anyone have any idea why they're not displaying? The code is below (TestKiller and its menus are generated by NetBeans - hence the slightly odd code). There are 5 menu items (I've simplified a lot from the original so it's a bit clunky): Add Region (you can only do this once in this version), Save As which serializes to a file, Restore which deserializes from a file, Exit which is obvious and Print which outputs the containment hierarchy of GamePanel to standard output.
    If you want to try it out, fire up the program, do a File|Add to add a Region (see the dotted lines) and File|Print to see that there's a Square at level 2 and a Region at level 3. Then File|Save as... to save it. Quit the program.
    Fire it up again and do a File|Restore and a File|Print. You'll see from the output that the Square and Region are there with identical parameters to the output before, but the Region hasn't displayed its outline.
    The output's below, with java-like comments added to show what I've done:
    D:>java -jar test*
    Painting gridlayer
    // File|Add Region
    New region 1
    Selecting square
    Checking region 1
    Painting gridlayer
    Painting region 1
    //File|Print
    Printing Gamepanel components
    com.ptoye.TestSBug1.Region[Region-1,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minim
    umSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 3
    com.ptoye.TestSBug1.Square[Square-0:0,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSi
    ze=,minimumSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 2
    \\File|Save
    Saving game to bug1.ksd
    D:>java -jar test*
    Painting gridlayer
    \\File|Restore
    Restoring game bug1.ksd
    Restored
    \\File|Print - same as above but only Square is displayed
    Printing Gamepanel components
    com.ptoye.TestSBug1.Region[Region-1,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=0,maximumSize=,minim
    umSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 3
    com.ptoye.TestSBug1.Square[Square-0:0,4,4,60x60,alignmentX=0.0,alignmentY=0.0,border=,flags=16777224,maximumSi
    ze=,minimumSize=,preferredSize=]
    Bounds java.awt.Rectangle[x=4,y=4,width=60,height=60]
    Layer 2
    D:>
    Please someone tell me what I'm doing wrong. As a serialization newbie it's probably something simple, but no amount of validate() and pack() makes any difference.
    The code's below - a bit long I'm afraid but it's difficult to cut it down much more and display the problem. The main class (TestKiller) was generated by NetBeans.
    * TestKiller.java
    * Created on 01 August 2006, 22:13
    package com.ptoye.TestSBug1;
    import java.io.File;
    import java.io.FileFilter;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import javax.swing.JFileChooser;
    import javax.swing.JOptionPane;
    * @author  PToye
    public class TestKiller extends javax.swing.JFrame {
      private GamePanel p;
      final String fileExtension="ksd";
       * Creates new form TestKiller
      public TestKiller() {
        initComponents();
        p=new GamePanel();
        setContentPane(p);
        p.setOpaque(true);
        setSize(p.getPreferredSize());
        pack();
      public static void showMessage(String s) {
        JOptionPane.showMessageDialog(null,s,"Error",JOptionPane.ERROR_MESSAGE);
      /** This method is called from within the constructor to
       * initialize the form.
       * WARNING: Do NOT modify this code. The content of this method is
       * always regenerated by the Form Editor.
      private void initComponents() {                         
        jMenuBar1 = new javax.swing.JMenuBar();
        jmFile = new javax.swing.JMenu();
        jmiAddRegion = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jmiSaveAs = new javax.swing.JMenuItem();
        jmiRestore = new javax.swing.JMenuItem();
        jmiExit = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jmiPrint = new javax.swing.JMenuItem();
        FormListener formListener = new FormListener();
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Restore bug");
        jmFile.setText("File");
        jmiAddRegion.setText("Add region");
        jmiAddRegion.addActionListener(formListener);
        jmFile.add(jmiAddRegion);
        jmFile.add(jSeparator2);
        jmiSaveAs.setMnemonic('s');
        jmiSaveAs.setText("Save as...");
        jmiSaveAs.addActionListener(formListener);
        jmFile.add(jmiSaveAs);
        jmiRestore.setMnemonic('r');
        jmiRestore.setText("Restore");
        jmiRestore.addActionListener(formListener);
        jmFile.add(jmiRestore);
        jmiExit.setMnemonic('x');
        jmiExit.setText("Exit");
        jmiExit.addActionListener(formListener);
        jmFile.add(jmiExit);
        jmFile.add(jSeparator1);
        jmiPrint.setText("Print");
        jmiPrint.addActionListener(formListener);
        jmFile.add(jmiPrint);
        jMenuBar1.add(jmFile);
        setJMenuBar(jMenuBar1);
        pack();
      // Code for dispatching events from components to event handlers.
      private class FormListener implements java.awt.event.ActionListener {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
          if (evt.getSource() == jmiSaveAs) {
            TestKiller.this.jmiSaveAsActionPerformed(evt);
          else if (evt.getSource() == jmiRestore) {
            TestKiller.this.jmiRestoreActionPerformed(evt);
          else if (evt.getSource() == jmiExit) {
            TestKiller.this.jmiExitActionPerformed(evt);
          else if (evt.getSource() == jmiPrint) {
            TestKiller.this.jmiPrintActionPerformed(evt);
          else if (evt.getSource() == jmiAddRegion) {
            TestKiller.this.jmiAddRegionActionPerformed(evt);
      private void jmiAddRegionActionPerformed(java.awt.event.ActionEvent evt) {                                            
        p.dummyAdd();
        jmiAddRegion.setEnabled(false);
      private void jmiPrintActionPerformed(java.awt.event.ActionEvent evt) {                                        
        p.print();
      private void jmiSaveAsActionPerformed(java.awt.event.ActionEvent evt) {                                         
        File f;
        ObjectOutputStream oos=null;
        JFileChooser jfc=new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setMultiSelectionEnabled(false);
        jfc.addChoosableFileFilter(jfc.getAcceptAllFileFilter());
        jfc.addChoosableFileFilter(new KDSFileFilter());
        jfc.showSaveDialog(this);
        f=jfc.getSelectedFile();
        if (f==null) {
          showMessage("Null file found");
        int i=f.getName().lastIndexOf(".");
        if (i==-1) {
          f=new File(f.getAbsolutePath()+"."+fileExtension);
        try {
          oos=new ObjectOutputStream(new FileOutputStream(f));
        } catch (FileNotFoundException ex) {
          showMessage("Cannot find file "+f.getName());
          return;
        } catch (IOException ex) {
          showMessage("Cannot open file "+f.getName());
          return;
        if (oos!=null) {
          System.out.println("Saving game to "+f.getName());
          try {
            oos.writeObject(p);
          } catch (IOException ex) {
            showMessage("Cannot write game to "+f.getName()+"\n"+ex.getMessage());
          } finally {
            try {
              oos.close();
            } catch (IOException ex) {
      private void jmiExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
        System.exit(0);
      private void jmiRestoreActionPerformed(java.awt.event.ActionEvent evt) {                                          
        File f;
        ObjectInputStream ois=null;
        JFileChooser jfc=new JFileChooser();
        jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        jfc.setMultiSelectionEnabled(false);
        jfc.addChoosableFileFilter(jfc.getAcceptAllFileFilter());
        jfc.addChoosableFileFilter( new KDSFileFilter());
        jfc.showOpenDialog(this);
        f=jfc.getSelectedFile();
        if (f!=null) {
          try {
            ois=new ObjectInputStream(new FileInputStream(f));
          } catch (FileNotFoundException ex) {
            showMessage("Cannot find file "+f.getName());
            return;
          } catch (IOException ex) {
            showMessage("Cannot open file "+f.getName());
            return;
          if (ois!=null) {
            System.out.println("Restoring game "+f.getName());
            try {
              p=(GamePanel) ois.readObject();
            } catch (IOException ex) {
              showMessage("Cannot read game from file "+f.getName());
            } catch (ClassNotFoundException ex) {
              showMessage("Cannot restore game - wrong object type");
            try {
              ois.close();
            } catch (IOException ex) {
            pack();
            p.validate();
            p.repaint();
            System.out.println("Restored");
      private class KDSFileFilter extends javax.swing.filechooser.FileFilter {
        public boolean accept(File f) {
          if (f.isDirectory()) {
            return true;
          String ext = null;
          String s = f.getName();
          int i = s.lastIndexOf('.');
          if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
          return (ext==null || ext.equalsIgnoreCase(fileExtension));
        public String getDescription() {
          return "Killer Su Doku games";
       * @param args the command line arguments
      public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
          public void run() {
            new TestKiller().setVisible(true);
      // Variables declaration - do not modify                    
      private javax.swing.JMenuBar jMenuBar1;
      private javax.swing.JSeparator jSeparator1;
      private javax.swing.JSeparator jSeparator2;
      private javax.swing.JMenu jmFile;
      private javax.swing.JMenuItem jmiAddRegion;
      private javax.swing.JMenuItem jmiExit;
      private javax.swing.JMenuItem jmiPrint;
      private javax.swing.JMenuItem jmiRestore;
      private javax.swing.JMenuItem jmiSaveAs;
      // End of variables declaration                  
    * GamePanel.java
    * Created on 10 January 2007, 18:45
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Set;
    import javax.swing.JLayeredPane;
    * @author PToye
    public class GamePanel extends JLayeredPane implements Serializable {
      private static final int GRID_LEVEL=2;
      private static final int REGIONS_LEVEL=3;
      private static final int THICK_WIDTH=4;
      private static final int THIN_WIDTH=1;
      static final int SQUARE_SIZE=60;
      private static final int SQUARES=1;  // test size
      static final int BIGSQUARES=SQUARES*SQUARES;
      static final int TotalSize=(SQUARES+1)*THICK_WIDTH+SQUARES*(SQUARES-1)*THIN_WIDTH+
          BIGSQUARES*SQUARE_SIZE;
      public final Color NORMAL_BACK_COLOUR=Color.WHITE;
      public final Color SELECTED_BACK_COLOUR=Color.PINK;
      int coordArray;  // used to be an array of start coords of each square
      private Region newRegion;
      private int regionId=1;
      private Square squareArray; // used to be an array
      private Region regions; // used to be a set
      /** Creates a new instance of GamePanel */
      public GamePanel() {
        super();
        regions=null;
        makeGridLayer();  //adds the white square
        setPreferredSize(new Dimension(TotalSize,TotalSize));
        setVisible(true);
        newRegion=null;
        setFocusable(true);
      public void dummyAdd() {
        setupRegion(squareArray);
        if (newRegion.checkNewRegion(1)) {
          addRegion(newRegion);
      public void addRegion(Region r) {
        if (regions==null) {
          regions=r;
          add(r,new Integer(REGIONS_LEVEL));
          r.repaint();
      void print() {
        Component[] cList=getComponents();
        System.out.println("Printing Gamepanel components");
        for (int i = 0; i < cList.length; i++) {
          Component c=cList;
    System.out.println(c.toString());
    System.out.println(" Bounds "+c.getBounds());
    System.out.println(" Layer "+getLayer(c));
    if (c instanceof Container) {
    printContainer((Container)c," ");
    void printContainer(Container c, String preString) {
    Component[] cList1=c.getComponents();
    for (int i = 0; i < cList1.length; i++) {
    Component comp=cList1[i];
    System.out.println(preString+comp.toString());
    System.out.println(preString+" Bounds "+comp.getBounds());
    if (comp instanceof Container) {
    printContainer((Container)comp,preString+" ");
    private void setupRegion(Square s) {
    if (newRegion==null) {
    newRegion=new Region(regionId++,this);
    Region r=s.getRegion();
    if (r==null) {
    newRegion.addSquare(s);
    selectSquare(s);
    s.setRegion(newRegion);
    } else {
    System.exit(1); // should not happen
    private void makeGridLayer() {
    int currentXCoord;
    int currentYCoord;
    int arrayIndex=0;
    Square sq;
    currentXCoord=THICK_WIDTH;
    currentYCoord=THICK_WIDTH;
    coordArray=currentYCoord;
    sq=new Square(0,0, NORMAL_BACK_COLOUR,this);
    add(sq,new Integer(GRID_LEVEL));
    squareArray=sq;
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    System.out.println("Painting gridlayer");
    g2.setBackground(Color.BLACK);
    g2.setColor(Color.BLACK);
    g2.fillRect(0,0,TotalSize,TotalSize);
    void selectSquare(Square s) {
    System.out.println("Selecting square");
    s.setBackColour(SELECTED_BACK_COLOUR);
    * Square.java
    * Created on 28 December 2006, 15:53
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.io.Serializable;
    import javax.swing.JComponent;
    * @author PToye
    class Square extends JComponent implements Serializable {
    * X index in grid
    private int xIndex;
    * Y index in grid
    private int yIndex;
    * The square's parent grid
    private GamePanel parent;
    * Region it belongs to (or null if none)
    private Region region;
    * The background colour
    private Color backColour;
    private boolean marked;
    // public Square() {
    // System.out.println("New Square - null constructor");
    // addMouseListener(parent);
    * Create a new square
    public Square(int x, int y, Color bcol, GamePanel parent) {
    this.parent=parent;
    xIndex=x;
    yIndex=y;
    backColour=bcol;
    region=null;
    setName("Square-"+x+":"+y);
    setBounds(parent.coordArray,parent.coordArray,
    GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    setOpaque(true);
    setVisible(true);
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    // System.out.println("Painting square "+xIndex+","+yIndex+":"+getBounds());
    g2.setColor(backColour);
    g2.fillRect(0,0,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    g2.setColor(Color.BLACK);
    public Dimension getPreferredSize() {
    return new Dimension(GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    public void setBackColour(Color backColour) {
    this.backColour = backColour;
    repaint(0,0,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    public Region getRegion() {
    return region;
    public void setRegion(Region region) {
    this.region = region;
    * Region.java
    * Created on 28 December 2006, 15:59
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package com.ptoye.TestSBug1;
    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.GeneralPath;
    import java.io.Serializable;
    import java.util.HashSet;
    import java.util.Iterator;
    import java.util.Set;
    import javax.swing.JComponent;
    * @author PToye
    * Class representing a region whose total sum is known
    public class Region extends JComponent implements Serializable {
    private static final float BORDER_WIDTH=1f;
    private static final float DASH_LENGTH=4f;
    private static final float[] dashes={DASH_LENGTH,DASH_LENGTH};
    private static final BasicStroke borderStroke=
    new BasicStroke(BORDER_WIDTH,BasicStroke.CAP_BUTT,BasicStroke.JOIN_MITER,
    1f,dashes,0);
    private static final int borderInset=3;
    private GamePanel parent;
    * The sum as given
    private int total;
    private String totalString;
    private int id;
    * The squares constituting the region
    private Square contents; // the square in the region
    private Square leadSquare; // top left-hand square
    private int leadXCoord,leadYCoord; // X, Y coords of lead square wrt border
    private GeneralPath border=null;
    public Region(int id, GamePanel parent) {
    super();
    this.id=id;
    this.parent=parent;
    setName("Region-"+id);
    contents=null;
    border=new GeneralPath();
    System.out.println("New region "+id);
    public void addSquare(Square s) {
    if (contents!=null) {
    contents=s;
    public boolean checkNewRegion(int tot) {
    System.out.println("Checking region "+id);
    border.moveTo(borderInset,borderInset);
    border.lineTo(GamePanel.SQUARE_SIZE-borderInset,borderInset);
    border.lineTo(GamePanel.SQUARE_SIZE-borderInset,GamePanel.SQUARE_SIZE-borderInset);
    border.lineTo(borderInset,GamePanel.SQUARE_SIZE-borderInset);
    border.lineTo(borderInset,borderInset);
    setBounds(parent.coordArray,parent.coordArray,GamePanel.SQUARE_SIZE,GamePanel.SQUARE_SIZE);
    repaint();
    return true;
    public void paintComponent(Graphics g) {
    int newX, newY;
    System.out.println("Painting region "+id);
    super.paintComponent(g);
    Graphics2D g2=(Graphics2D) g;
    g2.setColor(Color.BLACK);
    g2.setStroke(borderStroke);
    g2.draw(border);

    OK, I asked the FTE team and got this reply: "Lucida Grande is CTS's fallback font for Thai.  This font on OS 10.7 and 10.6 are not supporting Thai anymore.  The version on 10.5 was supporting it." This means that it's our bug that we keep using Lucida Grande as fallback font even Apple dropped support Thai script with that font after 10.6. Unfortunately this bug was deferred from current development release (11.2) because of time constraint. If this support is critical for your business, can you open a bug in our public bugbase and ask as many vote as possible? In this way I may be able to convince internal team to fix this bug in next release.
    Thank you for your feedback!
    Hitomi

Maybe you are looking for

  • Graphic Design on a PC vs Mac

    Just wanted to get some opinions my current situation. I went from designing on a PC for 4 1/2 years to a new job which has an iMac. My concerns are that I'm off the network, am the only one on an Apple, have less functionality than people have with

  • Unable to install Windows 8 updates error code 0x800736B3 and 0x80246007.

    Hi I am having issues with the Asus Transformer tablet/laptop TX300CA. It comes with Windows 8 Pro. After downloading windows 8 updates, it doesn't want to install all of the software updates. I received an error code such as 0x800736B3. Can anyone h

  • Formating problems when printing from googlemail text program

    I often use the text program in my google mail account to write letters. However when I click on print preview the format is altered in an undesireable way. How can I avoid such unwanted format changes?

  • Invoice cancellation issue!!

    Hi All, I have a inovice cancellation issue. A PO was created in the year 2007 & an inovice was posted for the same. The tax rate at that time, when the PO was created & the invoice posted was 6% but now the tax rate is 5% and when I try to cancel th

  • Won't remember media folder on NAS

    Greetings, I moved my iTunes to my NAS without issue, but one has shown up... Each time I reboot my iMac, iTunes cannot find the library and I go through the procedure of choosing another library....wherein I get it connected to iTunes library folder