SetEnabled of a button?

I have set the button to disable using
button.setEnabled(false)The text in the button becomes grey, but it still can perform the action when we click the button. Actually why it can be like this way?

I have checked it, i use the button for fire the drawing. When the drawing haven't finished, i click again when in the disable mode, but it still can perform next drawing after the first drawing (first click of the button) finished.
btnaddActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                btnActionPerformed(evt);
private void btnActionPerformed(ActionEvent evt) {
         Graphics2D g = (Graphics2D)getGraphics();
         btn.setEnabled(false);
         clearText();
     super.paint(g);
         draw(g);
         btn.setEnabled(true);
    }

Similar Messages

  • Disabling icon in button

    Hello everybody,
    I'm trying to disable a button. This is what i'm doing:
    btn.setDisabledIcon(btn.getIcon());
    btn.setEnabled(false);
    btn is the instance of JButton.
    My button is getting disabled but it's color is not turning to gray. Can somebody help me out please.
    Thank you in advance,

    Hi all,
    Thank you for your suggestions. It works and the button along with the icon becomes gray. Can anybody help me out in the following:
    In the JBuilder, as soon as i save the files, 'save' button in the toolbar becomes disabled. When the button is disabled, what all i see is a disabled icon. I can't even make out that the icon is part of a disabled button which means button's boundaries are removed when the button is disabled. Can anybody help me out in achieving this?
    In other words, this is what i'm trying to achieve:
    when i say btn.setenabled(false), my button along with the icon is disabled. So in this state my user can make out that the disabled icon is sitting on a disabled button. Is there any way i can take out that button part by just making the 'disabled icon' sitting on the tool bar?
    Thank you in advance

  • Why do I need to catch this exception?

    Hello all
    This is a question about exception handling. I have to build a diary application that lets you save reminders on particular dates using xml. Just to make it a little tougher, I was not allowed to use the Calendar class. This is the code I wrote:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*; 
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;     
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;                                                                                                                                                                                                                         
    import static java.lang.Math.*;
    public class CalendarAssignment extends JFrame implements ActionListener
         int MonthLength [] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
         public JButton [] days = new JButton[43];
         private JLabel lbl, reminderlbl;
         private JPanel top, grid, remindercenter, reminderbottom;
         private JFrame reminderframe;
         private JTextField year1, reminderinput, dayno;
         private JComboBox months;
         private Container container;
         private JButton fetch, save, cancel;
         private Document doc;
         private File file;
         private Node node;
         private String year, month, day;
              public static void main( String[] args ) {
                   CalendarAssignment c = new CalendarAssignment( );
                   c.setSize( 400, 300 );
                   c.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
                   c.show( );
              public CalendarAssignment( ) {
                   int CurrentYear, CurrentMonth;
                   String YearString, MonthString, Now;
                   Date today;
                   container = getContentPane( );
                   container.setLayout( new BorderLayout( ) );
                   SimpleDateFormat DateFormatter;
                   DateFormatter = new SimpleDateFormat( "MM.yyyy" );
                   today = new Date( );
                   Now = DateFormatter.format( today );
                   MonthString = Now.substring( 0,2 );
                   YearString = Now.substring( 3,7 );
                   CurrentMonth = Integer.valueOf( MonthString );
                   CurrentYear = Integer.valueOf( YearString );
                   top = new JPanel( );
                        String [] items = { "January", "February", "March", "April", "May", "June",
                                      "July", "August", "September", "October", "November",
                                      "December" };
                        months = new JComboBox( items );
                        months.setEditable( false );
                        months.setSelectedIndex( CurrentMonth - 1 );          
                        year1 = new JTextField( );
                        year1.setText( YearString );
                        year1.setEditable( true );
                        year1.setHorizontalAlignment( year1.CENTER );
                        fetch = new JButton( "Fetch Month" );
                        fetch.addActionListener( this );
                        top.setLayout( new GridLayout( 1, 3, 20, 0 ) );
                        top.add( months );
                        top.add( year1 );
                        top.add( fetch );
                   grid = new JPanel( );
                        grid.setLayout( new GridLayout( 7, 7, 0, 0 ) );
                        String [] week = { "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun" };
                        for ( int a = 0; a < 7; a ++ ) {
                                  JLabel lbl = new JLabel( week[a], JLabel.CENTER );
                                  grid.add( lbl );
                        for ( int i = 0; i < 42; i ++ ) {
                                  days[i] = new JButton( );
                                  grid.add( days[i] );
                                  days.addActionListener( this );
                        DrawCalendar( CurrentMonth, CurrentYear );
                        container.add( top, BorderLayout.NORTH );
                        container.add( grid, BorderLayout.CENTER );
              private void DrawCalendar( int SelectMonth, int SelectYear ) {
                        int DisplayMonthLength, Buttons;
                        String ButtonID = "";
                        int OffSet = MonthStart( SelectMonth, SelectYear );
                        DisplayMonthLength = MonthLength [SelectMonth - 1];
                        if ( SelectMonth == 2 )
                             DisplayMonthLength += LeapYear( SelectYear );
                        for ( Buttons = 1; Buttons < 43; Buttons ++ ) {
                             if ( ( Buttons <= OffSet ) || ( Buttons > ( DisplayMonthLength + OffSet ) ) ) {
                                  ButtonID = "";
                                  days[Buttons-1].setEnabled( false );
                             else {
                                  ButtonID = Integer.toString( Buttons - OffSet );
                                  days[Buttons-1].setEnabled( true );
                        days[Buttons-1].setLabel( ButtonID );
                        grid.add( days[Buttons-1] );
              private int LeapYear( int year ) {
                        int FourHundred, OneHundred, Fourth;
                        FourHundred = year % 400;
                        OneHundred = year % 100;
                        Fourth = year % 4;
                        if( ( ( FourHundred == 0 ) ) || ( ( OneHundred != 0 ) && ( Fourth == 0 ) ) )
                             return ( 1 );
                        else
                             return ( 0 );
              private int MonthStart( int Month, int Year ) {
                        int OffSet, LastMonths, BeforeOrAfter, Years;
                        int AllDays = 0;
                        int YearDays = 365;
                        int YearMonths = 12;
                        BeforeOrAfter = Year - 2006;
                        Years = abs( BeforeOrAfter );
                        if( BeforeOrAfter != 0 )
                             BeforeOrAfter = BeforeOrAfter / Years;
                        switch( BeforeOrAfter ) {
                             case 1:
                                  for( int a = 2006; a < Year; a ++ ) {
                                       AllDays += YearDays + LeapYear( a );
                                  AllDays += LastMonthsCalc( Month, Year );
                             break;
                             case -1:
                                  for( int a = 2005; a > Year; a -- ) {
                                       AllDays += YearDays + LeapYear( a );
                                  for( LastMonths = YearMonths; LastMonths >= Month; LastMonths -- ) {
                                       AllDays += MonthLength[LastMonths - 1];
                                       if( LastMonths == 2 )
                                            AllDays += LeapYear( Year );
                             break;
                             default:
                                  if( Month > 1 )
                                       AllDays += ( LastMonthsCalc( Month, Year ) );
                        OffSet = AllDays % 7;
                        if( BeforeOrAfter ==( -1 ) )
                             return( 6 - OffSet );
                        else if( OffSet > 0 )
                             return( OffSet - 1 );
                        else
                             return( 6 );
              private int LastMonthsCalc( int Month, int Year ) {
                        int Counter;
                        int days = 0;
                        for( Counter = 1; Counter < Month; Counter ++ ) {
                             days += MonthLength[Counter - 1];
                             if( Counter == 2 )
                                  days += LeapYear( Year );
                        return( days );
              public void CreateReminder( String buttonID, String yearID, String monthID ) {
                        reminderframe = new JFrame( );
                        reminderlbl = new JLabel( );
                        reminderframe.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                        remindercenter = new JPanel( );
                             reminderlbl = new JLabel( "Please type in reminder to be saved for " + buttonID + " " + monthID + " " + yearID + ":", JLabel.CENTER );
                             reminderinput = new JTextField( 30 );
                             reminderinput.setHorizontalAlignment( reminderinput.CENTER );
                             reminderinput.setEditable( true );
                             remindercenter.setLayout( new GridLayout( 2, 1, 0, 0 ) );
                             remindercenter.add( reminderlbl );
                             remindercenter.add( reminderinput );
                        reminderbottom = new JPanel( );
                             save = new JButton( "Save" );
                             save.addActionListener( this );
                             cancel = new JButton( "Cancel" );
                             cancel.addActionListener( this );
                             dayno = new JTextField( buttonID );
                             dayno.setEditable( false );
                             dayno.setEnabled( false );
                             dayno.show( false );
                             reminderbottom.setLayout( new FlowLayout( ) );
                             reminderbottom.add( save );
                             reminderbottom.add( cancel );
                             reminderbottom.add( dayno );
                        reminderframe.setSize( 500, 75 );
                        reminderframe.add( remindercenter );
                        reminderframe.add( reminderbottom );
                        reminderframe.pack( );
                        reminderframe.show( );
              public void SaveReminder( String dayID, String yearID, String monthID ) throws Exception {
                        file = new File( "Diary.xml" );
                        doc = DocumentBuilderFactory.newInstance( ).newDocumentBuilder( ).parse( file.toURL( ).toString( ) );
                        String year = yearID;
                        String month = monthID;
                        String day = dayID;
                        //System.out.println( year );
                        //System.out.println( month );
                        //System.out.println( day );
                        CreateEntry( doc.getDocumentElement( ) );
                        writeXmlFile( );
              public boolean CreateEntry( Node node ) {
                        Node searchNode;
                        searchNode = getYear( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Year" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", year );
                        node = searchNode;
                        searchNode = getMonth( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Month" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", month );
                        node = searchNode;
                        searchNode = getDay( node );
                        if( searchNode == null ) {
                             Element newNode = doc.createElement( "Day" );
                             searchNode = node.appendChild( newNode );
                             newNode.setAttribute( "Id", day );
                        node = searchNode;
                        String entry = reminderinput.getText( );
                        Node textNode = doc.createTextNode( entry );
                        node.appendChild( textNode );
                        return true;
              private Node getYear( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if(node.getNodeName( ).equals( "Year" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == year )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getMonth( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Month" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == month )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private Node getDay( Node node ) {
                        node = node.getFirstChild( );
                        while( node != null ) {
                             if( node.getNodeName( ).equals( "Day" ) && String.valueOf( node.getAttributes( ).item( 0 ).getNodeValue( ) ) == day )
                                  return node;
                                  node = node.getNextSibling( );                    
                        return null;
              private void writeXmlFile( ) throws Exception {
                   Source source = new DOMSource( doc );
                        Result result = new StreamResult( file );
                   Transformer xformer = TransformerFactory.newInstance( ).newTransformer( );
                   xformer.setOutputProperty( OutputKeys.INDENT,"yes" );
                   xformer.setOutputProperty( OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd" );
                   xformer.transform( source, result );
              public void actionPerformed( ActionEvent e ) {
                        String IDButton = e.getActionCommand( );
                        String IDYear = year1.getText( );
                        Object IDMonthObj = months.getSelectedItem( );
                        if( e.getSource( ) == fetch ) {
                             String YearText = year1.getText( );
                             int YearNumber = Integer.valueOf( YearText );
                             int MonthsIndex = months.getSelectedIndex( ) + 1;
                             DrawCalendar( MonthsIndex, YearNumber );
                        else if( e.getSource( ) == cancel ) {
                             reminderframe.hide( );
                        else if( e.getSource( ) == save ) {
                             String IDDay = dayno.getText( );
                             String IDMonth = String.valueOf( IDMonthObj );
                             SaveReminder( IDDay, IDYear, IDMonth );
                        else {
                             String IDMonth = String.valueOf( IDMonthObj );
                             Toolkit.getDefaultToolkit( ).beep( );
                             int n = JOptionPane.showConfirmDialog( null, "Set reminder on this date?", "Question", JOptionPane.YES_NO_OPTION );
                             if( n == JOptionPane.YES_OPTION ) {
                                  CreateReminder( IDButton, IDYear, IDMonth );
    If you compile it, you will realise that I get an error about exception handling. My lecturer gave me an example code of how to do the same thing without using a GUI:
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import java.io.*;
    import java.util.*;
    import org.w3c.dom.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    public class CallDOM
         Document doc;
         File file;
         Scanner input;
         int year, month, day;
         String currentYear, currentMonth;
         public static void main(String args[]) throws Exception
              CallDOM cd=new CallDOM();          
         CallDOM() throws Exception
              file=new File("Diary.xml");
              //create DOM from file
              doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(file.toURL().toString());
              input=new Scanner(System.in);
              System.out.println("1) Create entry");
              System.out.println("2) Read entry");
              System.out.println("3) Show Diary");
              System.out.println("4) Quit");
              int choice=input.nextInt();
              while(choice!=4)
                   switch(choice)
                        case 1: GetDate();CreateEntry(doc.getDocumentElement());break;
                        case 2: GetDate();ReadEntry(doc.getDocumentElement());break;
                        case 3: ShowDiary(doc.getDocumentElement());
                   System.out.println("1) Create entry");
                   System.out.println("2) Read entry");
                   System.out.println("3) Show Diary");
                   System.out.println("4) Quit");
                   choice=input.nextInt();
              writeXmlFile();
         public void GetDate()
              System.out.println("Enter date (dd mm yyyy)");
              day=input.nextInt();
              month=input.nextInt();
              year=input.nextInt();
         public boolean ReadEntry(Node node)
              node = getYear(node);
              if(node==null) return false;
              node = getMonth(node);
              if(node==null) return false;
              node = getDay(node);
              if(node==null) return false;
              node = node.getFirstChild();
              while(node!=null)
                   System.out.println(node.getNodeValue().trim());     
                   node=node.getNextSibling();
              return true;               
         public boolean CreateEntry(Node node)
              Node searchNode;
              searchNode = getYear(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Year");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(year));
              node = searchNode;
              searchNode = getMonth(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Month");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(month));
              node = searchNode;
              searchNode = getDay(node);
              if(searchNode==null)
                   Element newNode = doc.createElement("Day");
                   searchNode = node.appendChild(newNode);
                   newNode.setAttribute("Id",Integer.toString(day));
              node = searchNode;
              System.out.println("Enter Text");
              String entry=input.next();
              entry+=input.nextLine();
              Node textNode = doc.createTextNode(entry);
              node.appendChild(textNode);
              return true;               
         public void ShowDiary(Node node)
              Stack<Node> stack=new Stack<Node>();
              Node child;
              stack.push(node);
              while(!stack.empty())
                   node = stack.pop();
                   if(ProcessNode(node))
                        child = node.getLastChild();
                        while(child!=null)
                             stack.push(child);
                             child = child.getPreviousSibling();
         private boolean ProcessNode(Node node)
              if(node.getNodeName().equals("Year"))
                   currentYear=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Month"))
                   currentMonth=node.getAttributes().item(0).getNodeValue();
              if(node.getNodeName().equals("Day"))
                   System.out.print(node.getAttributes().item(0).getNodeValue()+"/"+
                                            currentMonth+"/"+currentYear+": ");
                   node=node.getFirstChild();
                   while(node!=null)
                        System.out.println(node.getNodeValue().trim());
                        node=node.getNextSibling();
                   return false;
              return true;               
         private Node getYear(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Year")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==year)
                             return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getMonth(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Month")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==month)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private Node getDay(Node node)
              node=node.getFirstChild();
              while(node!=null)
                   if(node.getNodeName().equals("Day")
                        && Integer.valueOf(node.getAttributes().item(0).getNodeValue())==day)
                        return node;
                   node = node.getNextSibling();                    
              return null;
         private void writeXmlFile() throws Exception
            Source source = new DOMSource(doc);
            Result result = new StreamResult(file);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            xformer.setOutputProperty(OutputKeys.INDENT,"yes");
            xformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"Diary.dtd");
            xformer.transform(source, result);
    }My question is, why does the exceptions in the example code not need to be caught? And why do I have to catch the exceptions in my code? Several exceptions are thrown in the example code, but there is no catch statement.
    Thanks for any advice!!

    Since your question didn't come with any relevant details, and since you have huge steaming piles of irrelevant code, all I can give is a general answer to "Why do I need to catch this exception?"
    [url http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html]Exception tutorial at http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html
    Here's a quick overview of exceptions:
    The base class for all exceptions is Throwable. Java provides Exception and Error that extend Throwable. RuntimeException (and many others) extend Exception.
    RuntimeException and its descendants, and Error and its descendants, are called unchecked exceptions. Everything else is a checked exception.
    If your method, or any method it calls, can throw a checked exception, then your method must either catch that exception, or declare that your method throws that exception. This way, when I call your method, I know at compile time what can possibly go wrong and I can decide whether to handle it or just bubble it up to my caller. Catching a given exception also catches all that exception's descendants. Declaring that you throw a given exception means that you might throw that exception or any of its descendants.
    Unchecked exceptions (RuntimeException, Error, and their descendants) are not subject to those restrictions. Any method can throw any unchecked exception at any time without declaring it. This is because unchecked exceptions are either the sign of a coding error (RuntimeException), which is totally preventable and should be fixed rather than handled by the code that encounters it, or a problem in the VM, which in general can not be predicted or handled.

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

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

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

  • Need help merging these two files togehter

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

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

  • Help in swing app. tic tac toe

    Trying to make this tic tac toe game. Need a little help. I want the newGameBUT to start the game over, and I would like turnTF to display if a tie occurs. (I tried using *if button.enabled(false) {* but it didn't work. If anyone could help me out, that'd be great. Oh, also, the new game button currently add's 1 to whoever won so far, which is really weird =x. Thanks beforehand.
    import java.awt.*; //import
    import javax.swing.*; //import
    import java.awt.event.*; //import
    import java.awt.Rectangle; //import
    import java.awt.Font; //import
    import javax.swing.BorderFactory; //import
    import javax.swing.border.TitledBorder; //import
    import java.awt.Color; //import
    public class TicTacToeFrame extends JFrame implements ActionListener {
        public TicTacToeFrame() {
            try { //try the following
                jbInit();
            } catch (Exception ex) { // exit on [X]
                ex.printStackTrace(); //exit and print errors
        int xWon = 0; //counting how many times O has won
        int oWon = 0; //counting how many times X has one
        double i = 0; // loop variable to determine turn
        public void actionPerformed(ActionEvent e) {
            String turn = "null"; //current turn
            String notTurn = "null"; //not current turn
            newGameBUT.setEnabled(false); //disable new game button
            if (i % 2 == 0) { // for determining who's turn it is
                turn = "X"; // X's turn when counter is even
                notTurn = "O"; //notTurn used to show who's turn it is in turnTF
            if (i % 2 != 0) { // for determining who's turn it is
                turn = "O"; // O's turn when counter is odd
                notTurn = "X"; //notTurn used to show who's turn it is in turnTF
            turnTF.setText("Currently " + notTurn + "'s turn"); // displays turn
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~O WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
             OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO
    //horizontal, top, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqFour == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, o wins
            if (sqOne == "O") { //checking too see if player O has won
                if (sqTwo == "O") {
                    if (sqThree == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, o wins
            if (sqOne == "O") {
                if (sqFive == "O") { //checking too see if player O has won
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, o wins
            if (sqTwo == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqEight == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqSix == "O") {
                    if (sqNine == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top right to bottom left, o wins
            if (sqThree == "O") { //checking too see if player O has won
                if (sqFive == "O") {
                    if (sqSeven == "O") {
                        turnTF.setText("O wins!"); //O wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
             $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~X WINS~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
             XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    //horizontal, top, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFour == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    //vertical, left, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqTwo == "X") {
                    if (sqThree == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // diagonal, top left to bottom right, x wins
            if (sqOne == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, mid, x wins
            if (sqTwo == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqEight == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
    // horizontal, bottom, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqSix == "X") {
                    if (sqNine == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            // diagonal, top right to bottom left, x wins
            if (sqThree == "X") { //checking too see if player X has won
                if (sqFive == "X") {
                    if (sqSeven == "X") {
                        turnTF.setText("X wins!"); //X wins text
                        sqOneBUT.setEnabled(false); //disable all buttons
                        sqTwoBUT.setEnabled(false); //disable all buttons
                        sqThreeBUT.setEnabled(false); //disable all buttons
                        sqFourBUT.setEnabled(false); //disable all buttons
                        sqFiveBUT.setEnabled(false); //disable all buttons
                        sqSixBUT.setEnabled(false); //disable all buttons
                        sqSevenBUT.setEnabled(false); //disable all buttons
                        sqEightBUT.setEnabled(false); //disable all buttons
                        sqNineBUT.setEnabled(false); //disable all buttons
            String wins = turnTF.getText(); //Reading who won to print win winTF
            if (wins.equals("X wins!")) { //if X wins
                xWon++; //adding 1 to X's amount of wins
                String xWonString = Integer.toString(xWon); //converting to String
                xWinsTF.setText(xWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (wins.equals("O wins!")) { //if O wins
                oWon++; //adding 1 to O's amount of wins
                String oWonString = Integer.toString(oWon); //converting to String
                oWinsTF.setText(oWonString); //displaying # of wins
                newGameBUT.setEnabled(true); //enable new game button
            if (e.getSource() == newGameBUT) {
            i++; // turn switch
        /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        private void jbInit() throws Exception {
            this.getContentPane().setLayout(null);
            this.getContentPane().setBackground(Color.darkGray);
            sqTwoBUT.setBounds(new Rectangle(2, 116, 115, 115));
            sqTwoBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFourBUT.setBounds(new Rectangle(118, 1, 115, 115));
            sqFourBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqFiveBUT.setBounds(new Rectangle(118, 116, 115, 115));
            sqFiveBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSixBUT.setBounds(new Rectangle(118, 232, 115, 115));
            sqSixBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.setBounds(new Rectangle(2, 1, 115, 115));
            sqOneBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqEightBUT.setBounds(new Rectangle(233, 116, 115, 115));
            sqEightBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqNineBUT.setBounds(new Rectangle(233, 232, 115, 115));
            sqNineBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqSevenBUT.setBounds(new Rectangle(233, 1, 115, 115));
            sqSevenBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            sqOneBUT.addActionListener(this);
            sqTwoBUT.addActionListener(this);
            sqThreeBUT.addActionListener(this);
            sqFourBUT.addActionListener(this);
            sqFiveBUT.addActionListener(this);
            sqSixBUT.addActionListener(this);
            sqSevenBUT.addActionListener(this);
            sqEightBUT.addActionListener(this);
            sqNineBUT.addActionListener(this);
            newGameBUT.addActionListener(this);
            sqThreeBUT.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setFont(new java.awt.Font(
                    "Tw Cen MT Condensed Extra Bold",
                    Font.BOLD, 20));
            turnTF.setEditable(false);
            turnTF.setText("X goes first");
            turnTF.setHorizontalAlignment(SwingConstants.CENTER);
            turnTF.setBounds(new Rectangle(2, 346, 346, 35));
            oWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            oWinsTF.setEditable(false);
            oWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsTF.setBounds(new Rectangle(256, 419, 79, 59));
            xWinsTF.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                              Font.BOLD, 18));
            xWinsTF.setEditable(false);
            xWinsTF.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsTF.setBounds(new Rectangle(12, 419, 79, 59));
            oWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            oWinsLBL.setForeground(Color.white);
            oWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            oWinsLBL.setText("O wins:");
            oWinsLBL.setBounds(new Rectangle(256, 399, 78, 21));
            xWinsLBL.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                               Font.PLAIN, 16));
            xWinsLBL.setForeground(Color.white);
            xWinsLBL.setDisplayedMnemonic('0');
            xWinsLBL.setHorizontalAlignment(SwingConstants.CENTER);
            xWinsLBL.setText("X wins:");
            xWinsLBL.setBounds(new Rectangle(12, 393, 78, 21));
            newGameBUT.setBounds(new Rectangle(101, 455, 146, 23));
            newGameBUT.setFont(new java.awt.Font("Tw Cen MT Condensed Extra Bold",
                                                 Font.BOLD, 14));
            newGameBUT.setText("New Game");
            this.getContentPane().add(sqFourBUT);
            this.getContentPane().add(sqThreeBUT);
            this.getContentPane().add(sqTwoBUT);
            this.getContentPane().add(sqOneBUT);
            this.getContentPane().add(sqFiveBUT);
            this.getContentPane().add(sqSixBUT);
            this.getContentPane().add(sqNineBUT);
            this.getContentPane().add(sqEightBUT);
            this.getContentPane().add(sqSevenBUT);
            this.getContentPane().add(turnTF);
            this.getContentPane().add(xWinsLBL);
            this.getContentPane().add(xWinsTF);
            this.getContentPane().add(oWinsLBL);
            this.getContentPane().add(oWinsTF);
            this.getContentPane().add(newGameBUT);
            sqThreeBUT.setBounds(new Rectangle(2, 232, 115, 115));
        JButton sqTwoBUT = new JButton();
        JButton sqThreeBUT = new JButton();
        JButton sqFourBUT = new JButton();
        JButton sqFiveBUT = new JButton();
        JButton sqSixBUT = new JButton();
        JButton sqOneBUT = new JButton();
        JButton sqEightBUT = new JButton();
        JButton sqNineBUT = new JButton();
        JButton sqSevenBUT = new JButton();
        JTextField turnTF = new JTextField();
        JTextField oWinsTF = new JTextField();
        JTextField xWinsTF = new JTextField();
        JLabel oWinsLBL = new JLabel();
        JLabel xWinsLBL = new JLabel();
        JButton newGameBUT = new JButton();
    }

    This code should be the poster-child for every time we tell someone that repeated code can usually be replaced with collections or method calls.
            if (e.getSource() == sqOneBUT) { //disable and print X or O to button
                sqOneBUT.setText(turn); //printing players symbol
                sqOneBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqTwoBUT) { //disable and print X or O to button
                sqTwoBUT.setText(turn); //printing players symbol
                sqTwoBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqThreeBUT) { //disable and print X or O to button
                sqThreeBUT.setText(turn); //printing players symbol
                sqThreeBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFourBUT) { //disable and print X or O to button
                sqFourBUT.setText(turn); //printing players symbol
                sqFourBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqFiveBUT) { //disable and print X or O to button
                sqFiveBUT.setText(turn); //printing players symbol
                sqFiveBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSixBUT) { //disable and print X or O to button
                sqSixBUT.setText(turn); //printing players symbol
                sqSixBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqSevenBUT) { //disable and print X or O to button
                sqSevenBUT.setText(turn); //printing players symbol
                sqSevenBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqEightBUT) { //disable and print X or O to button
                sqEightBUT.setText(turn); //printing players symbol
                sqEightBUT.setEnabled(false); //disabling button
            if (e.getSource() == sqNineBUT) { //disable and print X or O to button
                sqNineBUT.setText(turn); //printing players symbol
                sqNineBUT.setEnabled(false); //disabling button
            String sqOne = sqOneBUT.getText(); // Strings to read to find winner
            String sqTwo = sqTwoBUT.getText(); // Strings to read to find winner
            String sqThree = sqThreeBUT.getText(); // Strings to read to find winner
            String sqFour = sqFourBUT.getText(); // Strings to read to find winner
            String sqFive = sqFiveBUT.getText(); // Strings to read to find winner
            String sqSix = sqSixBUT.getText(); // Strings to read to find winner
            String sqSeven = sqSevenBUT.getText(); // Strings to read to find winner
            String sqEight = sqEightBUT.getText(); // Strings to read to find winner
            String sqNine = sqNineBUT.getText(); // Strings to read to find winner

  • Problem disabling JButton in ActionListener after setText of JLabel

    What i want is when i click View to see the label say "Viewing ..." and in the same time the btnView (View Button) to be disabled.
    I want the same with the other 2 buttons.
    My problem is in ActionListener of the button. It only half works.
    I cannot disable (setEnabled(false)) the button after it is pressed and showing the JLabel.
    The code i cannot run is the 3 buttons setEnabled (2 in comments).
    Any light?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    class BTester extends JFrame implements ActionListener { 
         JButton btnView, btnBook, btnSearch;
         BTester(){     //Constructor
              JPanel p = new JPanel();
         JButton btnView = new JButton( "View" );
         btnView.setActionCommand( "View" );
         btnView.addActionListener(this);
         JButton btnBook = new JButton( "Book" );
         btnBook.setActionCommand( "Book" );
         btnBook.addActionListener(this);
         JButton btnSearch = new JButton( "Search" );
         btnSearch.setActionCommand( "Search" );
         btnSearch.addActionListener(this);
         p.add(btnView);
         p.add(btnBook);
         p.add(btnSearch);
         getContentPane().add(show, "North"); //put text up
    getContentPane().add(p, "South"); //put panel of buttons down
    setSize(400,200);
    setVisible(true);
    setTitle("INITIAL BUTTON TESTER");
    show.setFont(new Font("Tahoma",Font.BOLD,20));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
         //actionPerformed implemented (overrided)
         public void actionPerformed( ActionEvent ae) {
    String actionName = ae.getActionCommand().trim();
    if( actionName.equals( "View" ) ) {
    show.setText("Viewing ...");
         btnView.setEnabled(false); // The line of problem
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Book" ) ) {
    show.setText("Booking ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(false);
    //btnSearch.setEnabled(true);
    else if( actionName.equals( "Search" ) ) {
    show.setText("Searching ...");
    //btnView.setEnabled(true);
    //btnBook.setEnabled(true);
    //btnSearch.setEnabled(false);
    } //end actionPerformed
         private JLabel show = new JLabel( "Press a button ... " );
    public static void main(String[] args) { 
         new BTester();
    } // End BTester class

    1. Use code formatting when posting code.
    2. You have a Null Pointer Exception since in your constructor you create the JButtons and assign them to a local variable instead of the class member.
    Change this
    JButton btnView = new JButton( "View" );to:
    btnView = new JButton( "View" );

  • Renderer problem for a JButton in a JTable

    Hi all,
    Here is my requirement -
    When the value of a particular cell in a JTable gets changed, another cell in the same selected row should display a JButton. The button should remain displayed for that row. Other rows should not have the button displayed unless there is any change in value of other columns in that row.
    I have the problem in displaying the button only when the values of a particular row is changed. The button gets displayed if I click that button cell which should not happen as the values are not changed for the corresponding row. Also, once the button is displayed for a particular row, if i click some other row, button gets disappeared for the previously selected row.
    Here is the code I have implemented. Please correct me where I am going wrong.
    Renderer code for the button-
    ==================
    class ButtonRenderer extends JButton implements TableCellRenderer {
    public ButtonRenderer() {
    setOpaque(true);
    public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column)
    if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
    } else{
    setForeground(table.getForeground());
    setBackground(UIManager.getColor("Button.background"));
    TableModel model = table.getModel();
    // get values from the table model's selected row and specific column
    if(// check if values are changed from old ones)
    setText("Undo");
    setVisible(true);
    return (JButton) value;
    else
    JButton button = new JButton("");
    button.setBackground(Color.white);
    button.setBorderPainted(false);
    button.setMargin(new Insets(0, 0, 0, 0));
    button.setEnabled(false);
    return button;
    Editor code for the button -
    =======================
    class ButtonCellEditor extends DefaultCellEditor
    public ButtonCellEditor(JButton aButton)
    super(new JTextField());
    setClickCountToStart(0);
    aButton.setOpaque(true);
    aButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    fireEditingStopped();
    editorComponent = aButton;
    protected void fireEditingStopped()
    super.fireEditingStopped();
    public Object getCellEditorValue()
    return editorComponent;
    public boolean stopCellEditing()
    return super.stopCellEditing();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
    return editorComponent;
    Code setting the renderer/editor -
    ==================================
    TableColumn column = colModel.getColumn(6);
    button.setVisible(true);
    button.setEnabled(true);
    column .setCellRenderer(new ButtonRenderer());
    column .setCellEditor(new ButtonCellEditor(button));
    Please correct me where I am going wrong.
    Thanks in advance!!

    Hope this is what you want...edit the column "Value" and type "Show" to get the desired result.
    import java.awt.Component;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.DefaultCellEditor;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.JTextField;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.DefaultTableCellRenderer;
    public class TableEdit2 extends JFrame
         Object[] columns =
         { "A", "Value", "Action" };
         Object[][] data =
         { "A0", "B0", "" },
         { "A1", "B1", "" },
         { "A2", "B2", "" },
         { "A3", "B3", "" },
         { "A4", "B4", "" },
         { "A5", "B5", "" },
         { "A6", "B6", "" },
         { "A7", "B7", "" },
         { "A8", "B8", "" },
         { "A9", "B9", "" },
         { "A10", "B10", "" },
         { "A11", "B11", "" } };
         JTable table = null;
         public TableEdit2()
              super("Table Edit");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              createGUI();
              setLocationRelativeTo(null);
              setSize(400, 300);
              setVisible(true);
         private void createGUI()
              table = new JTable(data, columns)
                   public void setValueAt(Object value, int row, int column)
                        super.setValueAt(value, row, column);
                        ((AbstractTableModel) table.getModel()).fireTableRowsUpdated(
                                  row, row);
              table.getColumn("Action").setCellRenderer(new ButtonRenderer());
              table.getColumn("Action").setCellEditor(new MyTableEditor(new JTextField()));
              JScrollPane sc = new JScrollPane(table);
              add(sc);
         class ButtonRenderer extends DefaultTableCellRenderer
              JButton undoButton = new JButton("Undo");
              public ButtonRenderer()
                   super();
              public Component getTableCellRendererComponent(JTable table,
                        Object value, boolean isSelected, boolean hasFocus, int row,
                        int column)
                   Component comp = super.getTableCellRendererComponent(table, value,
                             isSelected, hasFocus, row, column);
                   if (column == 2)// The Action Column
                        Object checkValue = table.getValueAt(row, 1);
                        if ("Show".equals(String.valueOf(checkValue)))
                             return undoButton;
                   return comp;
         class MyTableEditor extends DefaultCellEditor
              JButton undoButton = new JButton("Undo");
              public MyTableEditor(JTextField dummy)
                   super(dummy);
                   setClickCountToStart(0);
                   undoButton.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             JOptionPane.showMessageDialog(null, "Do your Action Here");
              public Component getTableCellEditorComponent(JTable table,
                        Object value, boolean isSelected, int row, int column)
                   Component comp = super.getTableCellEditorComponent(table, value, isSelected, row, column);
                   if (column == 2)// The Action Column
                        Object checkValue = table.getValueAt(row, 1);
                        if ("Show".equals(String.valueOf(checkValue)))
                             return undoButton;
                   return comp;
              public Object getCellEditorValue()
                   return "";
          * @param args
         public static void main(String[] args)
              // TODO Auto-generated method stub
              new TableEdit2();
    }

  • Spot the error!!!! float not saved in array

    I have the following class file which compiles fine and runs, but for some reason the salary is never stored into the file when saved, i am outputting store to the terminal window and everything comes up apart from salary which always says 0.0 can anybody see any errors has it is driving me mad lol!
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import bank.BankUI;
    import bank.*;
    public class CreateSequentialFile extends JFrame {
       private ObjectOutputStream output;
       private BankUI userInterface;
       private JButton enterButton, openButton;
       private Store store;
       private Employee record;
       // set up GUI
       public CreateSequentialFile()
          super( "Creating a Sequential File of Objects" ); // appears in top of gui
          // create instance of reusable user interface
          userInterface = new BankUI( 9 );  // four textfields
          getContentPane().add( userInterface, BorderLayout.CENTER );
          openButton = userInterface.getDoTask1Button();
          openButton.setText( "Save to file" );
          openButton.addActionListener(
             // anonymous inner class to handle openButton event
             new ActionListener() {
                // call openFile when button pressed
                public void actionPerformed( ActionEvent event )
                   openFile();
             } // end anonymous inner class
          ); // end call to addActionListener
          // configure button doTask2 for use in this program
          enterButton = userInterface.getDoTask2Button();
          enterButton.setText( "Save to file..." );
          enterButton.setEnabled( false );  // disable button
          // register listener to call addRecord when button pressed
          enterButton.addActionListener(
             // anonymous inner class to handle enterButton event
             new ActionListener() {
                // call addRecord when button pressed
                public void actionPerformed( ActionEvent event )
                   addRecord();
             } // end anonymous inner class
          ); // end call to addActionListener
          // register window listener to handle window closing event
          addWindowListener(
             // anonymous inner class to handle windowClosing event
             new WindowAdapter() {
                // add current record in GUI to file, then close file
                public void windowClosing( WindowEvent event )
                             if ( output != null )
                                addRecord();
                                  closeFile();
             } // end anonymous inner class
          ); // end call to addWindowListener
          setSize( 600, 500 );
          setVisible( true );
         store = new Store(100);
       } // end CreateSequentialFile constructor
       // allow user to specify file name
       private void openFile()
          // display file dialog, so user can choose file to open
          JFileChooser fileChooser = new JFileChooser();
          fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
          int result = fileChooser.showSaveDialog( this );
          // if user clicked Cancel button on dialog, return
          if ( result == JFileChooser.CANCEL_OPTION )
             return;
          File fileName = fileChooser.getSelectedFile(); // get selected file
          // display error if invalid
          if ( fileName == null || fileName.getName().equals( "" ) )
             JOptionPane.showMessageDialog( this, "Invalid File Name",
                "Invalid File Name", JOptionPane.ERROR_MESSAGE );
          else {
             // open file
             try {
                output = new ObjectOutputStream(
                   new FileOutputStream( fileName ) );
                openButton.setEnabled( false );
                enterButton.setEnabled( true );
             // process exceptions from opening file
             catch ( IOException ioException ) {
                JOptionPane.showMessageDialog( this, "Error Opening File",
                   "Error", JOptionPane.ERROR_MESSAGE );
          } // end else
       } // end method openFile
       // close file and terminate application
       private void closeFile()
          // close file
          try {
                                                 int storeSize = store.getCount();
                                            for (int i = 0; i<storeSize;i++)
                                            output.writeObject(store.elementAt(i));
             output.close();
             System.exit( 0 );
          // process exceptions from closing file
          catch( IOException ioException ) {
             JOptionPane.showMessageDialog( this, "Error closing file",
                "Error", JOptionPane.ERROR_MESSAGE );
             System.exit( 1 );
       } // end method closeFile
       // add record to file
       public void addRecord()
          int employeeNumber = 0;
          String fieldValues[] = userInterface.getFieldValues();
          // if account field value is not empty
          if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
             // output values to file
             try {
                employeeNumber = Integer.parseInt(
                   fieldValues[ BankUI.IDNUMBER ] );
                        String dob = fieldValues[ BankUI.DOB ];
                        String[] dateofBirth = dob.split ("-");
                        String sDate = fieldValues[ BankUI.START ];
                        String[] startDate = sDate.split ("-");
                        String sex = fieldValues[ BankUI.GENDER ];
                        char gender = (sex.charAt(0));
    if ( employeeNumber >= 0 ) {
                    record  = new Employee(
                    fieldValues[ BankUI.NAME ],
                        gender,
                    new Date(     Integer.parseInt(dateofBirth[0]),
                              Integer.parseInt(dateofBirth[1]),
                              Integer.parseInt(dateofBirth[2])),
                        fieldValues[ BankUI.ADDRESS ],
                        fieldValues[ BankUI.NATINTNO ],
                        fieldValues[ BankUI.PHONE ],
                        fieldValues[ BankUI.IDNUMBER ],
              new Date(     Integer.parseInt(startDate[0]),
                              Integer.parseInt(startDate[1]),
                              Integer.parseInt(startDate[2])),
              Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
                        if (!store.isFull())
                             store.add(record);
                        else
                        JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
                         "anymore employees. \nPlease Save Current File and Create a New File." );
                             System.out.println("Store full");
                        store.displayAll();
                        System.out.println("Count is " + store.getCount());
                                  // output record and flush buffer
                        //should be written to fuile in the close file method.
                                                 output.flush();
                else
                    JOptionPane.showMessageDialog( this,
                       "Account number must be greater than 0",
                       "Bad account number", JOptionPane.ERROR_MESSAGE );
                // clear textfields
                userInterface.clearFields();
             } // end try
             // process invalid account number or balance format
             catch ( NumberFormatException formatException ) {
                JOptionPane.showMessageDialog( this,
                   "Bad ID number, Date or Salary", "Invalid Number Format",
                   JOptionPane.ERROR_MESSAGE );
             // process exceptions from file output
             catch ( ArrayIndexOutOfBoundsException ArrayException ) {
                 JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                      // process exceptions from file output
             catch ( IOException ioException ) {
                 JOptionPane.showMessageDialog( this, "Error writing to file",
                    "IO Exception", JOptionPane.ERROR_MESSAGE );
                closeFile();
          } // end if
       } // end method addRecord
       public static void main( String args[] )
          new CreateSequentialFile();
    } // end class CreateSequentialFile

    I don't see any salary-related code in what you posted. Is there salary information in that Employee class or something? If so you should look there to see if it's working correctly. Or better still, test the Employee class properly before allowing other classes to use it.

  • Method trouble

    Hello,
    I have a problem with the following code. When I call the place_info_table method and pass it the 2d array information, the values in the array get lost. Can anyoe please help me ?
    Thanks
    Michael
    place_info_table(information);
    public void place_info_table(String information[][])
    System.out.println("Information in place method is "+information[0][0]);
    if(!(information.length > 1))
    JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
    client_open.setEnabled(false);
    client_refresh.setEnabled(false); //all buttons except refresh are disabled.
    client_search.setEnabled(false);
    client_view_files.setEnabled(false);
    client_quit.setEnabled(true);
    else
    client_open.setEnabled(true);
    client_refresh.setEnabled(true);
    client_search.setEnabled(true);
    client_view_files.setEnabled(false); //else all the buttons except view files are enabled
    client_quit.setEnabled(true);
    int j=0;
    for(int i=0;i<information.length;i++)
    client_listing.setValueAt(information[0],j,0);
    // client_listing.add
    j++;
    client_quit.setEnabled(true);
    client_refresh.setEnabled(true);
    //System.out.println("test1 "+information[i][0]);
    System.out.println("information at 0,0 "+information[i][0]);
    client_open.addActionListener(this);
    client_refresh.addActionListener(this);
    client_search.addActionListener(this);
    client_view_files.addActionListener(this);
    client_quit.addActionListener(this);

    What do you mean with the data gets lost?
    void foo(String[][] blarg) {
        for (int a=0; a < blarg.length; a++) {
            for (int b=0; b < blarg[a].length; b++) {
                System.out.println(blarg[a]);
    void test() {
    String[][] bar = new String[][] {
    {"a","b","c"},
    {"1","2","3"},
    {"+","-",";"},
    foo(bar);
    Works well for me.
    What's the problem?

  • JTable Trouble

    I have trouble with the following code. This method could place the data it receives in information onto a JTable but it does not work. The code compiles perfect and the values that information has are correct. I have commented the lines where the data is actually put onto the table. Its about two thirds way down. I would appreciate any help.
    Thanks
    Michael
    public void place_info_table(String information[][])
    if(!(information.length > 1))
    JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
    client_open.setEnabled(false);
    client_refresh.setEnabled(false); //all buttons except refresh are disabled.
    client_search.setEnabled(false);
    client_view_files.setEnabled(false);
    client_quit.setEnabled(true);
    else
    client_open.setEnabled(true);
    client_refresh.setEnabled(true);
    client_search.setEnabled(true);
    client_view_files.setEnabled(false); //else all the buttons except view files are enabled
    client_quit.setEnabled(true);
    int j=0;
    for(int i=0;i<information.length;i++) // Here is where the info is added
    client_listing.setValueAt(information[0],j,0);
    j++;
    client_quit.setEnabled(true);
    client_refresh.setEnabled(true);
    System.out.println(information[i][0]);
    client_open.addActionListener(this);
    client_refresh.addActionListener(this);
    client_search.addActionListener(this);
    client_view_files.addActionListener(this);
    client_quit.addActionListener(this);

    I have trouble with the following code. This method could place the data it receives in information onto a JTable but it does not work. The code compiles perfect and the values that information has are correct. I have commented the lines where the data is actually put onto the table. Its about two thirds way down. I would appreciate any help.
    Thanks
    Michael
    public void place_info_table(String information[][])
    if(!(information.length > 1))
    JOptionPane.showMessageDialog(this,"Sorry, there is no server at present to satisfy your request. ","Peer 2 Peer Client",JOptionPane.ERROR_MESSAGE);
    client_open.setEnabled(false);
    client_refresh.setEnabled(false); //all buttons except refresh are disabled.
    client_search.setEnabled(false);
    client_view_files.setEnabled(false);
    client_quit.setEnabled(true);
    else
    client_open.setEnabled(true);
    client_refresh.setEnabled(true);
    client_search.setEnabled(true);
    client_view_files.setEnabled(false); //else all the buttons except view files are enabled
    client_quit.setEnabled(true);
    int j=0;
    for(int i=0;i<information.length;i++) // Here is where the info is added
    client_listing.setValueAt(information[0],j,0);
    j++;
    client_quit.setEnabled(true);
    client_refresh.setEnabled(true);
    System.out.println(information[i][0]);
    client_open.addActionListener(this);
    client_refresh.addActionListener(this);
    client_search.addActionListener(this);
    client_view_files.addActionListener(this);
    client_quit.addActionListener(this);

  • JButton that enables a JComponent

    Hi all. For my application i would like a button that, when clicked, enables a text field otherwise disabled. i thought it would be easy to do with a mouseListener on the button that, when intercepts an event from BUTTON1, would simply call the setEnabled on the button:
    edit.addMouseListener(new MouseAdapter() {
                        public void mouseClicked(MouseEvent e) {
                            if (e.getButton () == e.BUTTON1)
                                comp1.setEnabled(true);
                    });but i have a "local variable comp1 is accessed from within inner class; needs to be declared final" and, i think, i can't declare it final because if i do, the setEnabled wouldn't have effect. What am i doing wrong?
    thank you all!

    i did my tests, and your right. i have a really nasty bug on my code, then.. i'll make you simplier that i can:
    since (i think) that the important one is the state of the component in the moment it's attached to the panel.. how can i make the trick??

  • Trying to make the checklist add up

    I am designing a prototype of a learning style which has 12 question and 5 checkboxs and a user will only need to check two out the 5 checkboxs, and then it add up the results of how many A, B, C, D or E's that was checked i dont know how i'm goin to that here is a piece of code i wrote can you please help me thankx.
    pls take a look at this code run it and i'll tell you what it's suppose to do.. import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputEvent;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.swing.JFileChooser;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.KeyStroke;
    public class CheckPanel extends Applet{
    CheckboxPanel panel1, panel2, panel3, panel4;
    ItemListener iListener;
    boolean state;
    /*protected JFileChooser m_chooser;
    //protected File m_currentFile;
    //JMenuBar menuBar = createMenuBar();
    //void JMenuBar(menuBar);
    //m_chooser = new JFileChooser();
    //try {
    File dir = (new File (".")).getCanonicalFile();
    m_chooser.setCurrentDirectory(dir);
    } catch (IOException ex){}
    updateEditor();
    newDocument();
    WindowListener wndCloser = new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    if (!promptToSave())
    return;
    System.exit(0);
    addWindowListener(wndCloser);
    protected JMenuBar createMenuBar(){
    final JMenuBar menuBar = new JMenuBar();
    JMenu mFile = new JMenu("File");
    mFile.setMnemonic('f');
    JMenuItem item = new JMenuItem("New");
    item.setMnemonic('n');
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
    ActionListener lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    boolean promptToSave;
    if (!promptToSave);
    return;
    newDocument();
    private void newDocument() {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    item = new JMenuItem("Open...");
    item.setMnemonic('o');
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
    lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    boolean promptToSave;
    if (!promptToSave);
    return;
    openDocument();
    private void openDocument() {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    item = new JMenuItem("Save");
    item.setMnemonic('s');
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
    lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    boolean m_textChanged;
    if (!m_textChanged)
    return ;
    saveFile(false);
    private void saveFile(boolean b) {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    item = new JMenuItem("Save As..");
    item.setMnemonic('a');
    lst = new ActionListener(){
    public void actionperformed(ActionEvent e){
    saveFile(true);
    private void saveFile(boolean b) {
    // TODO Auto-generated method stub
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    mFile.addSeparator();
    item = new JMenuItem("Exit");
    item.setMnemonic('x');
    lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    System.exit(0);
    item.addActionListener(lst);
    mFile.add(item);
    menuBar.add(mFile);
    return menuBar;
    //isSelected = new Checkbox();
    public void init(){
    setLayout(new BorderLayout());
    setBounds (20, 30, 300, 180);
    Panel headerPanel = new Panel();
    headerPanel.setLayout(new GridLayout(2,1));
    Label lblHeader = new Label("QUIZ 02 Learning Style");
    headerPanel.add(lblHeader);
    lblHeader = new Label("This quiz..");
    Label lblHeader1 = new Label("Please tick two checkboxes for each question...");
    headerPanel.add(lblHeader1);
    //lblHeader1 = new Label();
    headerPanel.add(lblHeader);
    add(headerPanel, BorderLayout.NORTH);
    //setLayout(new GridLayout(3,1));
    panel1 =new CheckboxPanel();
    add(panel1, BorderLayout.CENTER);
    panel2 = new CheckboxPanel();
    add(panel2);
    panel3 =new CheckboxPanel();
    add(panel3);
    panel4 =new CheckboxPanel();
    add(panel4);
    public static final long serialVersionUID = 1L;
    Checkbox check1, check2, check3, check4, check5;
    void CheckboxPanel(){
    setLayout(new GridLayout(4,1));
    setBackground(Color.gray);
    check1 = new Checkbox("1");
    add(check1);
    //isSelected = new Checkbox();
    check1.addItemListener((ItemListener) this);
    getContentPane().add(check1);// set checked state of box
    check2 = new Checkbox("2");
    add(check2);
    check2.addItemListener((ItemListener) this);
    getContentPane().add(check2);
    check3 = new Checkbox("3");
    add(check3);
    check3.addItemListener((ItemListener) this);
    getContentPane().add(check3);
    check4 = new Checkbox("4");
    add(check4);
    check4.addItemListener((ItemListener) this);
    getContentPane().add(check4);
    //check5 = new Checkbox("5");
    //add(check5);
    public void itemStateChanged(ItemEvent e) {
    int index = 0;
    char a = '-';
    Object source = e.getItemSelectable();
    if (source == check1) {
    index = 0;
    a = 'a';
    } else if (source == check2) {
    index = 1;
    a = 'b';
    } else if (source == check3) {
    index = 2;
    a = 'c';
    } else if (source == check4) {
    index = 3;
    a = 'd';
    if (e.getStateChange() == ItemEvent.DESELECTED) {
    a = '-';
    //choices.setCharAt(index, a);
    //System.out.println("hello");
    private File newFile(String data) throws IOException {
    // TODO Auto-generated method stub
    File newfile = newFile("I:\\ouput.txt");
    System.out.println("DATA? - " + data);
    FileOutputStream fos = new FileOutputStream(newfile);
    fos.write(data.getBytes());
    fos.close();
    JOptionPane.showMessageDialog(null, "Save File");
    return null;
    private Container getContentPane() {
    // TODO Auto-generated method stub
    return null;
    import java.awt.*;
    //import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentListener;
    //import java.awt.event.InputEvent;
    import java.awt.event.ItemListener;
    //import java.awt.event.KeyEvent;
    //import java.io.File;
    //import java.lang.reflect.Array;
    import javax.swing.JButton;
    //import javax.swing.JDialog;
    import javax.swing.JMenuBar;
    //import javax.swing.*;
    //import javax.swing.event.*;
    //import javax.swing.JToggleButton;
    public class CheckboxPanel extends Panel{
    ItemListener iListener;
    boolean state;
    Button button1;
    // public static Object newInstance(Class componentType,
    //int length){
    public static final long serialVersionUID = 1L;
    //public static final char k = 0;
    Checkbox[] check = new Checkbox[61];
    //Checkbox check1, check2, check3, check4, check5 , check6 ,check7 ,check8 ,check9 ,check10 ,check11 ,check12 ,check13 ,
    //check14 ,check15 ,check16 ,check17 ,check18 ,check19 ,check20 ,check21 ,check22 ,check23 ,check24 ,check25 ,check26 ,
    //check27 ,check28 ,check29 ,check30 ,check31 ,check32 ,check33 ,check34 ,check35 ,check36 ,check37 ,check38 ,check39 ,
    //check40 ,check41 ,check42 ,check43 ,check44 ,check45 ,check46 ,check47 ,check48 ,check49 ,check50 ,check51 ,check52 ,
    //check53 ,check54 ,check55 ,check56 ,check57 ,check58 ,check59 ,check60,
    //isSelected = new Checkbox();
    protected int group1,group2,group3,group4,group5,group6,group7,group8,group9,group10,group11,group12,group13,group14,group15;
    //int[] CheckBox = {k};
    //Array.newInstance(private Checkbox check6;
    // state of checkbox
    CheckboxPanel(){
    setLayout(new GridLayout(4,4));
    setBackground(Color.gray);
    /* Question 1 layout panel */
    // Create a panel for the question and answers
    Panel question1Panel = new Panel();
    question1Panel.setLayout(new GridLayout(1, 2));
    // Create a label for the question number
    Label lbl = new Label("1");
    // Add it to the question panel so it appears on the right
    question1Panel.add(lbl);
    // Add a panel for the answers to the question
    Panel answer1Panel = new Panel();
    // Use a grid layout of 4 rows by 1 column
    answer1Panel.setLayout(new GridLayout(4,1));
    //CheckBox.addActionListener(new ActionListener(){
    //public void actionPerformed(ActionEvent ae)
    // System.out.println("check box state"+check.getState());
    check[1] = new Checkbox("A. Imaginative");
    answer1Panel.add(check[1]);
    //check1.addItemListener(iListener);
    //state = check1.isSeleted() ; // tells whether box is checked
    //check1.setSelected(state);
    //getContentPane().add(check1);// set checked state of box
    check[2] = new Checkbox("B. Investigative");
    answer1Panel.add(check[2]);
    //check1.addItemListener(iListener);
    //state = check1.isSeleted() ; // tells whether box is checked
    //check1.setSelected(state);
    //getContentPane().add(check1);// set checked state of box
    check[3] = new Checkbox("C. Realistic");
    answer1Panel.add(check[3]);
    check[4] = new Checkbox("D. Analytical");
    answer1Panel.add(check[4]);
    question1Panel.add(answer1Panel);
    add(question1Panel);
    /* Question 2 layout panel */
    Panel question2Panel = new Panel();
    question2Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("2");
    question2Panel.add(lbl);
    Panel answer2Panel = new Panel();
    answer2Panel.setLayout(new GridLayout(4,1));
    check[5] = new Checkbox("A. Organized");
    answer2Panel.add(check[5]);
    check[6]= new Checkbox("B. Adaptable");
    answer2Panel.add(check[6]);
    check[7] = new Checkbox("C. Critical");
    answer2Panel.add(check[7]);
    check[8] = new Checkbox("D. Inquisitive");
    answer2Panel.add(check[8]);
    question2Panel.add(answer2Panel);
    add(question2Panel);
    /* Question 3 layout panel*/
    Panel question3Panel= new Panel();
    question3Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("3");
    question3Panel.add(lbl);
    Panel answer3Panel = new Panel();
    answer3Panel.setLayout(new GridLayout(4,1));
    check[9] = new Checkbox("A. Debating");
    answer3Panel.add(check[9]);
    check[10] = new Checkbox("B.Getting to the point");
    answer3Panel.add(check[10]);
    check[11] = new Checkbox("C. Creating");
    answer3Panel.add(check[11]);
    check[12] = new Checkbox("D. Relating");
    answer3Panel.add(check[12]);
    question3Panel.add(answer3Panel);
    add(question3Panel);
    /* Question 4 layout panel*/
    Panel question4Panel= new Panel();
    question4Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("4");
    question4Panel.add(lbl);
    Panel answer4Panel = new Panel();
    answer4Panel.setLayout(new GridLayout(4,1));
    check[13] = new Checkbox("A. Personal");
    answer4Panel.add(check[13]);
    check[14] = new Checkbox("B. Practical");
    answer4Panel.add(check[14]);
    check[15] = new Checkbox("C. Academic");
    answer4Panel.add(check[15]);
    check[16] = new Checkbox("D. Adventurous");
    answer4Panel.add(check[16]);
    question4Panel.add(answer4Panel);
    add(question4Panel);
    /* Question 5 layout panel*/
    Panel question5Panel= new Panel();
    question5Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("5");
    question5Panel.add(lbl);
    Panel answer5Panel = new Panel();
    answer5Panel.setLayout(new GridLayout(4,1));
    check[17] = new Checkbox("A. Presice");
    answer5Panel.add(check[17]);
    check[18 ]= new Checkbox("B. Flexible");
    answer5Panel.add(check[18]);
    check[19] = new Checkbox("C. Systematic");
    answer5Panel.add(check[19]);
    check[20] = new Checkbox("D. Inventive");
    answer5Panel.add(check[20]);
    question5Panel.add(answer5Panel);
    add(question5Panel);
    /* Question 6 layout panel*/
    Panel question6Panel= new Panel();
    question6Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("6");
    question6Panel.add(lbl);
    Panel answer6Panel = new Panel();
    answer6Panel.setLayout(new GridLayout(4,1));
    check[21] = new Checkbox("A. Sharing");
    answer6Panel.add(check[21]);
    check[22]= new Checkbox("B. Orderly");
    answer6Panel.add(check[22]);
    check[23] = new Checkbox("C. Sensible");
    answer6Panel.add(check[23]);
    check[24] = new Checkbox("D. Independent");
    answer6Panel.add(check[24]);
    question6Panel.add(answer6Panel);
    add(question6Panel);
    /* Question 7 layout panel*/
    Panel question7Panel= new Panel();
    question7Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("7");
    question7Panel.add(lbl);
    Panel answer7Panel = new Panel();
    answer7Panel.setLayout(new GridLayout(4,1));
    check[25] = new Checkbox("A. Competitive");
    answer7Panel.add(check[25]);
    check[26] = new Checkbox("B. Perfectionist");
    answer7Panel.add(check[26]);
    check[27] = new Checkbox("C. Cooperative");
    answer7Panel.add(check[27]);
    check[28] = new Checkbox("D. Logical");
    answer7Panel.add(check[28]);
    question7Panel.add(answer7Panel);
    add(question7Panel);
    /* Question 8 layout panel*/
    Panel question8Panel= new Panel();
    question8Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("8");
    question8Panel.add(lbl);
    Panel answer8Panel = new Panel();
    answer8Panel.setLayout(new GridLayout(4,1));
    check[29] = new Checkbox("A. Intellectual");
    answer8Panel.add(check[29]);
    check[30] = new Checkbox("B. Sensitive");
    answer8Panel.add(check[30]);
    check[31] = new Checkbox("C. Hard-working");
    answer8Panel.add(check[31]);
    check[32] = new Checkbox("D. Risk-taking");
    answer8Panel.add(check[32]);
    question8Panel.add(answer8Panel);
    add(question8Panel);
    /* Question 9 layout panel*/
    Panel question9Panel= new Panel();
    question9Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("9");
    question9Panel.add(lbl);
    Panel answer9Panel = new Panel();
    answer9Panel.setLayout(new GridLayout(4,1));
    check[33] = new Checkbox("A. Reader");
    answer9Panel.add(check[33]);
    check[34] = new Checkbox("B. People person");
    answer9Panel.add(check[34]);
    check[35] = new Checkbox("C. Problem solver");
    answer9Panel.add(check[35]);
    check[36] = new Checkbox("D. Planner");
    answer9Panel.add(check[36]);
    question9Panel.add(answer9Panel);
    add(question9Panel);
    /* Question 10 layout panel*/
    Panel question10Panel= new Panel();
    question10Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("10");
    question10Panel.add(lbl);
    Panel answer10Panel = new Panel();
    answer10Panel.setLayout(new GridLayout(4,1));
    check[37] = new Checkbox("A. Memorize");
    answer10Panel.add(check[37]);
    check[38] = new Checkbox("B. Associate");
    answer10Panel.add(check[38]);
    check[39] = new Checkbox("C. Think-through");
    answer10Panel.add(check[39]);
    check[40] = new Checkbox("D. Originate");
    answer10Panel.add(check[40]);
    question10Panel.add(answer10Panel);
    add(question10Panel);
    /* Question 11 layout panel*/
    Panel question11Panel= new Panel();
    question11Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("11");
    question11Panel.add(lbl);
    Panel answer11Panel = new Panel();
    answer11Panel.setLayout(new GridLayout(4,1));
    check[41] = new Checkbox("A. Changer");
    answer11Panel.add(check[41]);
    check[42] = new Checkbox("B. Judger");
    answer11Panel.add(check[42]);
    check[43] = new Checkbox("C. Spontaneous");
    answer11Panel.add(check[43]);
    check[44] = new Checkbox("D. Wants direction");
    answer11Panel.add(check[44]);
    question11Panel.add(answer11Panel);
    add(question11Panel);
    /* Question 12 layout panel*/
    Panel question12Panel= new Panel();
    question12Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("12");
    question12Panel.add(lbl);
    Panel answer12Panel = new Panel();
    answer12Panel.setLayout(new GridLayout(4,1));
    check[45] = new Checkbox("A. Communicating");
    answer12Panel.add(check[45]);
    check[46] = new Checkbox("B. Discovering");
    answer12Panel.add(check[46]);
    check[47] = new Checkbox("C. Caring");
    answer12Panel.add(check[47]);
    check[48] = new Checkbox("D. Examining");
    answer12Panel.add(check[48]);
    question12Panel.add(answer12Panel);
    add(question12Panel);
    /* Question 13 layout panel*/
    Panel question13Panel= new Panel();
    question13Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("13");
    question13Panel.add(lbl);
    Panel answer13Panel = new Panel();
    answer13Panel.setLayout(new GridLayout(4,1));
    check[49] = new Checkbox("A. Challenging");
    answer13Panel.add(check[49]);
    check[50] = new Checkbox("B. Practicing");
    answer13Panel.add(check[50]);
    check[51] = new Checkbox("C. Caring");
    answer13Panel.add(check[51]);
    check[52] = new Checkbox("D. Examining");
    answer13Panel.add(check[52]);
    question13Panel.add(answer13Panel);
    add(question13Panel);
    /* Question 14 layout panel*/
    Panel question14Panel= new Panel();
    question13Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("14 ");
    question14Panel.add(lbl);
    Panel answer14Panel = new Panel();
    answer14Panel.setLayout(new GridLayout(4,1));
    check[53] = new Checkbox("A. Completing work");
    answer14Panel.add(check[53]);
    check[54] = new Checkbox("B. Seeing possibilities");
    answer14Panel.add(check[54]);
    check[55] = new Checkbox("C. Gaining ideas");
    answer14Panel.add(check[55]);
    check[56] = new Checkbox("D. Interpreting");
    answer14Panel.add(check[56]);
    question14Panel.add(answer14Panel);
    add(question14Panel);
    /* Question 15 layout panel*/
    Panel question15Panel= new Panel();
    question15Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("15");
    question15Panel.add(lbl);
    Panel answer15Panel = new Panel();
    answer15Panel.setLayout(new GridLayout(4,1));
    check[57] = new Checkbox("A. Doing");
    answer15Panel.add(check[57]);
    check[58] = new Checkbox("B. Feeling");
    answer15Panel.add(check[58]);
    check[59] = new Checkbox("C. Thinking");
    answer15Panel.add(check[59]);
    check[60] = new Checkbox("D. Experimenting");
    answer15Panel.add(check[60]);
    question15Panel.add(answer15Panel);
    add(question15Panel);
    /*class ToggleButton extends JFrame{
    public ToggleButton(){
    super("ToggleButton");
    getContentPane().setLayout(new FlowLayout());
    ButtonGroup buttonGroup =new ButtonGroup();
    char ch = (char) ('1'+ k);
    for (int k=0; k<4; k++){
    JToggleButton button = new JToggleButton("Button"+ch, k==0);
    button.setMnemonic(ch);
    button.setEnabled(k<3);
    button.setToolTipText("This is button"+ ch);
    getContentPane().add(button);
    buttonGroup.add(button);
    //pack();
    JButton button1 = new JButton("SUBMIT");
    //Object BOX_TITLE;
    //JDialog dialog = Panel.createDialog(Dialog.this, BOX_TITLE);
    //dialog.show();
    add(button1);
    addComponentListener((ComponentListener) iListener);
    ActionListener al = new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    if (check[1].getState()== true){
    group1 = group1 +1;
    if (check[2].getState()== true){
    group1 = group1 +1;
    if (check[3].getState()== true){
    group1 = group1 +1;
    if (check[4].getState()== true){
    group1 = group1 +1;
    if (check[5].getState()== true){
    group2 = group2 +1;
    if (check[6].getState()== true){
    group2 = group2 +1;
    if (check[7].getState()== true){
    group2 = group2 +1;
    if (check[8].getState()== true){
    group2 = group2 +1;
    if (check[9].getState()== true){
    group3 = group3 +1;
    if (check[10].getState()== true){
    group3 = group3 +1;
    if (check[11].getState()== true){
    group3 = group3 +1;
    if (check[12].getState()== true){
    group3 = group3 +1;
    if (check[13].getState()== true){
    group4 = group4 +1;
    if (check[14].getState()== true){
    group4 = group4 +1;
    if (check[15].getState()== true){
    group4 = group4 +1;
    if (check[16].getState()== true){
    group4 = group4 +1;
    if (check[17].getState()== true){
    group5 = group5 +1;
    if (check[18].getState()== true){
    group5 = group5 +1;
    if (check[19].getState()== true){
    group5 = group5 +1;
    if (check[20].getState()== true){
    group5 = group5 +1;
    if (check[21].getState()== true){
    group6 = group6 +1;
    if (check[22].getState()== true){
    group6 = group6 +1;
    if (check[23].getState()== true){
    group6 = group6 +1;
    if (check[24].getState()== true){
    group6 = group6 +1;
    if (check[25].getState()== true){
    group7 = group7 +1;
    if (check[26].getState()== true){
    group7 = group7 +1;
    if (check[27].getState()== true){
    group7 = group7 +1;
    if (check[28].getState()== true){
    group7 = group7 +1;
    if (check[29].getState()== true){
    group8 = group8 +1;
    if (check[30].getState()== true){
    group8 = group8 +1;
    if (check[31].getState()== true){
    group8 = group8 +1;
    if (check[32].getState()== true){
    group8 = group8 +1;
    if (check[33].getState()== true){
    group9 = group9 +1;
    if (check[34].getState()== true){
    group9 = group9 +1;
    if (check[35].getState()== true){
    group9 = group9 +1;
    if (check[36].getState()== true){
    group9 = group9 +1;
    if (check[37].getState()== true){
    group10 = group10 +1;
    if (check[38].getState()== true){
    group10 = group10 +1;
    if (check[39].getState()== true){
    group10 = group10 +1;
    if (check[40].getState()== true){
    group10 = group10 +1;
    if (check[41].getState()== true){
    group11 = group11 +1;
    if (check[42].getState()== true){
    group11 = group11 +1;
    if (check[43].getState()== true){
    group11 = group11 +1;
    if (check[44].getState()== true){
    group11 = group11 +1;
    if (check[45].getState()== true){
    group12 = group12 +1;
    if (check[46].getState()== true){
    group12 = group12 +1;
    if (check[47].getState()== true){
    group12 = group12 +1;
    if (check[48].getState()== true){
    group12 = group12 +1;
    if (check[49].getState()== true){
    group13 = group13 +1;
    if (check[50].getState()== true){
    group13 = group13 +1;
    if (check[51].getState()== true){
    group13 = group13 +1;
    if (check[52].getState()== true){
    group13 = group13 +1;
    if (check[53].getState()== true){
    group14 = group14 +1;
    if (check[54].getState()== true){
    group14 = group14 +1;
    if (check[55].getState()== true){
    group14 = group14 +1;
    if (check[56].getState()== true){
    group14 = group14 +1;
    if (check[57].getState()== true){
    group15 = group15 +1;
    if (check[58].getState()== true){
    group15 = group15 +1;
    if (check[59].getState()== true){
    group15 = group15 +1;
    if (check[60].getState()== true){
    group15 = group15 +1;
    System.out.println(check[1].getState());
    System.out.println(check[2].getState());
    System.out.println(check[3].getState());
    System.out.println(check[4].getState());
    System.out.println(check[5].getState());
    System.out.println(check[6].getState());
    System.out.println(check[7].getState());
    System.out.println(check[8].getState());
    System.out.println(check[9].getState());
    System.out.println(check[10].getState());
    System.out.println(check[11].getState());
    System.out.println(check[12].getState());
    System.out.println(check[13].getState());
    System.out.println(check[14].getState());
    System.out.println(check[15].getState());
    System.out.println(check[16].getState());
    System.out.println(check[17].getState());
    System.out.println(check[18].getState());
    System.out.println(check[19].getState());
    System.out.println(check[20].getState());
    System.out.println(check[21].getState());
    System.out.println(check[22].getState());
    System.out.println(check[23].getState());
    System.out.println(check[24].getState());
    System.out.println(check[25].getState());
    System.out.println(check[26].getState());
    System.out.println(check[27].getState());
    System.out.println(check[28].getState());
    System.out.println(check[29].getState());
    System.out.println(check[30].getState());
    System.out.println(check[31].getState());
    System.out.println(check[32].getState());
    System.out.println(check[33].getState());
    System.out.println(check[34].getState());
    System.out.println(check[35].getState());
    System.out.println(check[36].getState());
    System.out.println(check[37].getState());
    System.out.println(check[38].getState());
    System.out.println(check[39].getState());
    System.out.println(check[40].getState());
    System.out.println(check[41].getState());
    System.out.println(check[42].getState());
    System.out.println(check[43].getState());
    System.out.println(check[44].getState());
    System.out.println(check[45].getState());
    System.out.println(check[46].getState());
    System.out.println(check[47].getState());
    System.out.println(check[48].getState());
    System.out.println(check[49].getState());
    System.out.println(check[50].getState());
    System.out.println(check[51].getState());
    System.out.println(check[52].getState());
    System.out.println(check[53].getState());
    System.out.println(check[54].getState());
    System.out.println(check[55].getState());
    System.out.println(check[56].getState());
    System.out.println(check[57].getState());
    System.out.println(check[58].getState());
    System.out.println(check[59].getState());
    System.out.println(check[60].getState());
    button1.addActionListener(al);
    private JMenuBar createMenuBar() {
    // TODO Auto-generated method stub
    return null;
    //button1.addActionListener(al);
    }

    am designing a prototype of a learning style which has 12 question and 5 checkboxs and a user will only need to check two out the 5 checkboxs, and then it add up the results of how many A, B, C, D or E's that was checked i dont know how i'm goin to that here is a piece of code i wrote can you please help me thankx. pls take a look at this code run it and i'll tell you what it's suppose to do..
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.InputEvent;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import javax.swing.JFileChooser;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.KeyStroke;
    public class CheckPanel extends Applet{
    CheckboxPanel panel1, panel2, panel3, panel4;
    ItemListener iListener;
    boolean state;
    /*protected JFileChooser m_chooser;
    //protected File m_currentFile;
    //JMenuBar menuBar = createMenuBar();
    //void JMenuBar(menuBar);
    //m_chooser = new JFileChooser();
    //try {
    File dir = (new File (".")).getCanonicalFile();
    m_chooser.setCurrentDirectory(dir);
    } catch (IOException ex){}
    updateEditor();
    newDocument();
    WindowListener wndCloser = new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    if (!promptToSave())
    return;
    System.exit(0);
    addWindowListener(wndCloser);
    protected JMenuBar createMenuBar(){
    final JMenuBar menuBar = new JMenuBar();
    JMenu mFile = new JMenu("File");
    mFile.setMnemonic('f');
    JMenuItem item = new JMenuItem("New");
    item.setMnemonic('n');
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_MASK));
    ActionListener lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    boolean promptToSave;
    if (!promptToSave);
    return;
    newDocument();
    private void newDocument() {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    item = new JMenuItem("Open...");
    item.setMnemonic('o');
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, InputEvent.CTRL_MASK));
    lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    boolean promptToSave;
    if (!promptToSave);
    return;
    openDocument();
    private void openDocument() {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    item = new JMenuItem("Save");
    item.setMnemonic('s');
    item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
    lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    boolean m_textChanged;
    if (!m_textChanged)
    return ;
    saveFile(false);
    private void saveFile(boolean b) {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    item = new JMenuItem("Save As..");
    item.setMnemonic('a');
    lst = new ActionListener(){
    public void actionperformed(ActionEvent e){
    saveFile(true);
    private void saveFile(boolean b) {
    // TODO Auto-generated method stub
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    item.addActionListener(lst);
    mFile.add(item);
    mFile.addSeparator();
    item = new JMenuItem("Exit");
    item.setMnemonic('x');
    lst = new ActionListener(){
    public void actionPerformed(ActionEvent e){
    System.exit(0);
    item.addActionListener(lst);
    mFile.add(item);
    menuBar.add(mFile);
    return menuBar;
    //isSelected = new Checkbox();
    public void init(){
    setLayout(new BorderLayout());
    setBounds (20, 30, 300, 180);
    Panel headerPanel = new Panel();
    headerPanel.setLayout(new GridLayout(2,1));
    Label lblHeader = new Label("QUIZ 02 Learning Style");
    headerPanel.add(lblHeader);
    lblHeader = new Label("This quiz..");
    Label lblHeader1 = new Label("Please tick two checkboxes for each question...");
    headerPanel.add(lblHeader1);
    //lblHeader1 = new Label();
    headerPanel.add(lblHeader);
    add(headerPanel, BorderLayout.NORTH);
    //setLayout(new GridLayout(3,1));
    panel1 =new CheckboxPanel();
    add(panel1, BorderLayout.CENTER);
    panel2 = new CheckboxPanel();
    add(panel2);
    panel3 =new CheckboxPanel();
    add(panel3);
    panel4 =new CheckboxPanel();
    add(panel4);
    public static final long serialVersionUID = 1L;
    Checkbox check1, check2, check3, check4, check5;
    void CheckboxPanel(){
    setLayout(new GridLayout(4,1));
    setBackground(Color.gray);
    check1 = new Checkbox("1");
    add(check1);
    //isSelected = new Checkbox();
    check1.addItemListener((ItemListener) this);
    getContentPane().add(check1);// set checked state of box
    check2 = new Checkbox("2");
    add(check2);
    check2.addItemListener((ItemListener) this);
    getContentPane().add(check2);
    check3 = new Checkbox("3");
    add(check3);
    check3.addItemListener((ItemListener) this);
    getContentPane().add(check3);
    check4 = new Checkbox("4");
    add(check4);
    check4.addItemListener((ItemListener) this);
    getContentPane().add(check4);
    //check5 = new Checkbox("5");
    //add(check5);
    public void itemStateChanged(ItemEvent e) {
    int index = 0;
    char a = '-';
    Object source = e.getItemSelectable();
    if (source == check1) {
    index = 0;
    a = 'a';
    } else if (source == check2) {
    index = 1;
    a = 'b';
    } else if (source == check3) {
    index = 2;
    a = 'c';
    } else if (source == check4) {
    index = 3;
    a = 'd';
    if (e.getStateChange() == ItemEvent.DESELECTED) {
    a = '-';
    //choices.setCharAt(index, a);
    //System.out.println("hello");
    private File newFile(String data) throws IOException {
    // TODO Auto-generated method stub
    File newfile = newFile("I:\\ouput.txt");
    System.out.println("DATA? - " + data);
    FileOutputStream fos = new FileOutputStream(newfile);
    fos.write(data.getBytes());
    fos.close();
    JOptionPane.showMessageDialog(null, "Save File");
    return null;
    private Container getContentPane() {
    // TODO Auto-generated method stub
    return null;
    import java.awt.*;
    //import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ComponentListener;
    //import java.awt.event.InputEvent;
    import java.awt.event.ItemListener;
    //import java.awt.event.KeyEvent;
    //import java.io.File;
    //import java.lang.reflect.Array;
    import javax.swing.JButton;
    //import javax.swing.JDialog;
    import javax.swing.JMenuBar;
    //import javax.swing.*;
    //import javax.swing.event.*;
    //import javax.swing.JToggleButton;
    public class CheckboxPanel extends Panel{
    ItemListener iListener;
    boolean state;
    Button button1;
    // public static Object newInstance(Class componentType,
    //int length){
    public static final long serialVersionUID = 1L;
    //public static final char k = 0;
    Checkbox[] check = new Checkbox[61];
    //Checkbox check1, check2, check3, check4, check5 , check6 ,check7 ,check8 ,check9 ,check10 ,check11 ,check12 ,check13 ,
    //check14 ,check15 ,check16 ,check17 ,check18 ,check19 ,check20 ,check21 ,check22 ,check23 ,check24 ,check25 ,check26 ,
    //check27 ,check28 ,check29 ,check30 ,check31 ,check32 ,check33 ,check34 ,check35 ,check36 ,check37 ,check38 ,check39 ,
    //check40 ,check41 ,check42 ,check43 ,check44 ,check45 ,check46 ,check47 ,check48 ,check49 ,check50 ,check51 ,check52 ,
    //check53 ,check54 ,check55 ,check56 ,check57 ,check58 ,check59 ,check60,
    //isSelected = new Checkbox();
    protected int group1,group2,group3,group4,group5,group6,group7,group8,group9,group10,group11,group12,group13,group14,group15;
    //int[] CheckBox = {k};
    //Array.newInstance(private Checkbox check6;
    // state of checkbox
    CheckboxPanel(){
    setLayout(new GridLayout(4,4));
    setBackground(Color.gray);
    /* Question 1 layout panel */
    // Create a panel for the question and answers
    Panel question1Panel = new Panel();
    question1Panel.setLayout(new GridLayout(1, 2));
    // Create a label for the question number
    Label lbl = new Label("1");
    // Add it to the question panel so it appears on the right
    question1Panel.add(lbl);
    // Add a panel for the answers to the question
    Panel answer1Panel = new Panel();
    // Use a grid layout of 4 rows by 1 column
    answer1Panel.setLayout(new GridLayout(4,1));
    //CheckBox.addActionListener(new ActionListener(){
    //public void actionPerformed(ActionEvent ae)
    // System.out.println("check box state"+check.getState());
    check[1] = new Checkbox("A. Imaginative");
    answer1Panel.add(check[1]);
    //check1.addItemListener(iListener);
    //state = check1.isSeleted() ; // tells whether box is checked
    //check1.setSelected(state);
    //getContentPane().add(check1);// set checked state of box
    check[2] = new Checkbox("B. Investigative");
    answer1Panel.add(check[2]);
    //check1.addItemListener(iListener);
    //state = check1.isSeleted() ; // tells whether box is checked
    //check1.setSelected(state);
    //getContentPane().add(check1);// set checked state of box
    check[3] = new Checkbox("C. Realistic");
    answer1Panel.add(check[3]);
    check[4] = new Checkbox("D. Analytical");
    answer1Panel.add(check[4]);
    question1Panel.add(answer1Panel);
    add(question1Panel);
    /* Question 2 layout panel */
    Panel question2Panel = new Panel();
    question2Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("2");
    question2Panel.add(lbl);
    Panel answer2Panel = new Panel();
    answer2Panel.setLayout(new GridLayout(4,1));
    check[5] = new Checkbox("A. Organized");
    answer2Panel.add(check[5]);
    check[6]= new Checkbox("B. Adaptable");
    answer2Panel.add(check[6]);
    check[7] = new Checkbox("C. Critical");
    answer2Panel.add(check[7]);
    check[8] = new Checkbox("D. Inquisitive");
    answer2Panel.add(check[8]);
    question2Panel.add(answer2Panel);
    add(question2Panel);
    /* Question 3 layout panel*/
    Panel question3Panel= new Panel();
    question3Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("3");
    question3Panel.add(lbl);
    Panel answer3Panel = new Panel();
    answer3Panel.setLayout(new GridLayout(4,1));
    check[9] = new Checkbox("A. Debating");
    answer3Panel.add(check[9]);
    check[10] = new Checkbox("B.Getting to the point");
    answer3Panel.add(check[10]);
    check[11] = new Checkbox("C. Creating");
    answer3Panel.add(check[11]);
    check[12] = new Checkbox("D. Relating");
    answer3Panel.add(check[12]);
    question3Panel.add(answer3Panel);
    add(question3Panel);
    /* Question 4 layout panel*/
    Panel question4Panel= new Panel();
    question4Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("4");
    question4Panel.add(lbl);
    Panel answer4Panel = new Panel();
    answer4Panel.setLayout(new GridLayout(4,1));
    check[13] = new Checkbox("A. Personal");
    answer4Panel.add(check[13]);
    check[14] = new Checkbox("B. Practical");
    answer4Panel.add(check[14]);
    check[15] = new Checkbox("C. Academic");
    answer4Panel.add(check[15]);
    check[16] = new Checkbox("D. Adventurous");
    answer4Panel.add(check[16]);
    question4Panel.add(answer4Panel);
    add(question4Panel);
    /* Question 5 layout panel*/
    Panel question5Panel= new Panel();
    question5Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("5");
    question5Panel.add(lbl);
    Panel answer5Panel = new Panel();
    answer5Panel.setLayout(new GridLayout(4,1));
    check[17] = new Checkbox("A. Presice");
    answer5Panel.add(check[17]);
    check[18 ]= new Checkbox("B. Flexible");
    answer5Panel.add(check[18]);
    check[19] = new Checkbox("C. Systematic");
    answer5Panel.add(check[19]);
    check[20] = new Checkbox("D. Inventive");
    answer5Panel.add(check[20]);
    question5Panel.add(answer5Panel);
    add(question5Panel);
    /* Question 6 layout panel*/
    Panel question6Panel= new Panel();
    question6Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("6");
    question6Panel.add(lbl);
    Panel answer6Panel = new Panel();
    answer6Panel.setLayout(new GridLayout(4,1));
    check[21] = new Checkbox("A. Sharing");
    answer6Panel.add(check[21]);
    check[22]= new Checkbox("B. Orderly");
    answer6Panel.add(check[22]);
    check[23] = new Checkbox("C. Sensible");
    answer6Panel.add(check[23]);
    check[24] = new Checkbox("D. Independent");
    answer6Panel.add(check[24]);
    question6Panel.add(answer6Panel);
    add(question6Panel);
    /* Question 7 layout panel*/
    Panel question7Panel= new Panel();
    question7Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("7");
    question7Panel.add(lbl);
    Panel answer7Panel = new Panel();
    answer7Panel.setLayout(new GridLayout(4,1));
    check[25] = new Checkbox("A. Competitive");
    answer7Panel.add(check[25]);
    check[26] = new Checkbox("B. Perfectionist");
    answer7Panel.add(check[26]);
    check[27] = new Checkbox("C. Cooperative");
    answer7Panel.add(check[27]);
    check[28] = new Checkbox("D. Logical");
    answer7Panel.add(check[28]);
    question7Panel.add(answer7Panel);
    add(question7Panel);
    /* Question 8 layout panel*/
    Panel question8Panel= new Panel();
    question8Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("8");
    question8Panel.add(lbl);
    Panel answer8Panel = new Panel();
    answer8Panel.setLayout(new GridLayout(4,1));
    check[29] = new Checkbox("A. Intellectual");
    answer8Panel.add(check[29]);
    check[30] = new Checkbox("B. Sensitive");
    answer8Panel.add(check[30]);
    check[31] = new Checkbox("C. Hard-working");
    answer8Panel.add(check[31]);
    check[32] = new Checkbox("D. Risk-taking");
    answer8Panel.add(check[32]);
    question8Panel.add(answer8Panel);
    add(question8Panel);
    /* Question 9 layout panel*/
    Panel question9Panel= new Panel();
    question9Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("9");
    question9Panel.add(lbl);
    Panel answer9Panel = new Panel();
    answer9Panel.setLayout(new GridLayout(4,1));
    check[33] = new Checkbox("A. Reader");
    answer9Panel.add(check[33]);
    check[34] = new Checkbox("B. People person");
    answer9Panel.add(check[34]);
    check[35] = new Checkbox("C. Problem solver");
    answer9Panel.add(check[35]);
    check[36] = new Checkbox("D. Planner");
    answer9Panel.add(check[36]);
    question9Panel.add(answer9Panel);
    add(question9Panel);
    /* Question 10 layout panel*/
    Panel question10Panel= new Panel();
    question10Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("10");
    question10Panel.add(lbl);
    Panel answer10Panel = new Panel();
    answer10Panel.setLayout(new GridLayout(4,1));
    check[37] = new Checkbox("A. Memorize");
    answer10Panel.add(check[37]);
    check[38] = new Checkbox("B. Associate");
    answer10Panel.add(check[38]);
    check[39] = new Checkbox("C. Think-through");
    answer10Panel.add(check[39]);
    check[40] = new Checkbox("D. Originate");
    answer10Panel.add(check[40]);
    question10Panel.add(answer10Panel);
    add(question10Panel);
    /* Question 11 layout panel*/
    Panel question11Panel= new Panel();
    question11Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("11");
    question11Panel.add(lbl);
    Panel answer11Panel = new Panel();
    answer11Panel.setLayout(new GridLayout(4,1));
    check[41] = new Checkbox("A. Changer");
    answer11Panel.add(check[41]);
    check[42] = new Checkbox("B. Judger");
    answer11Panel.add(check[42]);
    check[43] = new Checkbox("C. Spontaneous");
    answer11Panel.add(check[43]);
    check[44] = new Checkbox("D. Wants direction");
    answer11Panel.add(check[44]);
    question11Panel.add(answer11Panel);
    add(question11Panel);
    /* Question 12 layout panel*/
    Panel question12Panel= new Panel();
    question12Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("12");
    question12Panel.add(lbl);
    Panel answer12Panel = new Panel();
    answer12Panel.setLayout(new GridLayout(4,1));
    check[45] = new Checkbox("A. Communicating");
    answer12Panel.add(check[45]);
    check[46] = new Checkbox("B. Discovering");
    answer12Panel.add(check[46]);
    check[47] = new Checkbox("C. Caring");
    answer12Panel.add(check[47]);
    check[48] = new Checkbox("D. Examining");
    answer12Panel.add(check[48]);
    question12Panel.add(answer12Panel);
    add(question12Panel);
    /* Question 13 layout panel*/
    Panel question13Panel= new Panel();
    question13Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("13");
    question13Panel.add(lbl);
    Panel answer13Panel = new Panel();
    answer13Panel.setLayout(new GridLayout(4,1));
    check[49] = new Checkbox("A. Challenging");
    answer13Panel.add(check[49]);
    check[50] = new Checkbox("B. Practicing");
    answer13Panel.add(check[50]);
    check[51] = new Checkbox("C. Caring");
    answer13Panel.add(check[51]);
    check[52] = new Checkbox("D. Examining");
    answer13Panel.add(check[52]);
    question13Panel.add(answer13Panel);
    add(question13Panel);
    /* Question 14 layout panel*/
    Panel question14Panel= new Panel();
    question13Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("14 ");
    question14Panel.add(lbl);
    Panel answer14Panel = new Panel();
    answer14Panel.setLayout(new GridLayout(4,1));
    check[53] = new Checkbox("A. Completing work");
    answer14Panel.add(check[53]);
    check[54] = new Checkbox("B. Seeing possibilities");
    answer14Panel.add(check[54]);
    check[55] = new Checkbox("C. Gaining ideas");
    answer14Panel.add(check[55]);
    check[56] = new Checkbox("D. Interpreting");
    answer14Panel.add(check[56]);
    question14Panel.add(answer14Panel);
    add(question14Panel);
    /* Question 15 layout panel*/
    Panel question15Panel= new Panel();
    question15Panel.setLayout(new GridLayout(1,2));
    lbl = new Label("15");
    question15Panel.add(lbl);
    Panel answer15Panel = new Panel();
    answer15Panel.setLayout(new GridLayout(4,1));
    check[57] = new Checkbox("A. Doing");
    answer15Panel.add(check[57]);
    check[58] = new Checkbox("B. Feeling");
    answer15Panel.add(check[58]);
    check[59] = new Checkbox("C. Thinking");
    answer15Panel.add(check[59]);
    check[60] = new Checkbox("D. Experimenting");
    answer15Panel.add(check[60]);
    question15Panel.add(answer15Panel);
    add(question15Panel);
    /*class ToggleButton extends JFrame{
    public ToggleButton(){
    super("ToggleButton");
    getContentPane().setLayout(new FlowLayout());
    ButtonGroup buttonGroup =new ButtonGroup();
    char ch = (char) ('1'+ k);
    for (int k=0; k<4; k++){
    JToggleButton button = new JToggleButton("Button"+ch, k==0);
    button.setMnemonic(ch);
    button.setEnabled(k<3);
    button.setToolTipText("This is button"+ ch);
    getContentPane().add(button);
    buttonGroup.add(button);
    //pack();
    JButton button1 = new JButton("SUBMIT");
    //Object BOX_TITLE;
    //JDialog dialog = Panel.createDialog(Dialog.this, BOX_TITLE);
    //dialog.show();
    add(button1);
    addComponentListener((ComponentListener) iListener);
    ActionListener al = new ActionListener(){
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    if (check[1].getState()== true){
    group1 = group1 +1;
    if (check[2].getState()== true){
    group1 = group1 +1;
    if (check[3].getState()== true){
    group1 = group1 +1;
    if (check[4].getState()== true){
    group1 = group1 +1;
    if (check[5].getState()== true){
    group2 = group2 +1;
    if (check[6].getState()== true){
    group2 = group2 +1;
    if (check[7].getState()== true){
    group2 = group2 +1;
    if (check[8].getState()== true){
    group2 = group2 +1;
    if (check[9].getState()== true){
    group3 = group3 +1;
    if (check[10].getState()== true){
    group3 = group3 +1;
    if (check[11].getState()== true){
    group3 = group3 +1;
    if (check[12].getState()== true){
    group3 = group3 +1;
    if (check[13].getState()== true){
    group4 = group4 +1;
    if (check[14].getState()== true){
    group4 = group4 +1;
    if (check[15].getState()== true){
    group4 = group4 +1;
    if (check[16].getState()== true){
    group4 = group4 +1;
    if (check[17].getState()== true){
    group5 = group5 +1;
    if (check[18].getState()== true){
    group5 = group5 +1;
    if (check[19].getState()== true){
    group5 = group5 +1;
    if (check[20].getState()== true){
    group5 = group5 +1;
    if (check[21].getState()== true){
    group6 = group6 +1;
    if (check[22].getState()== true){
    group6 = group6 +1;
    if (check[23].getState()== true){
    group6 = group6 +1;
    if (check[24].getState()== true){
    group6 = group6 +1;
    if (check[25].getState()== true){
    group7 = group7 +1;
    if (check[26].getState()== true){
    group7 = group7 +1;
    if (check[27].getState()== true){
    group7 = group7 +1;
    if (check[28].getState()== true){
    group7 = group7 +1;
    if (check[29].getState()== true){
    group8 = group8 +1;
    if (check[30].getState()== true){
    group8 = group8 +1;
    if (check[31].getState()== true){
    group8 = group8 +1;
    if (check[32].getState()== true){
    group8 = group8 +1;
    if (check[33].getState()== true){
    group9 = group9 +1;
    if (check[34].getState()== true){
    group9 = group9 +1;
    if (check[35].getState()== true){
    group9 = group9 +1;
    if (check[36].getState()== true){
    group9 = group9 +1;
    if (check[37].getState()== true){
    group10 = group10 +1;
    if (check[38].getState()== true){
    group10 = group10 +1;
    if (check[39].getState()== true){
    group10 = group10 +1;
    if (check[40].getState()== true){
    group10 = group10 +1;
    if (check[41].getState()== true){
    group11 = group11 +1;
    if (check[42].getState()== true){
    group11 = group11 +1;
    if (check[43].getState()== true){
    group11 = group11 +1;
    if (check[44].getState()== true){
    group11 = group11 +1;
    if (check[45].getState()== true){
    group12 = group12 +1;
    if (check[46].getState()== true){
    group12 = group12 +1;
    if (check[47].getState()== true){
    group12 = group12 +1;
    if (check[48].getState()== true){
    group12 = group12 +1;
    if (check[49].getState()== true){
    group13 = group13 +1;
    if (check[50].getState()== true){
    group13 = group13 +1;
    if (check[51].getState()== true){
    group13 = group13 +1;
    if (check[52].getState()== true){
    group13 = group13 +1;
    if (check[53].getState()== true){
    group14 = group14 +1;
    if (check[54].getState()== true){
    group14 = group14 +1;
    if (check[55].getState()== true){
    group14 = group14 +1;
    if (check[56].getState()== true){
    group14 = group14 +1;
    if (check[57].getState()== true){
    group15 = group15 +1;
    if (check[58].getState()== true){
    group15 = group15 +1;
    if (check[59].getState()== true){
    group15 = group15 +1;
    if (check[60].getState()== true){
    group15 = group15 +1;
    System.out.println(check[1].getState());
    System.out.println(check[2].getState());
    System.out.println(check[3].getState());
    System.out.println(check[4].getState());
    System.out.println(check[5].getState());
    System.out.println(check[6].getState());
    System.out.println(check[7].getState());
    System.out.println(check[8].getState());
    System.out.println(check[9].getState());
    System.out.println(check[10].getState());
    System.out.println(check[11].getState());
    System.out.println(check[12].getState());
    System.out.println(check[13].getState());
    System.out.println(check[14].getState());
    System.out.println(check[15].getState());
    System.out.println(check[16].getState());
    System.out.println(check[17].getState());
    System.out.println(check[18].getState());
    System.out.println(check[19].getState());
    System.out.println(check[20].getState());
    System.out.println(check[21].getState());
    System.out.println(check[22].getState());
    System.out.println(check[23].getState());
    System.out.println(check[24].getState());
    System.out.println(check[25].getState());
    System.out.println(check[26].getState());
    System.out.println(check[27].getState());
    System.out.println(check[28].getState());
    System.out.println(check[29].getState());
    System.out.println(check[30].getState());
    System.out.println(check[31].getState());
    System.out.println(check[32].getState());
    System.out.println(check[33].getState());
    System.out.println(check[34].getState());
    System.out.println(check[35].getState());
    System.out.println(check[36].getState());
    System.out.println(check[37].getState());
    System.out.println(check[38].getState());
    System.out.println(check[39].getState());
    System.out.println(check[40].getState());
    System.out.println(check[41].getState());
    System.out.println(check[42].getState());
    System.out.println(check[43].getState());
    System.out.println(check[44].getState());
    System.out.println(check[45].getState());
    System.out.println(check[46].getState());
    System.out.println(check[47].getState());
    System.out.println(check[48].getState());
    System.out.println(check[49].getState());
    System.out.println(check[50].getState());
    System.out.println(check[51].getState());
    System.out.println(check[52].getState());
    System.out.println(check[53].getState());
    System.out.println(check[54].getState());
    System.out.println(check[55].getState());
    System.out.println(check[56].getState());
    System.out.println(check[57].getState());
    System.out.println(check[58].getState());
    System.out.println(check[59].getState());
    System.out.println(check[60].getState());
    button1.addActionListener(al);
    private JMenuBar createMenuBar() {
    // TODO Auto-generated method stub
    return null;
    //button1.addActionListener(al);
    }

  • Jbutton Help!!Pls do help if know

    i have a program that can;t compile because it stated canot resolve the button symbol,just got one error!!can anyone help see why the problem appear and how to fix it.Just cut and paste to compile(urgent)
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    public class bb extends JFrame implements ActionListener{
         public bb() {
              super("Software License Agreement");
              Container contentPane = getContentPane();
              JPanel panel = new JPanel();
              JCheckBox agree = new JCheckBox("I agree with all the term above");
              final JButton
                   accept = new JButton("Accept..."),          
                   decline = new JButton("Decline...");
                   accept.setEnabled(false);          
                   accept.setMnemonic('A');
                   decline.setEnabled(false);
                   decline.setMnemonic('D');
                   decline.addActionListener(this);
              String content = "testing" ;
              JLabel label = new JLabel("Important Notice!Please read this license agreement carefully before proceeding to the next page otherwise utilizing this product indicate your"),
              label2 = new JLabel("acknowledgement that you have already read the entire content agreement and agree all of its term.Scroll down to continue read below the page.");
                                       label.setFont(new Font("Arial", Font.PLAIN, 12));
                        label.setForeground(Color.darkGray);
                        label2.setForeground(Color.darkGray);
                        label2.setFont(new Font("Arial", Font.PLAIN, 12));
              JTextArea word= new JTextArea(content,23,68);
              word.setLineWrap(true);
              panel.add(new JScrollPane(word));
              panel.add(agree);
              agree.setSelected(false);
              word.setEditable(false);
              panel.setPreferredSize(new Dimension(785,470));
              panel.setBorder(BorderFactory.createTitledBorder("Contract"));
              contentPane.setLayout(new FlowLayout());
              contentPane.add(label, BorderLayout.NORTH);
              contentPane.add(label2);
              contentPane.add(panel);
              contentPane.add(accept,"Left");
              contentPane.add(decline,"Left");
              agree.addItemListener(new ItemListener() {
                   public void itemStateChanged(ItemEvent event) {
                        JCheckBox b = (JCheckBox)event.getSource();
                        accept.setEnabled(b.isSelected());
                        decline.setEnabled(b.isSelected());
                        //button.repaint();
         public void QuitScreen() {
         bb BB = new bb();
         programquit pQuit = new programquit(BB);
         pQuit.setVisible(true);
    public static void main(String args[]) {
              JFrame f = new bb();
              Toolkit theKit = f.getToolkit();
              Dimension wndSize = theKit.getScreenSize();
              f.setBounds(wndSize.width/10, wndSize.height/10,800,600);
              f.setVisible(true);
         f.setResizable(false);
    f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
         public void actionPerformed(ActionEvent e){
              if(e.getSource() == decline)
    QuitScreen();

    eg
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.border.*;
    class programquit extends Dialog /*implements ActionListener*/ {
        Label
        lConfirm = new Label("Are you sure ?");
        Button
        bYes = new Button("Yes"),
         bNo = new Button("No");
        Panel
        p1 = new Panel(),
         p2 = new Panel();
        public programquit(Frame owner) {
         this(owner, true);
        public programquit(Frame owner, boolean model) {
         super(owner, model);
         setTitle("Quiting EMS");
         setResizable(false);
         setSize(200, 150);
         setLocation(300, 200);
         setBackground(Color.black);
         setForeground(Color.green);
         addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                  setVisible(false);
         setLayout(new GridLayout(2, 1));
         p1.add(lConfirm);
         p2.add(bYes);
         p2.add(bNo);
         add(p1);
         add(p2);
         bYes.setBackground(Color.green);
         bYes.setForeground(Color.black);
         bNo.setBackground(Color.green);
         bNo.setForeground(Color.black);
         bYes.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  System.exit(0);
         bNo.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e) {
                  setVisible(false);
    public class bb extends JFrame /*implements ActionListener*/ {
        public bb() {
         super("Software License Agreement");
         Container contentPane = getContentPane();
         JPanel panel = new JPanel();
         JCheckBox agree = new JCheckBox("I agree with all the term above");
         final JButton
             accept = new JButton("Accept..."),
             decline = new JButton("Decline...");
         accept.setEnabled(false);
         accept.setMnemonic('A');
         decline.setEnabled(false);
         decline.setMnemonic('D');
         decline.addActionListener( new ActionListener() {
              public void actionPerformed(ActionEvent e){
                  QuitScreen();
         String content = "testing" ;
         JLabel label = new JLabel("Important Notice!Please read this license agreement carefully before proceeding to the next page otherwise utilizing this product indicate your"),
             label2 = new JLabel("acknowledgement that you have already read the entire content agreement and agree all of its term.Scroll down to continue read below the page.");
         label.setFont(new Font("Arial", Font.PLAIN, 12));
         label.setForeground(Color.darkGray);
         label2.setForeground(Color.darkGray);
         label2.setFont(new Font("Arial", Font.PLAIN, 12));
         JTextArea word= new JTextArea(content,23,68);
         word.setLineWrap(true);
         panel.add(new JScrollPane(word));
         panel.add(agree);
         agree.setSelected(false);
         word.setEditable(false);
         panel.setPreferredSize(new Dimension(785,470));
         panel.setBorder(BorderFactory.createTitledBorder("Contract"));
         contentPane.setLayout(new FlowLayout());
         contentPane.add(label, BorderLayout.NORTH);
         contentPane.add(label2);
         contentPane.add(panel);
         contentPane.add(accept,"Left");
         contentPane.add(decline,"Left");
         agree.addItemListener(new ItemListener() {
              public void itemStateChanged(ItemEvent event) {
                  JCheckBox b = (JCheckBox)event.getSource();
                  accept.setEnabled(b.isSelected());
                  decline.setEnabled(b.isSelected());
    //button.repaint();
        public void QuitScreen() {
         bb BB = new bb();
         programquit pQuit = new programquit(BB);
         pQuit.setVisible(true);
        public static void main(String args[]) {
         JFrame f = new bb();
         Toolkit theKit = f.getToolkit();
         Dimension wndSize = theKit.getScreenSize();
         f.setBounds(wndSize.width/10, wndSize.height/10,800,600);
         f.setVisible(true);
         f.setResizable(false);
         f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    }

  • Question related to JButton action event

    Hi All,
    In my application a small issue has poppedup i.e. i am giving a JButton with an action and with that action a .bat file is getting generated and immediately i am making it to get executed by using the runtime class.Now my question is if i keep on firing the same button for 20 times same batch file is getting executed for 20 times.SO i want to control that process something like once the execution is done i need to have an acknowledgement so that i will be getting a chance to fire in the next.
    After first click on the JButton second click should not process anything till the first execution is done.
    How is it possoible to implement this??
    Any help appreciated.
    regards,
    Viswanadh

    Hi Camic and Andre,
    Thanks for the replies i will try out in both the ways and get back to you people.
    And camic as you were saying to go through Process class i have seen and immediately got a question.When i disable the JButton is it a right way that me getting the exitValue of the Process soemthing like
    Process p;
    if ( p.exitValue()==0){
    JButton.setEnabled(true) /enabling button
    }Is this the right way to do???
    regards,
    Viswanadh

Maybe you are looking for