Problem With ActionPerformed!!

Ok so ive been writing a application to take buttons presses and then give an output ive created my layout and my button arrays and i keep getting the following errors when i try to add anything to the actionperformed method:
---------- javac ----------
E:\JavaCoursework\ParkingPaymentTest.java:99: cannot resolve symbol
symbol  : variable getSource
location: class java.awt.event.ActionEvent
          if (e.getSource == time[0])
                     ^
E:\JavaCoursework\ParkingPaymentTest.java:99: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          if (e.getSource == time[0])
                                   ^
E:\JavaCoursework\ParkingPaymentTest.java:101: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:102: cannot resolve symbol
symbol  : variable getSource
location: class java.awt.event.ActionEvent
          } else if (e.getSource == time[1]) {
                            ^
E:\JavaCoursework\ParkingPaymentTest.java:102: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource == time[1]) {
                                          ^
E:\JavaCoursework\ParkingPaymentTest.java:103: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:104: cannot resolve symbol
symbol  : variable getSource
location: class java.awt.event.ActionEvent
          } else if (e.getSource == time[2]) {
                            ^
E:\JavaCoursework\ParkingPaymentTest.java:104: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource == time[2]) {
                                          ^
E:\JavaCoursework\ParkingPaymentTest.java:105: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:106: cannot resolve symbol
symbol  : variable getSource
location: class java.awt.event.ActionEvent
          } else if (e.getSource == time[3]) {
                            ^
E:\JavaCoursework\ParkingPaymentTest.java:106: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource == time[3]) {
                                          ^
E:\JavaCoursework\ParkingPaymentTest.java:107: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:108: cannot resolve symbol
symbol  : variable getSource
location: class java.awt.event.ActionEvent
          } else if (e.getSource == time[4]) {
                            ^
E:\JavaCoursework\ParkingPaymentTest.java:108: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource == time[4]) {
                                          ^
E:\JavaCoursework\ParkingPaymentTest.java:109: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:110: cannot resolve symbol
symbol  : variable getSource
location: class java.awt.event.ActionEvent
          } else if (e.getSource == time[5]) {
                            ^
E:\JavaCoursework\ParkingPaymentTest.java:110: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource == time[5]) {
                                          ^
E:\JavaCoursework\ParkingPaymentTest.java:111: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
18 errors
Output completed (7 sec consumed) - Normal TerminationOk so heres the code im using:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ParkingPaymentTest extends JFrame implements ActionListener {
     public ParkingPaymentTest() {
          JFrame.setDefaultLookAndFeelDecorated(true); //Creates the window and its look.
          JFrame frame = new JFrame("Pre Payment Parking!"); //Sets the top bar title and the frame name.
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Tells it what to do when the close button is clicked.
          JLabel welcomeLabel = new JLabel("Welcome Please Select Your Required Time:"); //Creates A new label to be used with other actions etc.
          welcomeLabel.setPreferredSize(new Dimension(75, 10)); //sets the label size and whats in it.
          JTextField hoursField = new JTextField(30);
          hoursField.setEditable(false);
          JTextArea resultArea = new JTextArea(6, 30);
          resultArea.setEditable(false);
          JPanel buttons = new JPanel(new GridLayout(0,6));
          buttons.setBackground(Color.white);
          JPanel buttons2 = new JPanel(new GridLayout(0,5));
          buttons2.setBackground(Color.white);
          JPanel contentPane = new JPanel(new BorderLayout());
          buttons2.add(welcomeLabel); //Adds the label to the frame.
          contentPane.add(hoursField, BorderLayout.CENTER); //Adds the Textfield.
          contentPane.add(resultArea, BorderLayout.PAGE_END); //Adds the Textarea.
          contentPane.setBackground(Color.white);
          contentPane.setOpaque(true);
          JButton time[] = new JButton[6];
          for (int i = 0; i < 6; i++)//Adds the button array to the panel and adds the action listeners.
               time[i] = new JButton();
               time.addActionListener(this);
               buttons2.add(time[i]);
               time[i].setBackground(Color.white);
               contentPane.add(buttons2, BorderLayout.PAGE_START);
          time[0].setText("0-1");
          time[1].setText("1-2");
          time[2].setText("2-3");
          time[3].setText("3-4");
          time[4].setText("4-5");
          time[5].setText("5+");
          JButton payment[] = new JButton[5];
          for (int i = 0; i < 5; i++)
               payment[i] = new JButton();
               payment[i].addActionListener(this);
               buttons.add(payment[i]);
               payment[i].setBackground(Color.white);
               contentPane.add(buttons, BorderLayout.CENTER);
          payment[0].setText("10p");
          payment[1].setText("20p");
          payment[2].setText("50p");
          payment[3].setText("�1");
          payment[4].setText("�2");
          frame.setContentPane(contentPane);
          frame.pack();
          frame.setVisible(true); //Shows the window.
          int fee=400;
          int amountPaid=765;
          int amountToPay;
          int changeDue;
          amountToPay=fee-amountPaid;
          changeDue=amountPaid-fee;
          if (amountPaid<fee)
               resultArea.setText("Amount to pay is " + amountToPay + " pence");
               else if(amountPaid==fee)
                    resultArea.setText("Correct amount paid");
               else if(amountPaid>fee)
                    resultArea.setText("you get no change cunt!");//dispenseChange(changeDue);
     public static void main(String[] args) {
          ParkingPaymentTest p = new ParkingPaymentTest();
     public void actionPerformed (ActionEvent e){
          if (e.getSource == time[0])
               resultArea.setText("u smell");
          } else if (e.getSource == time[1]) {
               resultArea.setText("u smell");
          } else if (e.getSource == time[2]) {
               resultArea.setText("u smell");
          } else if (e.getSource == time[3]) {
               resultArea.setText("u smell");
          } else if (e.getSource == time[4]) {
               resultArea.setText("u smell");
          } else if (e.getSource == time[5]) {
               resultArea.setText("u smell");
Please can someone give me a hand as i cannot figure out why it cannot resolve symbol?
Ive added the actionlisteners properly but i cant figure out why it aint working.
Cheers LordOfGood

---------- javac ----------
E:\JavaCoursework\ParkingPaymentTest.java:99: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          if (e.getSource() == time[0])
                                     ^
E:\JavaCoursework\ParkingPaymentTest.java:101: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:102: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource() == time[1]) {
                                            ^
E:\JavaCoursework\ParkingPaymentTest.java:103: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:104: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource() == time[2]) {
                                            ^
E:\JavaCoursework\ParkingPaymentTest.java:105: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:106: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource() == time[3]) {
                                            ^
E:\JavaCoursework\ParkingPaymentTest.java:107: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
E:\JavaCoursework\ParkingPaymentTest.java:108: cannot resolve symbol
symbol  : variable time
location: class ParkingPaymentTest
          } else if (e.getSource() == time[4]) {
                                            ^
E:\JavaCoursework\ParkingPaymentTest.java:109: cannot resolve symbol
symbol  : variable resultArea
location: class ParkingPaymentTest
               resultArea.setText("u smell");
                        ^
10 errors
Output completed (1 sec consumed) - Normal TerminationOk so ive done that but its still telling me it cant resolve the button arrays and textarea? How can i fix it?

Similar Messages

  • Problem with Threads and a static variable

    I have a problem with the code below. I am yet to make sure that I understand the problem. Correct me if I am wrong please.
    Code functionality:
    A timer calls SetState every second. It sets the state and sets boolean variable "changed" to true. Then notifies a main process thread to check if the state changed to send a message.
    The problem as far I understand is:
    Assume the timer Thread calls SetState twice before the main process Thread runs. As a result, "changed" is set to true twice. However, since the main process is blocked twice during the two calls to SetState, when it runs it would have the two SetState timer threads blocked on its synchronized body. It will pass the first one, send the message and set "changed" to false since it was true. Now, it will pass the second thread, but here is the problem, "changed" is already set to false. As a result, it won't send the message even though it is supposed to.
    Would you please let me know if my understanding is correct? If so, what would you propose to resolve the problem? Should I call wait some other or should I notify in a different way?
    Thanks,
    B.D.
    Code:
    private static volatile boolean bChanged = false;
    private static Thread objMainProcess;
       protected static void Init(){
            objMainProcess = new Thread() {
                public void run() {
                    while( objMainProcess == Thread.currentThread() ) {
                       GetState();
            objMainProcess.setDaemon( true );
            objMainProcess.start();
        public static void initStatusTimer(){
            if(objTimer == null)
                 objTimer = new javax.swing.Timer( 1000, new java.awt.event.ActionListener(){
                    public void actionPerformed( java.awt.event.ActionEvent evt){
                              SetState();
        private static void SetState(){
            if( objMainProcess == null ) return;
            synchronized( objMainProcess ) {
                bChanged = true;
                try{
                    objMainProcess.notify();
                }catch( IllegalMonitorStateException e ) {}
        private static boolean GetState() {
            if( objMainProcess == null ) return false;
            synchronized( objMainProcess ) {
                if( bChanged) {
                    SendMessage();
                    bChanged = false;
                    return true;
                try {
                    objMainProcess.wait();
                }catch( InterruptedException e ) {}
                return false;
        }

    Thanks DrClap for your reply. Everything you said is right. It is not easy to make them alternate since SetState() could be called from different places where the state could be anything else but a status message. Like a GREETING message for example. It is a handshaking message but not a status message.
    Again as you said, There is a reason I can't call sendMessage() inside setState().
    The only way I was able to do it is by having a counter of the number of notifies that have been called. Every time notify() is called a counter is incremented. Now instead of just checking if "changed" flag is true, I also check if notify counter is greater than zero. If both true, I send the message. If "changed" flag is false, I check again if the notify counter is greater than zero, I send the message. This way it works, but it is kind of a patch than a good design fix. I am yet to find a good solution.
    Thanks,
    B.D.

  • Problem with JFrame and busy/wait Cursor

    Hi -- I'm trying to set a JFrame's cursor to be the busy cursor,
    for the duration of some operation (usually just a few seconds).
    I can get it to work in some situations, but not others.
    Timing does seem to be an issue.
    There are thousands of posts on the BugParade, but
    in general Sun indicates this is not a bug. I just need
    a work-around.
    I've written a test program below to demonstrate the problem.
    I have the problem on Solaris, running with both J2SE 1.3 and 1.4.
    I have not tested on Windows yet.
    When you run the following code, three JFrames will be opened,
    each with the same 5 buttons. The first "F1" listens to its own
    buttons, and works fine. The other two (F2 and F3) listen
    to each other's buttons.
    The "BUSY" button simply sets the cursor on its listener
    to the busy cursor. The "DONE" button sets it to the
    default cursor. These work fine.
    The "SLEEP" button sets the cursor, sleeps for 3 seconds,
    and sets it back. This does not work.
    The "INVOKE LATER" button does the same thing,
    except is uses invokeLater to sleep and set the
    cursor back. This also does not work.
    The "DELAY" button sleeps for 3 seconds (giving you
    time to move the mouse into the other (listerner's)
    window, and then it behaves just like the "SLEEP"
    button. This works.
    Any ideas would be appreciated, thanks.
    -J
    import java.awt.BorderLayout;
    import java.awt.Cursor;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class BusyFrameTest implements ActionListener
    private static Cursor busy = Cursor.getPredefinedCursor (Cursor.WAIT_CURSOR);
    private static Cursor done = Cursor.getDefaultCursor();
    JFrame frame;
    JButton[] buttons;
    public BusyFrameTest (String title)
    frame = new JFrame (title);
    buttons = new JButton[5];
    buttons[0] = new JButton ("BUSY");
    buttons[1] = new JButton ("DONE");
    buttons[2] = new JButton ("SLEEP");
    buttons[3] = new JButton ("INVOKE LATER");
    buttons[4] = new JButton ("DELAY");
    JPanel buttonPanel = new JPanel();
    for (int i = 0; i < buttons.length; i++)
    buttonPanel.add (buttons);
    frame.getContentPane().add (buttonPanel);
    frame.pack();
    frame.setVisible (true);
    public void addListeners (ActionListener listener)
    for (int i = 0; i < buttons.length; i++)
    buttons[i].addActionListener (listener);
    public void actionPerformed (ActionEvent e)
    System.out.print (frame.getTitle() + ": " + e.getActionCommand());
    if (e.getActionCommand().equals ("BUSY"))
    frame.setCursor (busy);
    else if (e.getActionCommand().equals ("DONE"))
    frame.setCursor (done);
    else if (e.getActionCommand().equals ("SLEEP"))
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    else if (e.getActionCommand().equals ("INVOKE LATER"))
    frame.setCursor (busy);
    SwingUtilities.invokeLater (thread);
    else if (e.getActionCommand().equals ("DELAY"))
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (busy);
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.print (" finished");
    System.out.println();
    Runnable thread = new Runnable()
    public void run()
    try { Thread.sleep (3000); } catch (Exception ex) { }
    frame.setCursor (done);
    System.out.println (" finished");
    public static void main (String[] args)
    BusyFrameTest f1 = new BusyFrameTest ("F1");
    f1.addListeners (f1);
    BusyFrameTest f2 = new BusyFrameTest ("F2");
    BusyFrameTest f3 = new BusyFrameTest ("F3");
    f2.addListeners (f3); // 2 listens to 3
    f3.addListeners (f2); // 3 listens to 2

    I've had the same problems with cursors and repaints in a swing application, and I was thinking of if I could use invokeLater, but I never got that far with it.
    I still believe you would need a thread for the time consuming task, and that invokeLater is something you only need to use in a thread different from the event thread.

  • Can some one help me with this problem with my frame???

    i have gt a veri strange problem with my program,that is teh graphic changes only when i resize the the frame,if i dun resize,it will remain the same.However what i intended is that when i click on the radio button,it will change immediately to the respective pages.A simple version of my code is below,can someone helpl me solve it??(there is 3 different class)
    import java.awt.event.*;
    import javax.swing.*;
    public class MainPg extends JFrame implements ActionListener{
         private javax.swing.JPanel jContentPane = null;
         private javax.swing.JPanel buttons = null;
         private javax.swing.JRadioButton one = null;
         private javax.swing.JRadioButton two = null;
         private javax.swing.JPanel change = null;
         public MainPg() {
              super();
              initialize();
         private void initialize() {
              this.setSize(300, 200);
              this.setContentPane(getJContentPane());
              this.setName("mainClass");
              this.setVisible(true);
         private javax.swing.JPanel getJContentPane() {
              if (jContentPane == null) {
                   jContentPane = new javax.swing.JPanel();
                   jContentPane.setLayout(new java.awt.BorderLayout());
                   jContentPane.add(getButtons(), java.awt.BorderLayout.WEST);
                   jContentPane.add(getChange(), java.awt.BorderLayout.CENTER);
              return jContentPane;
         private javax.swing.JPanel getButtons() {
              if(buttons == null) {
                   buttons = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout1 = new java.awt.GridLayout();
                   layGridLayout1.setRows(2);
                   layGridLayout1.setColumns(1);
                   ButtonGroup group=new ButtonGroup();
                   group.add(getOne());
                   group.add(getTwo());
                   buttons.setLayout(layGridLayout1);
                   buttons.add(getOne(), null);
                   buttons.add(getTwo(), null);
              return buttons;
         private javax.swing.JRadioButton getOne() {
              if(one == null) {
                   one = new javax.swing.JRadioButton();
                   one.setText("One");
                   one.setSelected(true);
                   one.addActionListener(this);
                   one.setActionCommand("one");
              return one;
         private javax.swing.JRadioButton getTwo() {
              if(two == null) {
                   two = new javax.swing.JRadioButton();
                   two.setText("Two");
                   two.addActionListener(this);
                   two.setActionCommand("two");
              return two;
         private javax.swing.JPanel getChange() {
              if(change == null) {
                   change = new javax.swing.JPanel();
              change.add(new One());
              return change;
         public static void main(String[] args){
              new MainPg();
         public void actionPerformed(ActionEvent e) {
              change.removeAll();
              if("one".equals(e.getActionCommand())){
                   change.add(new One());
              else{
                   change.add(new Two());
              change.repaint();
    import javax.swing.*;
    public class One extends JPanel {
         private javax.swing.JPanel jPanel = null;
         private javax.swing.JLabel jLabel = null;
         private javax.swing.JPanel jPanel1 = null;
         private javax.swing.JLabel jLabel1 = null;
         private javax.swing.JLabel jLabel2 = null;
         public One() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.BorderLayout());
              this.add(getJPanel(), java.awt.BorderLayout.NORTH);
              this.add(getJPanel1(), java.awt.BorderLayout.WEST);
              this.setSize(300, 200);
         * This method initializes jPanel
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel() {
              if(jPanel == null) {
                   jPanel = new javax.swing.JPanel();
                   jPanel.add(getJLabel(), null);
              return jPanel;
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("one");
              return jLabel;
         * This method initializes jPanel1
         * @return javax.swing.JPanel
         private javax.swing.JPanel getJPanel1() {
              if(jPanel1 == null) {
                   jPanel1 = new javax.swing.JPanel();
                   java.awt.GridLayout layGridLayout2 = new java.awt.GridLayout();
                   layGridLayout2.setRows(2);
                   layGridLayout2.setColumns(1);
                   jPanel1.setLayout(layGridLayout2);
                   jPanel1.add(getJLabel2(), null);
                   jPanel1.add(getJLabel1(), null);
              return jPanel1;
         * This method initializes jLabel1
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel1() {
              if(jLabel1 == null) {
                   jLabel1 = new javax.swing.JLabel();
                   jLabel1.setText("one");
              return jLabel1;
         * This method initializes jLabel2
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel2() {
              if(jLabel2 == null) {
                   jLabel2 = new javax.swing.JLabel();
                   jLabel2.setText("one");
              return jLabel2;
    import javax.swing.*;
    public class Two extends JPanel {
         private javax.swing.JLabel jLabel = null;
         public Two() {
              super();
              initialize();
         * This method initializes this
         * @return void
         private void initialize() {
              this.setLayout(new java.awt.FlowLayout());
              this.add(getJLabel(), null);
              this.setSize(300, 200);
         * This method initializes jLabel
         * @return javax.swing.JLabel
         private javax.swing.JLabel getJLabel() {
              if(jLabel == null) {
                   jLabel = new javax.swing.JLabel();
                   jLabel.setText("two");
              return jLabel;
    }

    //change.repaint();
    change.revalidate();

  • Problem with JTextPane and StateInvariantError

    Hi. I am having a problem with JTextPanes and changing only certain text to bold. I am writing a chat program and would like to allow users to make certain text in their entries bold. The best way I can think of to do this is to add <b> and </b> tags to the beginning and end of any text that is to be bold. When the other client receives the message, the program will take out all of the <b> and </b> tags and display any text between them as bold (or italic with <i> and </i>). I've searched the forums a lot and figured out several ways to make the text bold, and several ways to determine which text is bold before sending the text, but none that work together. Currently, I add the bold tags with this code: (note: messageDoc is a StyledDocument and messageText is a JTextPane)
    public String getMessageText() {
              String text = null;
              boolean bold = false, italic = false;
              for (int i = 0; i < messageDoc.getLength(); i++) {
                   messageText.setCaretPosition(i);
                   if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && !bold) {
                        bold = true;
                        if (text != null) {
                             text = text + "<b>";
                        else {
                             text = "<b>";
                   else if (StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        // Do nothing
                   else if (!StyleConstants.isBold(messageDoc.getCharacterElement(i).getAttributes()) && bold) {
                        bold = false;
                        if (text != null) {
                             text = text + "</b>";
                        else {
                             text = "</b>";
                   try {
                        if (text != null) {
                             text = text + messageDoc.getText(i,1);
                        else {
                             text = messageDoc.getText(i, 1);
                   catch (BadLocationException e) {
                        System.out.println("An error occurred while getting the text from the message document");
                        e.printStackTrace();
              return text;
         } // end getMessageText()When the message is sent to the other client, the program searches through the received message and changes the text between the bold tags to bold. This seems as if it should work, but as soon as I click on the bold button, I get a StateInvariantError. The code for my button is:
    public void actionPerformed(ActionEvent evt) {
              if (evt.getSource() == bold) {
                   MutableAttributeSet bold = new SimpleAttributeSet();
                   StyleConstants.setBold(bold, true);
                   messageText.getStyledDocument().setCharacterAttributes(messageText.getSelectionStart(), messageText.getSelectionStart() - messageText.getSelectionEnd() - 1, bold, false);
         } //end actionPerformed()Can anyone help me to figure out why this error is being thrown? I have searched for a while to figure out this way of doing what I'm trying to do and I've found out that a StateInvariantError has been reported as a bug in several different circumstances but not in relation to this. Or, if there is a better way to add and check the style of the text that would be great as well. Any help is much appreciated, thanks in advance.

    Swing related questions should be posted in the Swing forum.
    Can't tell from you code what the problem is because I don't know the context of how each method is invoked. But it would seem like you are trying to query the data in the Document while the Document is being updated. Try wrapping the getMessageText() method is a SwingUtilities.invokeLater().
    There is no need to write custom code for a Bold Action you can just use:
    JButton bold = new JButton( new StyledEditorKit.BoldAction() );Also your code to build the text String is not very efficient. You should not be using string concatenation to append text to the string. You should be using a StringBuffer or StringBuilder.

  • Problem with writing and reading using serialization

    I am having a problem with writing and reading an object that has another object in it. The purpose of the class is to write a order that has multiple items in it. And there will be several orders. This is for an IB project, where one of the requirements is to utilize a hierarchical composite data structure. That is, it is "one that contains more than one element and at least one of the elements is a composite data structure. Examples are, an array or linked list of records, a record that has one field that is another record, or an array". The code is shown below:
    The error produced is
    java.lang.NullPointerException
         at SamsonRubberIndustries.CustomerOrderDetails.createCustOrdDetailsScreen(CustomerOrderDetails.java:150)
         at SamsonRubberIndustries.CustomerOrderDetails$1.run(CustomerOrderDetails.java:78)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    public class CustOrdObject implements Serializable {
         public int CustID;
         public int CustOrderID;
         public Object OrderDate;
         public InnerCustOrdObject[] innerCustOrdObj;
         public float GrandTotal;
         public int MaxItems;
         public CustOrdObject() {}
         public CustOrdObject(InnerCustOrdObject[] innerCustOrdObj,
    int CustID, int CustOrderID, Object OrderDate,
    float GrandTotal, int innerarrlength, int innerarrpos, int MaxItems) {
              this.CustID = CustID;
              this.CustOrderID = CustOrderID;
              this.OrderDate = OrderDate;
              this.GrandTotal = GrandTotal;          
              this.MaxItems = MaxItems;
              this.innerCustOrdObj = new InnerCustOrdObject[MaxItems];
         public InnerCustOrdObject[] getInnerCustOrdObj() {
              return innerCustOrdObj;
         public void setInnerCustOrdObj(InnerCustOrdObject[] innerCustOrdObj) {
              this.innerCustOrdObj = innerCustOrdObj;
         public int getCustID() {
              return CustID;
         public void setCustID(int custID) {
              CustID = custID;
         public int getCustOrderID() {
              return CustOrderID;
         public void setCustOrderID(int custOrderID) {
              CustOrderID = custOrderID;
         public Object getOrderDate() {
              return OrderDate;
         public void setOrderDate(Object orderDate) {
              OrderDate = orderDate;
         public void setGrandTotal(float grandTotal) {
              GrandTotal = grandTotal;
         public float getGrandTotal() {
              return GrandTotal;
         public int getMaxItems() {
              return MaxItems;
         public void setMaxItems(int maxItems) {
              MaxItems = maxItems;
    public class InnerCustOrdObject implements Serializable{
         public int ItemNumber;
         public float UnitPrice;
         public int QuantityRequired;
         public float TotalPrice;
         public InnerCustOrdObject() {}
         public InnerCustOrdObject(int ItemNumber, float
    UnitPrice, int QuantityRequired, float TotalPrice){
              this.ItemNumber = ItemNumber;
              this.UnitPrice = UnitPrice;
              this.QuantityRequired = QuantityRequired;
              this.TotalPrice = TotalPrice;
         public int getItemNumber() {
              return ItemNumber;
         public void setItemNumber(int itemNumber) {
              ItemNumber = itemNumber;
         public int getQuantityRequired() {
              return QuantityRequired;
         public void setQuantityRequired(int quantityRequired) {
              QuantityRequired = quantityRequired;
         public float getTotalPrice() {
              return TotalPrice;
         public void setTotalPrice(float totalPrice) {
              TotalPrice = totalPrice;
         public float getUnitPrice() {
              return UnitPrice;
         public void setUnitPrice(float unitPrice) {
              UnitPrice = unitPrice;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems;
         private static boolean FileExists, recFileExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.dat");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                 innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord-1);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              //TotPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++CurrentRecord;
                             //readOrder();
                             //readInnerOrderRecord(CurrentRecord);
                             setInnerFieldText(currentItem);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             //readOrder();
                             setInnerFieldText(currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             writeRecordNumber(MaxRecord);
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             currentItem++;
                             setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              System.err.println("currentItem" + currentItem);
              getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07
    Message was edited by:
    Kilik07

    ok i got reading to work to a certain extent... but the prob is i cnt seem to save my innerCustOrdObj proprly...when ever i look for a record using the gotorecordbtn, the outerobject, which is the orderDetails, seems to change but the innerCustOrdObj remains the same... heres the new code..
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems = 1;
         private static boolean FileExists, recFileExists;
         private static boolean RecordExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.ser");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                   //CurrentRecord--;
                   //System.out.println("Current Rec Here"+CurrentRecord);
                   if(orderDetails[CurrentRecord] == null){
                        System.err.println("CustomerOrderObj 1 is null !!");
                   }else{
                        System.err.println("CustomerOrderObj 1 is  not null !!");
                   if(orderDetails[CurrentRecord].getInnerCustOrdObj() == null){
                        System.err.println("InnerCustomerOrderObj is null !!");
                   }else{
                        System.err.println("InnerCustomerOrderObj is  not null !!");
                   innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord);
                   getInnerFieldText(MaxItems);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              //CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              TotPriceTxt.setEditable(false);
              TotPriceTxt.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt){
                        TotPriceTxt.setText(""+Integer.parseInt(UnitPriceTxt.getText())*Integer.parseInt(QuantityReqTxt.getText()));
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println("Current Record " + CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             CurrentRecord = MaxRecord;
                             orderDetails[CurrentRecord] = new CustOrdObject();
                             writeRecordNumber(MaxRecord);
                             MaxItems = 1;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        setInnerFieldText(MaxItems);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             MaxItems++;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             System.out.println("Max Items "+MaxItems);
                             currentItem = MaxItems;
                             orderDetails[CurrentRecord].setMaxItems(MaxItems);
                             ///setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              gotorecordbtn = new JButton("Go To Record", createGotoButtonIcon());
              gotorecordbtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt){
                         * The text from the GotorecordTxt textfield will be taken and assigned
                         * to a temporary integer variable called Find. 
                        int Find = Integer.parseInt(CustOrderIDTxt.getText());
                        for(int j=1; j <= MaxRecord; j++){
                              * Using a for loop, each record can be read using the readCustRecord
                              * method.
                             getFieldText(j);
                              * An if condition is utilized to check whether the temporary stored variable, Find,
                              * matches a field in a record. If this record is found, then using the RecordExists
                              * which was declared at the top, either a true or false statement can be assigned
                              * If the record exists, then a true statement will be assigned, if not a false
                              * statement will be assigned.
                             if(orderDetails[j].getCustOrderID() == Find){
                                  RecordExists = true;
                                  break;
                             }else{
                                  RecordExists = false;
                        if(RecordExists == false){
                              * If the RecordExists is assigned a false statement, then a message will be
                              * displayed to show that the record does not exist.
                             JOptionPane.showMessageDialog(null, "Record Does Not Exist!", "Error Message", JOptionPane.ERROR_MESSAGE, createErrorIcon());
                        }else{
                             getFieldText(Find);
              buttonpanel.add(gotorecordbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setMaxItems(MaxItems);
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              orderDetails[orderID].getInnerCustOrdObj();
              System.err.println("currentItem" + currentItem);
              //getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   /*               System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());*/
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07

  • Problem with JTable and JPanel

    Hi,
    I'm having problems with a JTable in a JPanel. The code is basicly as follows:
    public class mainFrame extends JFrame
            public mainFrame()
                    //A menu is implemeted giving rise to the following actions:
                    public void actionPerformed(ActionEvent evt)
                            String arg = evt.getActionCommand();
                            if(arg.equals("Sit1"))
                            //cells, columnNames are initiated correctly
                            JTable table = new JTable(cells,columnNames);
                            JPanel holdingPanel = new JPanel();
                            holdingPanel.setLayout( new BorderLayout() );
                            JScrollPane scrollPane = new JScrollPane(holdingPanel);
                            holdingPanel.setBackground(Color.white);
                            holdingPanel.add(table,BorderLayout.CENTER);
                            add(scrollPane, "Center");
                            if(arg.equals("Sit2"))
                                    if(scrollPane !=null)
                                            remove(scrollPane);validate();System.out.println("ScrollPane");
                                    if(holdingPanel !=null)
                                            remove(holdingPanel);
                                    if(table !=null)
                                            remove(table);table.setVisible(false);System.out.println("table");
                            //Put other things on the holdingPanel....
            private JScrollPane scrollPane;
            private JPanel holdingPanel;
            private JTable table;
    }The problem is that the table isn't removed. When you choose another situation ( say Sit2), at first the table apparently is gone, but when you press with the mouse in the area it appeared earlier, it appears again. How do I succesfully remove the table from the panel? Removing the panel doesn't seem to be enough. Help is much appreciated...
    Best regards
    Schwartz

    If you reuse the panel and scroll pane throughout the application,
    instantiate them in the constructor, not in an often-called event
    handler. In the event handler, you only do add/remove of the table
    on to the panel. You can't remove the table from the container
    which does not directly contain it.
    if (arg.equals("Sit2")){
      holdingPanel.remove(table);
      holdingPanel.revalidate();
      holdingPanel.repaint(); //sometimes necessary
    }

  • Memory problem with JTextFields

    Hello,
    I have a wierd problem with JTextField and the memory.
    I need to fill a JPanel with different Components (including JTextFields), then do some calculation, remove the Components and filling the JPanel again.
    When i so this too often my i get an OutOfMemory Exception. I narrowed to problem down and wrote a small sample program to demonstrate the problem.
    When i call the method doIT (where the Panel is repeatedly filled) from the main-function everything works fine, but when it is called as a result from the GUI-Button-Event the memory for the JTextFields is not freed (even the call of the Garbage collector changes nothing)
    When i only use JButtons to fill the Panel everything works fine.
    Has anyone an idea why this problem occurs and how i can work around it?
    [Edit] I tested it whith java 1.5.0_06, 1.5.0_11, 1.6.0_02
    Thanks
    Marc
    import java.awt.Frame;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.lang.management.ManagementFactory;
    import java.lang.management.MemoryUsage;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class MemoryTestDLG extends JDialog {
         public MemoryTestDLG(Frame owner) {
              // create Dialog with one Button that calls the testMethod
              super(owner);
              JButton b = new JButton("doIT ...");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doIT();
                        setVisible(false);
              getContentPane().add(b);
              pack();
         public void doIT() {
              // Testmethod that fills a JPanel 20 times with Components and clears it
              // again
              JPanel p = new JPanel();
              long memUse1 = 0;
              long memUse2 = 0;
              long memUseTemp = 0;
              for (int count = 0; count < 20; count++) {
                   // Clear the panel
                   p.removeAll();
                   // Get memory usage before the task
                   Runtime.getRuntime().gc();
                   memUse1 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // Fill Panel with components
                   for (int i = 0; i < 200; i++) {
                        // The Buttons seem to be released without any problem
                        p.add(new JButton("test" + Math.random()));
                        // JTextFields are not released when used from the dialog.
                        p.add(new JTextField("test " + Math.random()));
                   // get memory usage after the task
                   Runtime.getRuntime().gc();
                   memUseTemp = memUse2;
                   memUse2 = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage()
                             .getUsed();
                   // print Memory results
                   System.out.println("Memory Usage: " + f(memUse1) + "   ->"
                             + f(memUse2) + " [ Used:" + f(memUse2 - memUse1)
                             + " ] [ Freed: " + f(memUseTemp - memUse1) + "]");
         public String f(long m) // formats the output
              String s = "" + m;
              while (s.length() < 8)
                   s = " " + s;
              return s;
         public static void main(String[] args) {
              MemoryTestDLG d = new MemoryTestDLG(null);
              System.out
                        .println("------------------ Direct Call (all is OK) -------------------");
              d.doIT(); // Memory is freed with every call to JPanel.removeAll()
              System.out
                        .println("------------ Call from Dialog (memory is not freed) -------------");
              // The Memory keeps blocked
              d.setModal(true);
              d.setVisible(true);
              System.exit(0);
    }Message was edited by:
    marcvomorc

    Thank you for your answer,
    In this sample the programm does not run out of memory. But when you look at the output you see, that in the first run (direct call) the memory ist freed immediately when tha panel is cleared but in the second run (from the Button) the memory usage is getting bigger and bigger. Wenn you change the number of components to 2000 (4000)
    // Fill Panel with components
            for (int i = 0; i < 2000; i++) {
                // The Buttons seem to be released without any problem
    //... ...and use the default memory settings (69mb heap) the programm runns out of memory.
    I get the following output:
    ------------------ Direct Call (all is OK) -------------------
    Memory Usage:   445504   -> 8121016 [ Used: 7675512 ] [ Freed:  -445504]
    Memory Usage:   617352   -> 8114336 [ Used: 7496984 ] [ Freed:  7503664]
    Memory Usage:   810488   -> 8491768 [ Used: 7681280 ] [ Freed:  7303848]
    Memory Usage:   943704   -> 8114976 [ Used: 7171272 ] [ Freed:  7548064]
    Memory Usage:   836760   -> 8505072 [ Used: 7668312 ] [ Freed:  7278216]
    Memory Usage:   978352   -> 8114784 [ Used: 7136432 ] [ Freed:  7526720]
    Memory Usage:   835552   -> 8498288 [ Used: 7662736 ] [ Freed:  7279232]
    Memory Usage:   977096   -> 8114312 [ Used: 7137216 ] [ Freed:  7521192]
    Memory Usage:   835640   -> 8498376 [ Used: 7662736 ] [ Freed:  7278672]
    Memory Usage:   977296   -> 8115000 [ Used: 7137704 ] [ Freed:  7521080]
    Memory Usage:   835392   -> 8504872 [ Used: 7669480 ] [ Freed:  7279608]
    Memory Usage:   976968   -> 8115192 [ Used: 7138224 ] [ Freed:  7527904]
    Memory Usage:   836224   -> 8501624 [ Used: 7665400 ] [ Freed:  7278968]
    Memory Usage:   977840   -> 8115120 [ Used: 7137280 ] [ Freed:  7523784]
    Memory Usage:   835664   -> 8498256 [ Used: 7662592 ] [ Freed:  7279456]
    Memory Usage:   976856   -> 8114384 [ Used: 7137528 ] [ Freed:  7521400]
    Memory Usage:   835784   -> 8502848 [ Used: 7667064 ] [ Freed:  7278600]
    Memory Usage:   977360   -> 8114592 [ Used: 7137232 ] [ Freed:  7525488]
    Memory Usage:   835496   -> 8502720 [ Used: 7667224 ] [ Freed:  7279096]
    Memory Usage:   976440   -> 8115128 [ Used: 7138688 ] [ Freed:  7526280]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   866504   -> 8784320 [ Used: 7917816 ] [ Freed:  -866504]
    Memory Usage:  7480760   ->14631152 [ Used: 7150392 ] [ Freed:  1303560]
    Memory Usage: 14245264   ->22127104 [ Used: 7881840 ] [ Freed:   385888]
    Memory Usage: 19302896   ->27190744 [ Used: 7887848 ] [ Freed:  2824208]
    Memory Usage: 27190744   ->35073944 [ Used: 7883200 ] [ Freed:        0]
    Memory Usage: 31856624   ->39740176 [ Used: 7883552 ] [ Freed:  3217320]
    Memory Usage: 39740176   ->47623040 [ Used: 7882864 ] [ Freed:        0]
    Memory Usage: 44410480   ->52293864 [ Used: 7883384 ] [ Freed:  3212560]
    Memory Usage: 52293864   ->58569304 [ Used: 6275440 ] [ Freed:        0]
    Memory Usage: 58569304   ->64846400 [ Used: 6277096 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spacewhen I outcomment the adding of the JButtons the amount of freed memory is 0 in the second run. So my guess is, that there is a problem with freeing the memory for the JTextFields.
    Memory Usage:   447832   -> 6509960 [ Used: 6062128 ] [ Freed:  6332768]
    Memory Usage:   722776   -> 6785632 [ Used: 6062856 ] [ Freed:  5787184]
    ------------ Call from Dialog (memory is not freed) -------------
    Memory Usage:   468880   -> 6770240 [ Used: 6301360 ] [ Freed:  -468880]
    Memory Usage:  6770240   ->13016264 [ Used: 6246024 ] [ Freed:        0]
    Memory Usage: 13016264   ->19297080 [ Used: 6280816 ] [ Freed:        0]
    Memory Usage: 19297080   ->25570152 [ Used: 6273072 ] [ Freed:        0]
    Memory Usage: 25570152   ->31849160 [ Used: 6279008 ] [ Freed:        0]
    Memory Usage: 31849160   ->38124368 [ Used: 6275208 ] [ Freed:        0]
    Memory Usage: 38124368   ->44402072 [ Used: 6277704 ] [ Freed:        0]
    Memory Usage: 44402072   ->50677928 [ Used: 6275856 ] [ Freed:        0]
    Memory Usage: 50677928   ->56955880 [ Used: 6277952 ] [ Freed:        0]
    Memory Usage: 56955880   ->63232152 [ Used: 6276272 ] [ Freed:        0]
    Exception occurred during event dispatching:
    java.lang.OutOfMemoryError: Java heap spaceAdditionally the JPanel I am using is not displayed on the screen. It stays invisible the whole time, but i cannot work around that, because the calculation is depending on the values being in components on the JPanel)
    Marc

  • Problem with event handling

    Hello all,
    I have a problem with event handling. I have two buttons in my GUI application with the same name.They are instance variables of two different objects of the same class and are put together in the one GUI.And their actionlisteners are registered with the same GUI. How can I differentiate between these two buttons?
    To be more eloborate here is a basic definition of my classes
    class SystemPanel{
             SystemPanel(FTP ftp){ app = ftp};
             FTP app;
             private JButton b = new JButton("ChgDir");
            b.addActionListener(app);
    class FTP extends JFrame implements ActionListener{
               SystemPanel rem = new SystemPanel(this);
               SystemPanel loc = new SystemPanel(this);
               FTP(){
                       add(rem);
                       add(loc);
                       pack();
                       show();
           void actionPerformed(ActionEvent evt){
            /*HOW WILL I BE ABLE TO KNOW WHICH BUTTON WAS PRESSED AS THEY
               BOTH HAVE SAME ID AND getSouce() ?
               In this case..it if was from rem or loc ?
    }  It would be really helpful if anyone could help me in this regard..
    Thanks
    Hari Vigensh

    Hi levi,
    Thankx..
    I solved the problem ..using same concept but in a different way..
    One thing i wanted to make clear is that the two buttons are in the SAME CLASS and i am forming 2 different objects of the SAME class and then putting them in a GUI.THERE IS NO b and C. there is just two instances of b which belong to the SAME CLASS..
    So the code
    private JButton b = new JButton("ChgDir");
    b.setActionCommand ("1");
    wont work as both the instances would have the label "ChgDir" and have setActionCommand set to 1!!!!
    Actually I have an array of buttons..So I solved the prob by writting a function caled setActionCmdRemote that would just set the action commands of one object of the class differently ..here is the code
    public void setActionCommandsRemote()
         for(int i = 0 ; i <cmdButtons.length ; i++)
         cmdButtons.setActionCommand((cmdButtons[i].getText())+"Rem");
    This just adds "rem" to the existing Actioncommand and i check it as folows in my actionperformed method
         if(button.getActionCommand().equals("DeleteRem") )          
                        deleteFileRemote();
          else if(button.getActionCommand().equals("Delete") )
                     deleteFileLocal();Anyway thanx a milion for your help..this was my first posting and I was glad to get a prompt reply!!!

  • Problem with JTextArea or is it my code, Help!!!

    Hi,
    I am going crazy. I am sending a message to a JTextArea and I get some very wierd things happening? I really need help because this is driving me crazy. Please see the following code to see my annotations for the problems. Has anyone else experienced problems with this component?
    Thanks,
    Steve
    // THIS IS THE CLASS THAT HANDLES ALL OF THE WORK
    public class UpdateDataFields implements ActionListener {     // 400
         JTextArea msg;
         JPanel frameForCardPane;
         CardLayout cardPane;
         TestQuestionPanel fromRadio;
         public UpdateDataFields( JTextArea msgout ) {     // 100
              msg = msgout;
          }       // 100
         public void actionPerformed(ActionEvent evt) {     // 200
              String command = evt.getActionCommand();
              String reset = "Test of reset.";
              try{
                   if (command.equals("TestMe")){     // 300
                        msg.append("\nSuccessful");
                        Interface.changeCards();
                        }     // 300
              catch(Exception e){
                   e.printStackTrace();
              try{
                   if (command.equals("ButtonA")){     // 300
    // WHEN I CALL BOTH OF THE FOLLOWING METHODS THE DISPLAY WORKS
    // BUT THE CHANGECARDS METHOD DOES NOT WORK.  WHEN I COMMENT OUT
    // THE CALL TO THE DISPLAYMESSAGE METHOD THEN THE CHANGECARDS WORKS
    // FINE.  PLEASE THE INTERFACE CLASS NEXT.
                        Interface.changeCards();
                        Interface.displayMessage("test of xyz");
                        }     // 300
              catch(Exception e){
                   e.printStackTrace();
         }     // 200
    }     // 400
    // END OF UPDATEDATAFIELS  END END END
    public class Interface extends JFrame {     // 300
         static JPanel frameForCardPane;
         static CardLayout cardPane;
         static JTextArea msgout;
         TestQuestionPanel radio;
         Interface () {     // 100
              super("This is a JFrame");
            setSize(800, 400);  // width, height
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              // set-up card layout
              cardPane = new CardLayout();
              frameForCardPane = new JPanel();     // for CardLayout
              frameForCardPane.setLayout(cardPane);     // set the layout to cardPane = CardLayout
              TestQuestionPanel cardOne = new TestQuestionPanel("ABC", "DEF", msgout, radio);
              TestQuestionPanel cardTwo = new TestQuestionPanel("GHI", "JKL", msgout, radio);
              frameForCardPane.add(cardOne, "first");
              frameForCardPane.add(cardTwo, "second");
              // end set-up card layout
              // set-up main pane
              // declare components
              msgout = new JTextArea( 8, 40 );
              ButtonPanel commandButtons = new ButtonPanel(msgout);
              JPanel pane = new JPanel();
              pane.setLayout(new GridLayout(2, 4, 5, 15));             pane.setBorder(BorderFactory.createEmptyBorder(30, 20, 10, 30));
              pane.add(frameForCardPane);
                 pane.add( new JScrollPane(msgout));
                 pane.add(commandButtons);
              msgout.append("Successful");
              setContentPane(pane);
              setVisible(true);
         }     // 100
    // HERE ARE THE METHODS THAT SHOULD HANDLE THE UPDATING
         static void changeCards() {     // 200
                   cardPane.next(frameForCardPane);
                   System.out.println("Calling methods works!");
         }     // 200
         static void displayMessage(String test) {     // 200
                   String reset = "Test of reset.";
                   String passMessage = test;
                   cardPane.next(frameForCardPane);
                   System.out.println("Calling methods works!");
                   msgout.append("\n"+ test);
         }     // 200
    }     // 300

    Hi,
    I instantiate it in this class. Does that change your opinion or the advice you gave me? Please help!
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class CardLayoutQuestionsv2 {
        public static void main(String[] arguments) {
            JFrame frame = new Interface();
            frame.show();
    }

  • Problem With ObjectSream and GUI

    Hi
    I had a problem with the sendBtn ActionListener. When i press the send button the application freeze and the button freeze pressed.
    But when i put some code to do the same think that send button should do, into the main method everything works fine. Any help?
    Thanks in advanced and sorry for my english
    //Some imports
    public class SampleCommunicationAgentGUI extends BaseCommunicationAgent {
         public SampleCommunicationAgentGUI(String name) {
              super(name);
              try {
                   connectToACS("127.0.0.1", 3333);
              } catch (IOException e) {
                   System.out.print("\nNetwork error while connecting to ACS ("
                             + e.getMessage() + ")");
              } catch (ClassNotFoundException e) {
                   System.out.print("\nNetwork error while connecting to ACS ("
                             + e.getMessage() + ")");
              frame = new SampleAgentFrame(name);
              frame.sendBtn.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        KQML message = new KQML();
                        message.setSender(getName());
                        message.setReceiver(frame.receiverField.getText());
                        message.setContent(frame.contentField.getText());
                        message.setInReplyTo(frame.inReplyToField.getText());
                        message.setLanguage(frame.languageField.getText());
                        message.setOntology(frame.ontologyField.getText());
                        message.setPerformative(frame.perfomativeField.getText());
                        message.setReplyWith(frame.inReplayWithField.getText());
                        System.out.println(message.getTotalMsg());
                        try {
                             sendMessage(message); // A method of BaseCommunicationAgent
                        } catch (Exception e) {
                             e.printStackTrace();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.validate();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public static SampleAgentFrame frame;
         public static void main(String[] args) {
              KQML message;
              SampleCommunicationAgentGUI agent = new SampleCommunicationAgentGUI("Chris");
              if (!agent.getACSStatus().equals(ACSStatus.CONNECTED)) {
                   System.out.println("\nERROR: Could not connect on ACS!");
                   return;
              /*If i put this code here everything works fine
                    * message = new KQML();
                    * agent.sendMessage(message);
              while (true) {
                   message = agent.getMessage();
                   frame.messageTextArea.append(message.getContent() + "\r\n");
         protected static class SampleAgentFrame extends JFrame {
              //Some variables
              public SampleAgentFrame(String name) {
                   setTitle(name);
                   initComponents(name);
               * Initializes the GUI.
              private void initComponents(String name) {
                   //Inits the GUI but is to big to post it.
    }And the BaseCommunicationAgent
    //Some imports
    public class BaseCommunicationAgent extends BaseAgent {
         public static enum ACSStatus {
              INITIALIZING, INITIALIZED, CONNECTING, CONNECTED
         private Socket socketACS;
         private ObjectOutputStream dataOut;
         private ObjectInputStream dataIn;
         protected ACSStatus statusACS;
         private KQML kqmlMessage;
         public BaseCommunicationAgent(String name) {
              super(name);
              statusACS = ACSStatus.INITIALIZING;
              socket = null;
              dataOut = null;
              dataOut = null;
              kqmlMessage = null;
              statusACS = ACSStatus.INITIALIZED;
         protected synchronized boolean connectToACS(String address, int port)
                   throws IOException, ClassNotFoundException {
              try {
                   statusACS = ACSStatus.CONNECTING;
                   socketACS = new Socket(address, port);
                   dataOut = new ObjectOutputStream(socketACS.getOutputStream());
                   dataIn = new ObjectInputStream(socketACS.getInputStream());
                   kqmlMessage = new KQML();
                   KQML message;
                   boolean isComment;
                   do {
                        message = (KQML) dataIn.readObject();
                        isComment = message.getPerformative().equals("comment");
                        if (isComment) {
                             System.out.println(message.getContent());
                   } while (isComment);
                   if (message.getPerformative().equals("identify")) {
                        kqmlMessage.resetMessage();
                        kqmlMessage.setPerformative("who-am-i");
                        kqmlMessage.setSender(getName());
                        dataOut.writeObject(kqmlMessage);
                        dataOut.flush();
                        dataOut.reset();
                        do {
                             message = (KQML) dataIn.readObject();
                             isComment = message.getPerformative().equals("comment");
                             if (isComment) {
                                  System.out.println(message.getContent());
                        } while (isComment);
                        if (message.getPerformative().equals("registered")) {
                             statusACS = ACSStatus.CONNECTED;
                        } else {
                             System.out.println(message.getContent());
                             socketACS.close();
                             statusACS = ACSStatus.INITIALIZING;
                   } else {
                        System.out.println(message.getContent());
                        socketACS.close();
                        statusACS = ACSStatus.INITIALIZING;
              } catch (IOException e) {
                   statusACS = ACSStatus.INITIALIZING;
                   throw e;
              } catch (ClassNotFoundException e) {
                   statusACS = ACSStatus.INITIALIZING;
                   throw e;
              return statusACS.equals(ACSStatus.CONNECTED);
         public ACSStatus getACSStatus() {
              return statusACS;
         protected synchronized void closeConnectionWithACS() { // Only the
                                                                               // dataOut.close()
              try {
                   dataOut.flush();
                   dataOut.close();
                   dataIn.close();
                   socketACS.close();
              } catch (IOException ex) {
                   ex.printStackTrace();
         protected synchronized void sendMessage(KQML message) throws IOException {
              dataOut.writeObject(message);
              dataOut.flush();
              dataOut.reset();
         protected synchronized KQML getMessage() {
              KQML message = new KQML();
              try {
                   message = (KQML) dataIn.readObject();
                   return message;
              } catch (IOException e) {
                   e.printStackTrace();
              } catch (ClassNotFoundException e) {
                   e.printStackTrace();
              return message;
    }

    Thanks for the answer. I take a look at Swing Worker but i have a few problems :
    1)The GUI doesn't freeze but nothing happens either.
    2) When i remove the sendMessage method and i put only a System.out.println(somethingToPrint); it works but only once. After i hit second time my send button nothing happens. Somewhere i read that works only once is that true or i misunderstood? And if yes how i can do it every time i press the send button?
    Could you take a look at my code?
    Thanks in advanced
    //Some imports
    public class SampleCommunicationAgentGUI extends BaseCommunicationAgent {
         public SampleCommunicationAgentGUI(String name) {
              super(name);
              try {
                   // agent.connectToREVE("127.0.0.1", 4444);
                   connectToACS("127.0.0.1", 3333);
              } catch (IOException e) {
                   System.out.print("\nNetwork error while connecting to ACS ("
                             + e.getMessage() + ")");
              } catch (ClassNotFoundException e) {
                   System.out.print("\nNetwork error while connecting to ACS ("
                             + e.getMessage() + ")");
                final SwingWorker worker =
                    new SwingWorker() {
                        @Override
                        protected KQML doInBackground() throws Exception {
                             KQML message = new KQML();
                             message.setSender(getName());
                             message.setReceiver(frame.receiverField.getText());
                             message.setContent(frame.contentField.getText());
                             message.setInReplyTo(frame.inReplyToField.getText());
                             message.setLanguage(frame.languageField.getText());
                             message.setOntology(frame.ontologyField.getText());
                             message.setPerformative(frame.perfomativeField.getText());
                             message.setReplyWith(frame.inReplayWithField.getText());
                             System.out.println(message.getTotalMsg());
                             sendMessage(message);
                             return message;
              frame = new SampleAgentFrame(name);
              frame.sendBtn.addActionListener(new java.awt.event.ActionListener() {
                   public void actionPerformed(java.awt.event.ActionEvent evt) {
                        try{
                             worker.execute();
                        } catch (Exception e) {
                             e.printStackTrace();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.validate();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public static SampleAgentFrame frame;
         public static void main(String[] args) {
              KQML message;
              SampleCommunicationAgentGUI agent = new SampleCommunicationAgentGUI("Chris");
              if (!agent.getACSStatus().equals(ACSStatus.CONNECTED)) {
                   System.out.println("\nERROR: Could not connect on ACS!");
                   return;
              while (true) {
                   message = agent.getMessage();
                   frame.messageTextArea.append(message.getContent() + "\r\n");
         protected static class SampleAgentFrame extends JFrame {
              //Some variables
              public SampleAgentFrame(String name) {
                   setTitle(name);
                   initComponents(name);
               * Initializes the GUI.
              private void initComponents(String name) {
                   //Init components
    }

  • Problem with addRow and MultiLine Cell renderer

    Hi ,
    Ive a problem with no solution to me .......
    Ive seen in the forum and Ivent found an answer.......
    The problem is this:
    Ive a JTable with a custom model and I use a custom multiline cell renderer.
    (becuse in the real application "way" hasnt static lenght)
    When I add the first row all seem to be ok.....
    when I try to add more row I obtain :
    java.lang.ArrayIndexOutOfBoundsException: 1
    at javax.swing.SizeSequence.insertEntries(SizeSequence.java:332)
    at javax.swing.JTable.tableRowsInserted(JTable.java:2926)
    at javax.swing.JTable.tableChanged(JTable.java:2858)
    at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableMo
    del.java:280)
    at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTa
    bleModel.java:215)
    at TableDemo$MyTableModel.addRow(TableDemo.java:103)
    at TableDemo$2.actionPerformed(TableDemo.java:256)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:17
    64)
    at javax.swing.AbstractButton$ForwardActionEvents.actionPerformed(Abstra
    ctButton.java:1817)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:419)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:257
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:245)
    at java.awt.Component.processMouseEvent(Component.java:5134)
    at java.awt.Component.processEvent(Component.java:4931)
    at java.awt.Container.processEvent(Container.java:1566)
    at java.awt.Component.dispatchEventImpl(Component.java:3639)
    at java.awt.Container.dispatchEventImpl(Container.java:1623)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3165)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
    at java.awt.Container.dispatchEventImpl(Container.java:1609)
    at java.awt.Window.dispatchEventImpl(Window.java:1590)
    at java.awt.Component.dispatchEvent(Component.java:3480)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchTh
    read.java:197)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)
    This seems to be caused by
    table.setRowHeight(row,(getPreferredSize().height+2)); (line 164 of my example code)
    About the model I think its ok.....but who knows :-(......
    Please HELP me in anyway!!!
    Example code :
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class TableDemo extends JFrame {
    private boolean DEBUG = true;
    MyTableModel myModel = new MyTableModel();
    MyTable table = new MyTable(myModel);
    int i=0;
    public TableDemo() {
    super("TableDemo");
    JButton bottone = new JButton("Aggiungi 1 elemento");
    table.setPreferredScrollableViewportSize(new Dimension(500, 70));
    //table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    getContentPane().add(bottone,BorderLayout.NORTH);
    getContentPane().add(scrollPane, BorderLayout.CENTER);
    bottone.addActionListener(Add_Action);
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    class MyTable extends JTable {
    MultiLineCellRenderer multiRenderer=new MultiLineCellRenderer();
    MyTable(TableModel tm)
    super(tm);
    public TableCellRenderer getCellRenderer(int row,int col) {
              if (col==1) return multiRenderer;
              else return super.getCellRenderer(row,col);
    class MyTableModel extends AbstractTableModel {
    Vector data=new Vector();
    final String[] columnNames = {"Name",
    "Way",
    "DeadLine (ms)"
    public int getColumnCount() { return 3; }
    public int getRowCount() { return data.size(); }
    public Object getValueAt(int row, int col) {
    Vector rowdata=(Vector)data.get(row);
                                                                return rowdata.get(col); }
    public String getColumnName(int col) {
    return columnNames[col];
    public void setValueAt (Object value, int row,int col)
         //setto i dati della modifica
    Vector actrow=(Vector)data.get(row);
    actrow.set(col,value);
         this.fireTableCellUpdated(row,col);
         public Class getColumnClass(int c)
              return this.getValueAt(0,c).getClass();
         public boolean isCellEditable(int row, int col) {
    //Note that the data/cell address is constant,
    //no matter where the cell appears onscreen.
    if (col == 1)
    return false;
    else
    return true;
    public void addRow (String name,ArrayList path,Double dead) {
         Vector row =new Vector();
         row.add(name);
         row.add(path);
         row.add(dead);
         row.add(name); //!!!Mi tengo questo dato da utilizzare come key per andare a
         //prendere il path nella lista dei paths di Project
         //(needed as key to retrive data if name in col. 1 is changed)
         data.add(row);
         //Inspector.inspect(this);
         System.out.println ("Before firing Adding row...."+this.getRowCount());
         this.fireTableRowsInserted(this.getRowCount(),this.getRowCount());
    public void delRow (String namekey)
    for (int i=0;i<this.getRowCount();i++)
    if (namekey.equals(this.getValueAt(i,3)))
    data.remove(i);
    this.fireTableRowsDeleted(i,i);
    //per uscire dal ciclo
    i=this.getRowCount();
    public void delAllRows()
    int i;
    int bound =this.getRowCount();     
    for (i=0;i<bound;i++)     
         {data.remove(0);
         System.out.println ("Deleting .."+data);
    this.fireTableRowsDeleted(0,i);          
    class MultiLineCellRenderer extends JTextArea implements TableCellRenderer {
    private Hashtable rowHeights=new Hashtable();
    public MultiLineCellRenderer() {
    setEditable(false);
    setLineWrap(true);
    setWrapStyleWord(true);
    //this.setBorder(new Border(
    public Component getTableCellRendererComponent(JTable table,Object value,                              boolean isSelected, boolean hasFocus, int row, int column) {
    //System.out.println ("Renderer called"+value.getClass());
    if (value instanceof ArrayList) {
    String way=new String     (value.toString());
    setText(way);
    TableColumn thiscol=table.getColumn("Way");
    //System.out.println ("thiscol :"+thiscol.getPreferredWidth());
    //setto il size della JTextarea sulle dimensioni della colonna
    //per quanto riguarda il widht e su quelle ottenute da screen per l'height
    this.setSize(thiscol.getPreferredWidth(),this.getPreferredSize().height);
    // set the table's row height, if necessary
    //System.out.println ("Valore getPreferred.height"+getPreferredSize().height);
         if (table.getRowHeight(row)!=(this.getPreferredSize().height+2))
         {System.out.println ("Setting Row :"+row);
             System.out.println ("Dimension"+(getPreferredSize().height+2));
             System.out.println ("There are "+table.getRowCount()+"rows in the table ");
             if (row<table.getRowCount())
             table.setRowHeight(row,(getPreferredSize().height+2));
    else
    setText("");
    return this;
    /**Custom JTextField Subclass che permette all'utente di immettere solo numeri
    class WholeNumberField extends JTextField {
    private Toolkit toolkit;
    private NumberFormat integerFormatter;
    public WholeNumberField(int value, int columns) {
    super(columns);
    toolkit = Toolkit.getDefaultToolkit();
    integerFormatter = NumberFormat.getNumberInstance(Locale.US);
    integerFormatter.setParseIntegerOnly(true);
    setValue(value);
    public int getValue() {
    int retVal = 0;
    try {
    retVal = integerFormatter.parse(getText()).intValue();
    } catch (ParseException e) {
    // This should never happen because insertString allows
    // only properly formatted data to get in the field.
    toolkit.beep();
    return retVal;
    public void setValue(int value) {
    setText(integerFormatter.format(value));
    protected Document createDefaultModel() {
    return new WholeNumberDocument();
    protected class WholeNumberDocument extends PlainDocument {
    public void insertString(int offs,
    String str,
    AttributeSet a)
    throws BadLocationException {
    char[] source = str.toCharArray();
    char[] result = new char[source.length];
    int j = 0;
    for (int i = 0; i < result.length; i++) {
    if (Character.isDigit(source))
    result[j++] = source[i];
    else {
    toolkit.beep();
    System.err.println("insertString: " + source[i]);
    super.insertString(offs, new String(result, 0, j), a);
    ActionListener Add_Action = new ActionListener() {
              public void actionPerformed (ActionEvent e)
              System.out.println ("Adding");
              ArrayList way =new ArrayList();
              way.add(new String("Uno"));
              way.add(new String("Due"));
              way.add(new String("Tre"));
              way.add(new String("Quattro"));
              myModel.addRow(new String("Nome"+i++),way,new Double(0));     
    public static void main(String[] args) {
    TableDemo frame = new TableDemo();
    frame.pack();
    frame.setVisible(true);

    In the addRow method, change the line
    this.fireTableRowsInserted(this.getRowCount(),this.getRowCount()); to
    this.fireTableRowsInserted(data.size() - 1, data.size() - 1);Sai Pullabhotla

  • Problem with JFrame's dispose();

    Hello everyone,
    I'm having a problem with JFrame's dispose() method. In my program I have 2 classes which go into full screen. On each screen there is a button to switch to the other screen. The first time I push the button on both of them the other screen closes, which is what I want. However, if I push the same button more than twice - like by going from Screen1 to Screen2 and Screen2 to Screen1 and then Screen1 to Screen2 - I get 2 screens. If I keep doing that I eventually get 10+ screens up, which is bad. How do I prevent that?

    There's a lot of code, so I'll just post up the part that does it.
    backButton.addActionListener(new ActionListener()
                  public void actionPerformed(ActionEvent e)
                      soundManagerM.close();
                        new MenuScreen().setVisible(true);
                        dispose();
             });I don't think it opens up 2 at once, because it would play multiple music right?

  • Problem With ButtonUI in an Auxiliary Look and Feel

    This is my first post to one of these forums, so I hope everything works correctly.
    I have been trying to get an axiliary look and feel installed to do some minor tweaking to the default UI. In particular, I need it to work with Windows and/or Metal as the default UI. For the most part I let the installed default look and feel handle things with my code making some colors lighter, darker, etc. I also play with focus issues by adding FocusListeners to some components. I expect my code to work reasonably well no matter what the default look and feel is. It works well with Motif, Metal, and Windows, the only default look and feels I've tested with. What I'm going to post is a stripped down version of what I have been working on. This example makes gross changes to the JButton background and foreground colors in order to illustrate what I've encountered.
    I have three source code files. The first, Problem.java, creates a JFrame and adds five buttons to it. One button installs MyAuxLookAndFeel as an auxiliary look and feel using MyAuxButtonUI for the look and feel of JButtons. The next button removes that look and feel. The next button does nothing except print a line to System.out. The next button installs MyAuxLookAndFeel as an auxiliary look and feel using MyModButtonUI for the look and feel of JButtons. The last button removes that look and feel.
    The problem is, when I install the first auxiliary look and feel, buttons are no longer tabable. Also, they cannot be invoked by pressing the space button when they're in focus. When I remove the first auxiliary look and feel everything reverts to behaving normally. When I add the "Mod" version, button tabability is fine. The only difference is I've added the following code:
    if ( c.isFocusable() ) {
       c.setFocusable(true);
    }That strikes me as an odd piece of code to profoundly change the program behavior. Anyway, after adding and removing the "Mod" look and feel, the tababilty is forever fixed. That is, if I subsequently re-install the first look and feel, tababilty works just fine.
    The problem with using the space bar to select a focused button is more problematic. My class is not supposed to mess with the default look and feel which may or may not use the space bar to press the button with focus. When the commented code in MyModButtonUI is uncommented, things behave correctly. Even the statement
    button.getInputMap().remove( spaceKeyStroke );doesn't mess things up after the auxiliary look and feel is removed. So far I've tested this with JRE 1.4.2_06 under Windows 2000, JRE 1.4.2_10 under Windows XP, and JRE 1.5.0_06 under Windows XP and the behavior is the same.
    All of this leads me to two questions.
    1. Is my approach fundamentally flawed? I've extended TextUI and ScrollBarUI with no problems. This is the only problem I've encountered with ButtonUI. My real workaround for the space bar issue is better than the one I've supplied in the example, but it certainly is not guaranteed to work for any arbitrary default look and feel.
    2. Assuming I have no fundamental problems with my approach, it's possible I've found a real bug. I searched the bug database and couldn't find anything like this. Of course, this is the first time I've tried seasrching the database for a bug so my I'm doing it badly. Has this already been reported as a bug? Is there any reason I shouldn't report it?
    What follows is the source code for my example. It's in three files because the two ButtonUI classes must be public in order to work. Thanks for insight you can provide.
    Bill
    File Problem.java:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Problem extends JFrame {
       public boolean isAuxInstalled = false;
       public boolean isModInstalled = false;
       public LookAndFeel lookAndFeel = new MyAuxLookAndFeel();
       private static int ctr = 0;
       public static void main( String[] args ) {
          new Problem();
       public Problem() {
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          setSize(250, 150);
          setTitle("Button Test");
          JButton install = new JButton("Install");
          JButton remove = new JButton("Remove");
          JButton doNothing = new JButton("Do Nothing");
          JButton installMod = new JButton("Install Mod");
          JButton removeMod = new JButton("Remove Mod");
          this.getContentPane().setLayout(new FlowLayout());
          this.getContentPane().add(install);
          this.getContentPane().add(remove);
          this.getContentPane().add(doNothing);
          this.getContentPane().add(installMod);
          this.getContentPane().add(removeMod);
          install.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( !isAuxInstalled ) {
                   isAuxInstalled = true;
                   UIManager.addAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          remove.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( isAuxInstalled ) {
                   isAuxInstalled = false;
                   UIManager.removeAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          doNothing.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                System.out.println( "Do nothing " + (++ctr) );
          installMod.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( !isModInstalled ) {
                   isModInstalled = true;
                   UIManager.addAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          removeMod.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                if ( isModInstalled ) {
                   isModInstalled = false;
                   UIManager.removeAuxiliaryLookAndFeel( lookAndFeel );
                   SwingUtilities.updateComponentTreeUI( Problem.this );
          setVisible(true);
       class MyAuxLookAndFeel extends LookAndFeel {
          public String getName() {
             return "Button Test";
          public String getID() {
             return "Not well known";
          public String getDescription() {
             return "Button Test Look and Feel";
          public boolean isSupportedLookAndFeel() {
             return true;
          public boolean isNativeLookAndFeel() {
             return false;
          public UIDefaults getDefaults() {
             UIDefaults table = new MyDefaults();
             Object[] uiDefaults = {
                "ButtonUI", (isModInstalled ? "MyModButtonUI" : "MyAuxButtonUI"),
             table.putDefaults(uiDefaults);
             return table;
       class MyDefaults extends UIDefaults {
          protected void getUIError(String msg) {
    //         System.err.println("(Not) An annoying error message!");
    }File MyAuxButtonUI.java:
    import javax.swing.*;
    import java.awt.*;
    import javax.swing.plaf.*;
    import javax.swing.plaf.multi.*;
    import javax.accessibility.*;
    public class MyAuxButtonUI extends ButtonUI {
       private Color background;
       private Color foreground;
       private ButtonUI ui = null;
       public static ComponentUI createUI( JComponent c ) {
          return new MyAuxButtonUI();
       public void installUI(JComponent c) {
          MultiButtonUI multiButtonUI = (MultiButtonUI) UIManager.getUI(c);
          this.ui = (ButtonUI) (multiButtonUI.getUIs()[0]);
          super.installUI( c );
          background = c.getBackground();
          foreground = c.getForeground();
          c.setBackground(Color.GREEN);
          c.setForeground(Color.RED);
       public void uninstallUI(JComponent c) {
          super.uninstallUI( c );
          c.setBackground(background);
          c.setForeground(foreground);
          this.ui = null;
       public void paint(Graphics g, JComponent c) {
          this.ui.paint( g, c );
       public void update(Graphics g, JComponent c) {
          this.ui.update( g, c );
       public Dimension getPreferredSize(JComponent c) {
          if ( this.ui == null ) {
             return super.getPreferredSize( c );
          return this.ui.getPreferredSize( c );
       public Dimension getMinimumSize(JComponent c) {
          if ( this.ui == null ) {
             return super.getMinimumSize( c );
          return this.ui.getMinimumSize( c );
       public Dimension getMaximumSize(JComponent c) {
          if ( this.ui == null ) {
             return super.getMaximumSize( c );
          return this.ui.getMaximumSize( c );
       public boolean contains(JComponent c, int x, int y) {
          if ( this.ui == null ) {
             return super.contains( c, x, y );
          return this.ui.contains( c, x, y );
       public int getAccessibleChildrenCount(JComponent c) {
          if ( this.ui == null ) {
             return super.getAccessibleChildrenCount( c );
          return this.ui.getAccessibleChildrenCount( c );
       public Accessible getAccessibleChild(JComponent c, int ii) {
          if ( this.ui == null ) {
             return super.getAccessibleChild( c, ii );
          return this.ui.getAccessibleChild( c, ii );
    }File MyModButtonUI.java:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.plaf.*;
    public class MyModButtonUI extends MyAuxButtonUI
       static KeyStroke spaceKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0 );
       public static ComponentUI createUI( JComponent c ) {
          return new MyModButtonUI();
       public void installUI(JComponent c) {
          super.installUI(c);
          c.setBackground(Color.CYAN);
          if ( c.isFocusable() ) {
             c.setFocusable(true);
    //      final JButton button = (JButton) c;
    //      button.getInputMap().put( spaceKeyStroke, "buttonexample.pressed" );
    //      button.getActionMap().put( "buttonexample.pressed", new AbstractAction() {
    //         public void actionPerformed(ActionEvent e) {
    //            button.doClick();
    //   public void uninstallUI(JComponent c) {
    //      super.uninstallUI(c);
    //      JButton button = (JButton) c;
    //      button.getInputMap().remove( spaceKeyStroke );
    //      button.getActionMap().remove( "buttonexample.pressed" );
    }

    here is the code used to change the current look and feel :
    try {
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
             catch (InstantiationException e)
                  System.out.println("Error occured  "+ e.toString());
             catch (ClassNotFoundException e)
                  System.out.println("Error occured  "+ e.toString());
             catch (UnsupportedLookAndFeelException e)
                  System.out.println("Error occured  "+ e.toString());
             catch (IllegalAccessException e)
                  System.out.println("Error occured in .. " + e.toString());
             Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
             Fenetre fen = new Fenetre();
             fen.setSize(dim.width, dim.height);
             fen.setResizable(false);
                 fen.setLocation(0, 0);
                  fen.setVisible(true);

  • Problem with GUI in applet

    Hai to all,
    I am having a problem with GUI in applets
    My first class extends a JPanel named A_a
    import javax.swing .*;
    import java.awt.*;
    import java.awt.event.*;
    public class A_a extends JPanel
    JButton jb;
    JTextArea text;
    public A_a()
    setLayout(new FlowLayout());
    jb=new JButton("Click me");
    //add(jb);
    text=new JTextArea(5,20);
    add(text);
    public void text_appendText(String aa)
    System.out.println("I AM IN A_a");
    text.append(aa);
    text.revalidate();
    revalidate();
    /*public static void main(String ags[])
    A_a a = new A_a();
    JFrame frame=new JFrame();
    frame.getContentPane().add(a);
    frame.pack();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { System.exit(0); }
    frame.setSize(200,200);
    frame.show();
    and then I am using other class B_b which is an applet carries a exitsing panel (A_a) inside it .
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class B_b extends JApplet
    public A_a a;
    public void init()
    a=new A_a();
    getContentPane().add(a);
    public void text_appendText(String aa)
    final String aaa =aa;
    new Thread(new Runnable()
    public void run()
    a=new A_a();
    a.setBackground(new java.awt.Color(255,200,200));
    System.out.println("I AM IN B_b");
    a.text.append(aaa);
    a.text.revalidate();
    getContentPane().remove(a);
    resize(500,500);
    }).start();
    and the I am using the second applet C_c in which by performing a button action the old panel A_a should get removed and replace the new panel D_a (which is not here )in the applet B_b with all other components(namely button , text fields etc)
    import javax.swing .*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.*;
    public class C_c extends JApplet implements ActionListener
    JButton jbt;
    JTextArea jta;
    public void init()
    getContentPane().setLayout(new FlowLayout());
    jbt=new JButton("Click me");
    jbt.addActionListener(this);
    getContentPane().add(jbt);
    jta=new JTextArea(5,20);
    getContentPane().add(jta);
    public void actionPerformed(ActionEvent ae)
    Enumeration e = getAppletContext().getApplets();
    Applet applets = null;
    while(e.hasMoreElements())
    applets=(Applet)e.nextElement();
    if ( applets instanceof B_b)
    System.out.println("I AM CLASS C_c");
    ((B_b)applets).text_appendText(jta.getText());
    ((B_b)applets).remove());
    ((B_b)applets).getContentPane().add(D_d);
    both the applets C_c and B_b are in same browser page
    How can i achive that pls help .

    Just to make the code readable...
    import javax.swing .*;
    import java.awt.*;
    import java.awt.event.*;
    public class A_a extends JPanel
    JButton jb;
    JTextArea text;
    public A_a()
    setLayout(new FlowLayout());
    jb=new JButton("Click me");
    //add(jb);
    text=new JTextArea(5,20);
    add(text);
    public void text_appendText(String aa)
    System.out.println("I AM IN A_a");
    text.append(aa);
    text.revalidate();
    revalidate();
    /*public static void main(String ags[])
    A_a a = new A_a();
    JFrame frame=new JFrame();
    frame.getContentPane().add(a);
    frame.pack();
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) { System.exit(0); }
    frame.setSize(200,200);
    frame.show();
    }and then I am using other class B_b which is an applet carries a exitsing panel (A_a) inside it .
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class B_b extends JApplet
    public A_a a;
    public void init()
    a=new A_a();
    getContentPane().add(a);
    public void text_appendText(String aa)
    final String aaa =aa;
    new Thread(new Runnable()
    public void run()
    a=new A_a();
    a.setBackground(new java.awt.Color(255,200,200));
    System.out.println("I AM IN B_b");
    a.text.append(aaa);
    a.text.revalidate();
    getContentPane().remove(a);
    resize(500,500);
    }).start();
    }and the I am using the second applet C_c in which by performing a button action the old panel A_a should get removed and replace the new panel D_a (which is not here )in the applet B_b with all other components(namely button , text fields etc)
    import javax.swing .*;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import java.util.*;
    public class C_c extends JApplet implements ActionListener
    JButton jbt;
    JTextArea jta;
    public void init()
    getContentPane().setLayout(new FlowLayout());
    jbt=new JButton("Click me");
    jbt.addActionListener(this);
    getContentPane().add(jbt);
    jta=new JTextArea(5,20);
    getContentPane().add(jta);
    public void actionPerformed(ActionEvent ae)
    Enumeration e = getAppletContext().getApplets();
    Applet applets = null;
    while(e.hasMoreElements())
    applets=(Applet)e.nextElement();
    if ( applets instanceof B_b)
    System.out.println("I AM CLASS C_c");
    ((B_b)applets).text_appendText(jta.getText());
    ((B_b)applets).remove());
    ((B_b)applets).getContentPane().add(D_d);
    }

Maybe you are looking for

  • Unable to delete request from write-optimized DSO (Error during rollback)

    Hi Gurus, I am trying to delete a delta request from a Write-Optimized DSO. This request was uploaded with a DTP from another Write-optimized DSO. The actual overall status of the request is RED and the description of that status is now: 'Error durin

  • CS5 having problems embedding fonts

    I am trying to embed a couple of fonts - one for each dynamic textbox. The first has Arial Bold embeded, and the second has Arial Regular. I have used the embed panel and set the character range. Oddly, when I export the SWF, both textboxes come out

  • Preview - PDF files?

    Okay soo confused here. I cannot find where to post this topic. I have an online class, and that class comes with an online textbook that is opened with the application Preview automatically. I want to search for a specific topic, so I enter it in th

  • Error in javamail with weblogic 6.0

    Hi,I am facing the following error while installing Javamail in weblogic 6.0.javax.activation.UnsupportedDataTypeException: no object DCH for MIME type text/plain; charset=us-ascii at javax.activation.ObjectDataContentHandler.writeTo(DataHandler.java

  • Dba_jobs interval

    hi guys, i have a dba job scheduled in oracle 9i database. when i query from dba_jobs, the interval is TRUNC(LAST_DAY(LAST_DAY(SYSDATE)+1))+2/24. May i know how to interprete it? anyway to check when the job is 1st scheduled? thanks