Finishing methods

hi!
i had to develop this program for anassignement and im dont know how to finish it. most of the work is already done. it is a library that perform simple operations. im missing A method that chehcs wheter and item has been borrowed or not as well as a method to lend.
i would apreciate if anyone could help me out with this
lasse.
here are files(there are several mains just for developing pourposes)
library(which contains main) this program works as it is)------------
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Library extends JFrame
private Container container;
private JLabel statusLabel,Label;
private static Properties table;
private JTextArea displayArea;
private UIManager.LookAndFeelInfo looks[];
private JTextField nameField,typeField,noField,tempField;
//Constructor
public Library()
super( "Departmental Library" );
// Set Up GUI
statusLabel = new JLabel();
table = new Properties();
displayArea = new JTextArea( 4,8 );
displayArea.setEditable( false );
JPanel northPanel = new JPanel();
JPanel eastPanel = new JPanel();
eastPanel.setLayout( new GridLayout( 8,1 ) );
northPanel.setLayout( new BorderLayout( ) );
eastPanel.add( new JLabel( " " ) );
JButton insertButton = new JButton( "Insert Item" );
eastPanel.add( insertButton );
insertButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event )
BookInsert bookInsert = new BookInsert();
JButton removeButton = new JButton( "Remove Item" );
eastPanel.add( removeButton );
removeButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event )
ItemRemove itemRemove = new ItemRemove();
JButton listItemsButton = new JButton ( "List Items" );
eastPanel.add( listItemsButton );
listItemsButton.addActionListener(
new ActionListener(){
public void actionPerformed( ActionEvent event )
listProperties();
JButton expiredButton = new JButton( "Check overdue Items" );
eastPanel.add( expiredButton );
expiredButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event )
JOptionPane.showMessageDialog( null, "Incomplete!!!!\n\n\n" );
JButton saveButton = new JButton ( "Save Contents" );
eastPanel.add( saveButton );
saveButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event )
try {
FileOutputStream output = new FileOutputStream( "libraryContents.dat" );
table.store( output, "" );
output.close();
listProperties();
catch( IOException ioException ) {
ioException.printStackTrace();
JOptionPane.showMessageDialog( null, "The current contents in the library are saved" );
JButton loadButton = new JButton ( "Load Contents" );
eastPanel.add( loadButton );
loadButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent event )
try {
FileInputStream input = new FileInputStream( "libraryContents.dat" );
table.load( input );
input.close();
listProperties();
catch ( IOException ioException ) {
ioException.printStackTrace();
eastPanel.add( new JLabel( " " ) );
int valBold = Font.BOLD;
int valItalic = Font.ITALIC;
Label = new JLabel( "The Library", SwingConstants.CENTER);
Label.setFont( new Font( "Courier New", valBold, 24 ) );
northPanel.add( Label );
container = getContentPane();
container.add( northPanel, BorderLayout.NORTH );
container.add( new JScrollPane( displayArea ), BorderLayout.CENTER );
container.add( eastPanel, BorderLayout.EAST );
looks = UIManager.getInstalledLookAndFeels();
try{
UIManager.setLookAndFeel( looks[ 2 ].getClassName() );
SwingUtilities.updateComponentTreeUI( this );
catch ( Exception exception )
exception.printStackTrace();
setSize( 600, 300 );
setLocation( 130,120 );
setVisible( true );
public static void insertItem( String name, String type )
LibraryItem libraryItem = new LibraryItem( name, type );
Object value = table.setProperty( name, type );
JOptionPane.showMessageDialog( null, "Stock Item " + name + "inserted in the Library." );
public static void removeItem( String name )
Object value = table.remove( name );
if ( value != null ) {
JOptionPane.showMessageDialog( null, "Library item " + name + " removed." );
else {
JOptionPane.showMessageDialog( null, "Library item " + name + " was NOT FOUND in the Library!" );
public void listProperties()
StringBuffer buffer = new StringBuffer();
String name, icode, value;
Enumeration enumeration = table.propertyNames();
while ( enumeration.hasMoreElements() ) {
name = enumeration.nextElement().toString();
value = table.getProperty( name );
buffer.append( name ).append( '\t' );
buffer.append( value ).append( '\n' );
displayArea.setText( "Item Name" + "\t" + "Item code" + "\tItem Type" );
displayArea.setText( buffer.toString() );
public static void ValidDate(int day,int month,int year)
int dayok;
int yearok;
int daysOfMonths[] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if ( day >=1 && day <= daysOfMonths[ month ]){
dayok = 1;
else
dayok = 0;
if ( month == 2 && day == 29 && (year % 400 == 0 || ( year % 4 == 0 && year % 100 != 0 ) ) ) {
yearok = 1;
else{
yearok = 0;
if ( dayok ==1 || ( dayok == 1 && yearok == 1) || (dayok == 0 && yearok == 1 ) || yearok == 1){
BookInsert.executeInsertion();
else {
JOptionPane.showMessageDialog( null, "The Library item name is missing!" );
return;
public static void main( String args[] )
Library library = new Library();
library.addWindowListener(
new WindowAdapter() {
public void windowClosing( WindowEvent event )
System.exit( 0 );
class LibraryItem
private String name, code, type;
public LibraryItem( String itemName, String itemType )
name = itemName;
type = itemType;
public String toString()
return name + " " + type;
mport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ItemRemove extends JFrame
private static JButton removeButton;
private static JTextField nameField;
public ItemRemove()
super( "Remove a Library Item" );
Container container = getContentPane();
container.setLayout( new GridLayout( 4,1 ) );
container.add( new JLabel( "Book title: ", SwingConstants.LEFT) );
nameField = new JTextField( 10 );
container.add( nameField );
container.add( new JLabel( " " ) );
removeButton = new JButton( " Remove " );
container.add( removeButton );
removeButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
Library.removeItem( nameField.getText() );
setSize( 200, 150 );
setLocation( 250,150 );
setVisible( true );
// public static void main( String args[] )
// ItemRemove itemRemove = new ItemRemove();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BookInsert extends JFrame implements ActionListener
private JTextField nameField, codeField;
private static JComboBox itypesBox;
public static int day, month, year;
private static JButton insertButton;
private static boolean toggle = true;
public static String itemName, itemCode, itemType, itemTypeCode;
private String names[] = { "Computing", "Mathematics", "Poetry", "Literature", "Programming", "Science Fiction", "Economics", "Physics", "Engineering" };
public BookInsert()
super( " Insert a Book Item in the stock" );
Container container = getContentPane();
container.setLayout( new GridLayout( 6,3 ) );
container.add( new JLabel( " " ) );
container.add( new JLabel( " " ) );
container.add( new JLabel( " " ) );
container.add( new JLabel( "Book title: ", SwingConstants.RIGHT) );
nameField = new JTextField( 10 );
container.add( nameField );
container.add( new JLabel(" "));
container.add( new JLabel( "Book code: ", SwingConstants.RIGHT ));
codeField = new JTextField( 10 );
container.add( codeField );
container.add( new JLabel( " " ) );
container.add( new JLabel("Book Subject:", SwingConstants.RIGHT) );
StringBuffer buffer = new StringBuffer();
itypesBox = new JComboBox( names );
itypesBox.setMaximumRowCount( 4 );
itypesBox.setSize( 7,8 );
container.add( itypesBox );
container.add( new JLabel( " " ) );
container.add( new JLabel( " " ) );
container.add( new JLabel( " " ) );
container.add( new JLabel( " " ) );
container.add( new JLabel( " " ) );
insertButton = new JButton( " Insert " );
container.add( insertButton );
insertButton.addActionListener( this );
setSize( 300, 150 );
setLocation( 220,150 );
setVisible( true );
public void actionPerformed( ActionEvent event )
itemType = names[ itypesBox.getSelectedIndex() ];
itemName = nameField.getText();
itemCode = codeField.getText();
itemTypeCode = itemCode + " " + itemType;
executeInsertion();
try {
catch ( NumberFormatException numberFormatException ) {
public static void executeInsertion()
Library.insertItem( itemName, itemTypeCode );
public static void main( String args[] )
BookInsert bookInsert = new BookInsert();
bookInsert.setVisible( true );
}thanks in advance for any help!

your right but dont have time since i have to submit it tomorrow. i hava a new version which im gonna post in full here and illd like someone to provide de code to make buttom"check overdue items " work taking in consideration that a book is borrowed only for 15 day max from the date it was borrowed.i hope htis is more espacific.ive got 4 classes and the program works ,so you can try it on you IDE. there we go
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Library extends JFrame
     private Container container;
     private JLabel statusLabel,Label;
     private static Properties table;
     private JTextArea displayArea;
     private JTextField nameField,typeField,noField,tempField;
     private  UIManager.LookAndFeelInfo looks[];
        //Constructor
     public Library()                   
          super( "Departmental Library" );
                //  Set Up GUI
          statusLabel = new JLabel();
          table = new Properties();
          displayArea = new JTextArea( 4,8 );
          displayArea.setEditable( false );
          JPanel northPanel = new JPanel();
          JPanel eastPanel = new JPanel();
          eastPanel.setLayout( new GridLayout( 8,1 ) );
          northPanel.setLayout( new BorderLayout( ) );
          JButton insertButton = new JButton( "Insert Item" );
          eastPanel.add( insertButton );
          insertButton.addActionListener( new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         BookInsert bookInsert = new BookInsert();
          JButton removeButton = new JButton( "Remove Item" );
          eastPanel.add( removeButton );
          removeButton.addActionListener( new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         ItemRemove itemRemove = new ItemRemove();
          JButton listItemsButton = new JButton ( "List Items" );
          eastPanel.add( listItemsButton );
          listItemsButton.addActionListener(
               new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         listProperties();
          JButton borrowButton = new JButton("Borrow an Item");
          eastPanel.add(borrowButton);
          borrowButton.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent event)
                         ItemBorrow itemBorrow = new ItemBorrow();
          JButton returnButton=new JButton("Return an Item");
          eastPanel.add(returnButton);
          returnButton.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent event)
                         JOptionPane.showMessageDialog( null, "Return!" );
          JButton overdueButton = new JButton( "Check overdue Items" );
          eastPanel.add( overdueButton );
          overdueButton.addActionListener(new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         JOptionPane.showMessageDialog( null, "Incomplete!!!!\n\n\n" );
          JButton saveButton = new JButton ( "Save Contents" );
                eastPanel.add( saveButton );     
          saveButton.addActionListener( new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         try {
                              FileOutputStream output = new FileOutputStream( "libraryContents.dat" );
                              table.store( output, "" );
                              output.close();
                              listProperties();
                         catch( IOException ioException ) {
                              ioException.printStackTrace();
                         JOptionPane.showMessageDialog( null, "The current contents in the library are saved" );
          JButton loadButton = new JButton ( "Load Contents" );
          eastPanel.add( loadButton );
          loadButton.addActionListener( new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         try {
                              FileInputStream input = new FileInputStream( "libraryContents.dat" );
                              table.load( input );
                              input.close();
                              listProperties();
                         catch ( IOException ioException ) {
                              ioException.printStackTrace();
          int valBold      = Font.BOLD;
          int valItalic     = Font.ITALIC;
          Label = new JLabel( "The Library", SwingConstants.CENTER);
          Label.setFont( new Font( "Courier New", valBold, 24 ) );
          northPanel.add( Label );
          container = getContentPane();
          container.add( northPanel, BorderLayout.NORTH );
          container.add( new JScrollPane( displayArea ), BorderLayout.CENTER );
          container.add( eastPanel, BorderLayout.EAST );
          setSize(750,300);
          setLocation(10,120);
          setVisible(true);
          looks = UIManager.getInstalledLookAndFeels();
          try{
               UIManager.setLookAndFeel( looks[ 2 ].getClassName() );
               SwingUtilities.updateComponentTreeUI( this );
          catch ( Exception exception )
               exception.printStackTrace();
     public static void insertItem( String name, String type )
          LibraryItem libraryItem = new LibraryItem( name, type );
          Object value = table.setProperty( name, type );
          JOptionPane.showMessageDialog( null, "Stock Item " + name + " was inserted in the Library. Press \"Save contents\" to insert it permanently to file" );
     public static void removeItem(String name)
          Object value = table.remove(name);
          if ( value != null ){
               JOptionPane.showMessageDialog( null, "Library item " + name + " removed. Press \" Save contents \"to remove it permanently" );
          else {
               JOptionPane.showMessageDialog( null, "Library item " + name + " was NOT FOUND in the Library!" );
     public static void borrowItem(String name)
          String value=table.getProperty(name);
          if (value !=null){
               String date = "" + new java.util.Date();
               String day     = date.substring( 8,10 );
               String month= date.substring( 4,7 );
               String nmonth = "";
               if (month.equals("Jan")){
                    nmonth = "01";
               else if (month.equals("Feb")){
                    nmonth = "02";
               else if (month.equals("Mar")){
                    nmonth = "03";
               else if (month.equals("Apr")){
                    nmonth = "04";
               else if (month.equals("May")){
                    nmonth = "05";
               else if (month.equals("Jun")){
                    nmonth = "06";
               else if (month.equals("Jul")){
                    nmonth = "07";
               else if (month.equals("Aug")){
                    nmonth = "08";
               else if (month.equals("Sep")){
                    nmonth = "09";
               else if (month.equals("Oct")){
                    nmonth = "10";
               else if (month.equals("Nov")){
                    nmonth = "11";
               else if (month.equals("Dec")){
                    nmonth = "12";
               String year     = date.substring( 24,date.length() );
               String allDate=day+"/"+nmonth+"/"+year;
               String elems[] = {"-","-","-","-","-"};
               int el=0;
               int stopper=0;
               for (int i=0; i<value.length();i++)
                    if (value.substring(i,i+1).equals(" "))
                         elems[el]=value.substring(stopper,i);
                         stopper=i;
                         el+=1;
               elems[el]=value.substring(stopper,value.length());
               elems[2] = "Borrowed";
               String newValue = elems[0]+" "+elems[1]+" "+elems[2]+" "+allDate;
               LibraryItem item = new LibraryItem( name,newValue );
               Object aValue = table.setProperty(name,newValue);
               JOptionPane.showMessageDialog( null, "Item " + name + " is borrowed on " + allDate + "\nand must be returned within 15 days" );
          else {
               JOptionPane.showMessageDialog( null, "Library item " + name + " NOT found among Stock!");
          //JOptionPane.showMessageDialog( null, "Works so far. Now borrow" );
          //Object value = table.setProperty( name, type );
     public void listProperties()
          StringBuffer buffer = new StringBuffer();
          String name="", value = "";
          Enumeration enumeration = table.propertyNames();
          while ( enumeration.hasMoreElements() ) {
               name = enumeration.nextElement().toString();
               value = table.getProperty( name );
               buffer.append(name).append("\t\t");
               String elems[] = {"-","-","-","-","-"};
               int el=0;
               int stopper=0;
               for (int i=0; i<value.length();i++)
                    if (value.substring(i,i+1).equals(" "))
                         elems[el]=value.substring(stopper,i);
                         stopper=i;
                         el+=1;
               elems[el]=value.substring(stopper,value.length());
               String output="";
               for (int i=0;i<elems.length;i++)
                    buffer.append(elems[i] + "\t");
               buffer.append("\n");
          String output=buffer.toString();
          displayArea.setText(output);
     public static void main( String args[] )
          Library library = new Library();
          library.addWindowListener(
               new WindowAdapter() {
                    public void windowClosing( WindowEvent event )
                         System.exit( 0 );
class LibraryItem
     private String name, code, type;
     public LibraryItem( String itemName, String itemType )
          name = itemName;
        type = itemType;
     public String toString()
          return name + " " + type;
mport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ItemRemove extends JFrame
     private static JButton removeButton;
     private static JTextField nameField;
     public ItemRemove()
          super( "Remove a Library Item" );
          Container container = getContentPane();
          container.setLayout( new GridLayout( 4,1 ) );
          container.add( new JLabel( "Book title: ", SwingConstants.LEFT) );
          nameField = new JTextField( 10 );
          container.add( nameField );
          container.add( new JLabel( "  " ) );
          removeButton = new JButton( " Remove " );
          container.add( removeButton );
          removeButton.addActionListener(
               new ActionListener() {
                    public void actionPerformed( ActionEvent event )
                         Library.removeItem( nameField.getText() );
          setSize( 280, 150 );
          setLocation( 250,150 );
          setVisible( true );
//     public static void main( String args[] )
//          ItemRemove itemRemove = new ItemRemove();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ItemBorrow extends JFrame
     private static JButton borrowButton;
     private static JTextField nameField;
     public ItemBorrow()
          super( "Borrow a Library Item" );
          Container container = getContentPane();
          container.setLayout( new GridLayout( 4,1 ) );
          container.add( new JLabel( "Book title: ", SwingConstants.LEFT) );
          nameField = new JTextField( 10 );
          container.add( nameField );
          container.add( new JLabel( "  " ) );
          borrowButton = new JButton( " Borrow " );
          container.add( borrowButton );
          borrowButton.addActionListener( new ActionListener(){
                    public void actionPerformed( ActionEvent event )
                         Library.borrowItem( nameField.getText() );
          setSize( 250, 150 );
          setLocation( 250,150 );
          setVisible( true );
//     public static void main( String args[] )
//          ItemBorrow itemBorrow = new ItemBorrow();
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class BookInsert extends JFrame implements ActionListener
     private JTextField nameField, codeField;
     private static JComboBox itypesBox;
     public static int day, month, year;
     private static JButton insertButton;
     private static boolean toggle = true;
     public static String itemName, itemCode, itemType, itemTypeCode;
     private String names[] = { "Computing", "Mathematics", "Poetry", "Literature", "Programming", "Science Fiction", "Economics", "Physics", "Engineering" };
     public BookInsert()
          super( " Insert a Book Item in the stock" );
          Container container = getContentPane();
          container.setLayout( new GridLayout( 6,3 ) );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( "Book title: ", SwingConstants.RIGHT) );
          nameField = new JTextField( 10 );
          container.add( nameField );
          container.add( new JLabel(" "));
        container.add( new JLabel( "Book code: ", SwingConstants.RIGHT ));
        codeField = new JTextField( 10 );
        container.add( codeField );
        container.add( new JLabel( "    " ) );
        container.add( new JLabel("Book Subject:", SwingConstants.RIGHT) );
          StringBuffer buffer = new StringBuffer();
          itypesBox = new JComboBox( names );
          itypesBox.setMaximumRowCount( 4 );
          itypesBox.setSize( 7,8 );
          container.add( itypesBox );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( " " ) );
          container.add( new JLabel( " " ) );
          insertButton = new JButton( " Insert " );
          container.add( insertButton );
          insertButton.addActionListener( this );
          setSize( 300, 150 );
          setLocation( 220,150 );
          setVisible( true );
     public void actionPerformed( ActionEvent event )
          itemType = names[ itypesBox.getSelectedIndex() ];
                    itemName = nameField.getText();
                itemCode = codeField.getText();
                itemTypeCode = itemCode + " " + itemType + " " + "notBorrowed";
                executeInsertion();
     public static void executeInsertion()
          Library.insertItem( itemName, itemTypeCode );
     public static void main( String args[] )
          BookInsert bookInsert = new BookInsert();
          bookInsert.setVisible( true );
}hope any one can give me an answer.thanks a lot.

Similar Messages

  • ElementChange interface and accessing those methods..

    Hi all, I'm stuck on accessing the three methods contained in ElementChange (below). This interface class is supposed to be an inner class interface of DocumentEvent, if that helps? This is more a java question about the API (which is not so documented in this area of ElementChange. If someone can lead me down the right path, it would be fantastic!! Thanks so much! Sorry I'm not able to provide my attempts with ElementChange, as I'm so lost at how I can access it.. :(
    Element[] getChildrenAdded();
    Element[] getChildrenRemoved();
    Element[] getElement();So far I have my DocumentListener ( which is added to my JEditorPane - separate class)
    public class Changes implements DocumentListener {
        public Changes() {
        //----------------------Inferface Methods Start-----------------------//
        //Method from DocumentListener
        public void changedUpdate( DocumentEvent e ) {
            pushEditInfo( e );
        //Method from DocumentListener
        public void insertUpdate( DocumentEvent e ) {
            pushEditInfo( e );
        //Method from DocumentListener
        public void removeUpdate( DocumentEvent e ) {
            pushEditInfo( e );
        //----------------------Inferface Methods Finish-----------------------//
        //Method to handle DocumentEvents
        private void pushEditInfo( DocumentEvent e ) {
                Document doc = ( Document )e.getDocument();
                Element elem = doc.getDefaultRootElement();
                //get hold of element change - need this for elementchange class' methods
                e.getChange( elem );
    }

    Mistake: methods are:
    Element[] getChildrenAdded();
    Element[] getChildrenRemoved();
    Element getElement();

  • I am really sorry but I am still stuck. Please help.

    Please can someone help me with the following code. I have a number of questions. So far all buttons that I have coded actions for work fine. When The program saves it does it correctly as I have seen the text file. However I have some problems.
    1) How can I declare the arrays in another way without setting them to "" when the program starts. I need the program to start and show the previous saved arrays instead. I dont know if my method used for retrieving data from the file is correct either?.
    2) When retrieving the values from a file that has example (all are string values). ADAM SANDLER 111 222 333 MICKY MOUSE 222 444 666
    Where I want them to be in the follwing arrays as an example.
    String name[1] = ADAM
    String surname[1] = SANDLER
    String home[1] = 111
    String work[1] = 222
    String cell[1] = 333
    String name[2] = MICKY
    String surname[2] = MOUSE
    String home[2] = 222
    String work[2] = 444
    String cell[2] = 666
    Here is my code.
         Filename:     ContactsListInterface.java
         Date:           16 March 2008
         Programmer:     Yucca Nel
         Purpose:     Provides a GUI for entering names and contact numbers into a telephone directory.
                        Also allows options for searching for a specific name and deleting of data from the record
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class ContactsListInterface extends JFrame implements ActionListener
    { //start of class
         // Declare outputstream and inputStream
         DataOutputStream output;
         DataInputStream input;
         String filename = "phonebook";
         // construct fields, buttons, labels and text boxes
         JTextPane displayPane = new JTextPane();
         JLabel listOfContacts = new JLabel("List Of Contacts");               // creates a label for the scrollpane
         JButton createButton = new JButton("Create");
         JButton searchButton = new JButton("Search");
         JButton modifyButton = new JButton("Modify");
         JButton deleteButton = new JButton("Delete");
         // declare data arrays for name, surname, work number, home number and cell number
         private String name[] = {""};
         private String surname[] = {""};
         private String home[] = {""};
         private String work[] = {""};
         private String cell[] = {""};
         // create an instance of the ContactsListInterface
         public ContactsListInterface()
         { // start of cli()
              super("Phonebook Interface");
         } // end of cli()
         public JMenuBar createMenuBar()
         { // start of the createMenuBar()
              // construct and populate a menu bar
              JMenuBar mnuBar = new JMenuBar();                    // creates a menu bar
              setJMenuBar(mnuBar);
              JMenu mnuFile = new JMenu("File",true);               // creates a file menu in the menu bar which is visible
                   mnuFile.setMnemonic(KeyEvent.VK_F);
                   mnuFile.setDisplayedMnemonicIndex(0);
                   mnuFile.setToolTipText("File Options");
                   mnuBar.add(mnuFile);
              JMenuItem mnuFileExit = new JMenuItem("Exit");     // creates an exit option in the file menu
                   mnuFileExit.setMnemonic(KeyEvent.VK_X);
                   mnuFileExit.setDisplayedMnemonicIndex(1);
                   mnuFileExit.setToolTipText("Close Application");
                   mnuFile.add(mnuFileExit);
                   mnuFileExit.setActionCommand("Exit");
                   mnuFileExit.addActionListener(this);
              JMenu mnuEdit = new JMenu("Edit",true);               // creates a menu for editing options
                   mnuEdit.setMnemonic(KeyEvent.VK_E);
                   mnuEdit.setDisplayedMnemonicIndex(0);
                   mnuEdit.setToolTipText("Edit Options");
                   mnuBar.add(mnuEdit);
              JMenu mnuEditSort = new JMenu("Sort",true);          // creates an option for sorting entries
                   mnuEditSort.setMnemonic(KeyEvent.VK_S);
                   mnuEditSort.setDisplayedMnemonicIndex(0);
                   mnuEdit.add(mnuEditSort);
              JMenuItem mnuEditSortByName = new JMenuItem("Sort By Name");          // to sort entries by name
                   mnuEditSortByName.setMnemonic(KeyEvent.VK_N);
                   mnuEditSortByName.setDisplayedMnemonicIndex(8);
                   mnuEditSortByName.setToolTipText("Sort entries by first name");
                   mnuEditSortByName.setActionCommand("Name");
                   mnuEditSortByName.addActionListener(this);
                   mnuEditSort.add(mnuEditSortByName);
              JMenuItem mnuEditSortBySurname = new JMenuItem("Sort By Surname");     // to sort entries by surname
                   mnuEditSortBySurname.setMnemonic(KeyEvent.VK_R);
                   mnuEditSortBySurname.setDisplayedMnemonicIndex(10);
                   mnuEditSortBySurname.setToolTipText("Sort entries by surname");
                   mnuEditSortBySurname.setActionCommand("Surname");
                   mnuEditSortBySurname.addActionListener(this);
                   mnuEditSort.add(mnuEditSortBySurname);
              JMenu mnuHelp = new JMenu("Help",true);                    // creates a menu for help options
                   mnuHelp.setMnemonic(KeyEvent.VK_H);
                   mnuHelp.setDisplayedMnemonicIndex(0);
                   mnuHelp.setToolTipText("Help options");
                   mnuBar.add(mnuHelp);
              JMenuItem mnuHelpHelp = new JMenuItem("Help");          // creates a help option for help topic
                   mnuHelpHelp.setMnemonic(KeyEvent.VK_P);
                   mnuHelpHelp.setDisplayedMnemonicIndex(3);
                   mnuHelpHelp.setToolTipText("Help Topic");
                   mnuHelpHelp.setActionCommand("Help");
                   mnuHelpHelp.addActionListener(this);
                   mnuHelp.add(mnuHelpHelp);
              JMenuItem mnuHelpAbout = new JMenuItem("About");     // creates a about option for info about api
                   mnuHelpAbout.setMnemonic(KeyEvent.VK_T);
                   mnuHelpAbout.setDisplayedMnemonicIndex(4);
                   mnuHelpAbout.setToolTipText("About this program");
                   mnuHelpAbout.setActionCommand("About");
                   mnuHelpAbout.addActionListener(this);
                   mnuHelp.add(mnuHelpAbout);
              return mnuBar;
         } // end of the createMenuBar()
         // create the content pane
         public Container createContentPane()
         { // start of createContentPane()
              // try blocks for the input and output
              try
                   output = new DataOutputStream(new FileOutputStream(filename));
              catch(IOException io)
                   JOptionPane.showMessageDialog(null,"This program could not create a storage location. Please check the disk drive and the tun the program again.","Error",JOptionPane.ERROR_MESSAGE);
                   System.exit(1);
              //construct and populate panels and content pane
              JPanel labelPanel = new JPanel(); // panel is only used to put the label for the textpane in
                   labelPanel.setLayout(new FlowLayout());
                   labelPanel.add(listOfContacts);
              JPanel displayPanel = new JPanel();// panel is used to display all the contacts and thier numbers
                   setTabsAndStyles(displayPane);
                   displayPane = addTextToTextPane();
                   displayPane.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(displayPane);
                   scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // pane is scrollable vertically
                   scrollPane.setWheelScrollingEnabled(true);// pane is scrollable by use of the mouse wheel
                   scrollPane.setPreferredSize(new Dimension(400,320));
              displayPanel.add(scrollPane);
              JPanel workPanel = new JPanel();// panel is used to enter, edit and delete data
                   workPanel.setLayout(new FlowLayout());
                   workPanel.add(createButton);
                        createButton.setToolTipText("Create a new entry");
                        createButton.addActionListener(this);
                   workPanel.add(searchButton);
                        searchButton.setToolTipText("Search for an entry by name number or surname");
                        searchButton.addActionListener(this);
                   workPanel.add(modifyButton);
                        modifyButton.setToolTipText("Modify an existing entry");
                        modifyButton.addActionListener(this);
                   workPanel.add(deleteButton);
                        deleteButton.setToolTipText("Delete an existing entry");
                        deleteButton.addActionListener(this);
              labelPanel.setBackground(Color.red);
              displayPanel.setBackground(Color.red);
              workPanel.setBackground(Color.red);
              // create container and set attributes
              Container c = getContentPane();
                   c.setLayout(new BorderLayout(30,30));
                   c.add(labelPanel,BorderLayout.NORTH);
                   c.add(displayPanel,BorderLayout.CENTER);
                   c.add(workPanel,BorderLayout.SOUTH);
                   c.setBackground(Color.red);
              // add a listener for the window closing and save
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             int answer = JOptionPane.showConfirmDialog(null,"Are you sure you would like to save all changes and exit?","File submission",JOptionPane.YES_NO_OPTION);
                             if(answer == JOptionPane.YES_OPTION)
                                  save();
                                  System.exit(0);
              return c;
         } // end of createContentPane()
         protected void setTabsAndStyles(JTextPane displayPane)
         { // Start of setTabsAndStyles()
              // set Font style
              Style fontStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
              Style regular = displayPane.addStyle("regular", fontStyle);
              StyleConstants.setFontFamily(fontStyle, "SansSerif");
              Style s = displayPane.addStyle("bold", regular);
              StyleConstants.setBold(s,true);
         } // End of setTabsAndStyles()
         public JTextPane addTextToTextPane()
         { // start of addTextToTextPane()
              try
                   input = new DataInputStream(new FileInputStream(filename));
                   for(int i=0; i<name.length;i++)
                        name[i] = input.readUTF();
                        surname[i] = input.readUTF();
                        home[i] = input.readUTF();
                        work[i] = input.readUTF();
                        cell[i] = input.readUTF();
              catch(IOException io)
              Document doc = displayPane.getDocument();
              try
              { // start of tryblock
                   // clear previous text
                   doc.remove(0,doc.getLength());
                   // insert titles of columns
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   // insert data
                   for(int i=0; i<name.length; i++)
                        doc.insertString(doc.getLength(), name[i] +"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), surname[i] +"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), home[i]+"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), work[i]+"\t",displayPane.getStyle("regular"));
                        doc.insertString(doc.getLength(), cell[i]+"\t",displayPane.getStyle("regular"));
              } // end of try block
              catch(BadLocationException ble)
              { // start of ble exception handler
                   System.err.println("Could not insert text.");
              } // end of ble exception handler
              return displayPane;
         } // end of addTextToTextPane()
         // code to process user clicks
         public void actionPerformed(ActionEvent e)
         { // start of actionPerformed()
              String arg = e.getActionCommand();
              // user clicks exit option
              if(arg.equals("Exit"))
                   int answer = JOptionPane.showConfirmDialog(null,"Exiting will save all changes to file. \nAre you sure you would like to save and exit now?","File submission",JOptionPane.YES_NO_OPTION);
                   if(answer == JOptionPane.YES_OPTION)
                        save();
                        System.exit(1);
              // user clicks help option
              if(arg.equals("Help"))
                   JOptionPane.showMessageDialog(null, "Welcome to the phone book application. To add a new entry press the \"Create\" button.\n To search for an entry press the \"Search\" button.\n To modify an existing entry press the \"Modify\" button. \n To delete an entry press the \"Delete\" button.","Help Topic",JOptionPane.INFORMATION_MESSAGE);
              // user clicks about option
              if(arg.equals("About"))
                   JOptionPane.showMessageDialog(null,"Phonebook v 1.01 created by Yucca Nel.\nNo copyright exists.\nThis program is freeware and should not be sold.\nEnjoy :-)","About phonebook",JOptionPane.INFORMATION_MESSAGE);
              // user clicks create button
              if(arg.equals("Create"))
                   createNew();
              // user clicks search button
              if(arg.equals("Search"))
                   searchForName(arg, name);                    // Only possible to search by name as all contacts Must have a name
              if(arg.equals("Modify"))
                   modifyContact(arg,name);
                   save();
              // user clicks the sort by name option
              if(arg.equals("Name"))
                   sort(name);
              if(arg.equals("Surname"))
                   sort(surname);
         } // end of actionPerformed()
         // Method to ceate a new entry
         public void createNew()
         { // start of createNew()
              int newHome, newWork, newCell = 0;
              String newContactName = JOptionPane.showInputDialog(null,"Please enter the new contacts first name or press cancel to exit.");
              if(newContactName == null)     finish();                         // if user clicks cancel
              if(newContactName.length() <=0)
                   JOptionPane.showMessageDialog(null,"You did not enter a valid name.\nPlease make sure you enter data correctly.","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();                                                  // To return to the create method
              String newContactSurname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname or press cancel to exit.");
              if(newContactSurname == null)     finish();                    // if user clicks cancel
              if(newContactSurname.equals(""))
                   int answer = JOptionPane.showConfirmDialog(null,"You did not enter a surname.\nAre you sure you wish to leave the surname empty?","No data entered",JOptionPane.YES_NO_OPTION);   // Asks if data was valid
                   if(answer == JOptionPane.NO_OPTION)
                        newContactSurname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname.");
              String newContactWorkNum = JOptionPane.showInputDialog(null,"Please enter the new contacts work number or press cancel to exit.");
              if(newContactWorkNum == null)   finish();                    // if user clicks cancel
              String newContactHomeNum = JOptionPane.showInputDialog(null,"Please enter the new contacts home number or press cancel to exit.");
              if(newContactHomeNum == null)     finish();                    // if user clicks cancel
              String newContactCellNum = JOptionPane.showInputDialog(null,"Please enter the new contacts cell number or press cancel to exit.");
              if(newContactCellNum == null)     finish();                    // if user clicks cancel
              // enlarge the arrays so they can accept data
              name = enlargeArray(name);
              surname = enlargeArray(surname);
              work = enlargeArray(work);
              home = enlargeArray(home);
              cell = enlargeArray(cell);
              // add the new data into the arrays
              name[name.length-1] = newContactName;
              surname[surname.length-1] = newContactSurname;
              home[home.length-1] = newContactHomeNum;
              work[work.length-1] = newContactWorkNum;
              cell[cell.length-1] = newContactCellNum;
              // sort the names so they appear in alphebetical order
              sort(name);
         } // end of createNew()
         // The enlarge array method
         //method to enlarge an array by 1
         public String[] enlargeArray(String[] currentArray)
              String[] newArray = new String[currentArray.length + 1];
              for (int i = 0; i < currentArray.length; i++)
              newArray[i] = currentArray;
              return newArray;
         }// End of enlargeArray()
         // The Sort Method
         public void sort(String tempArray[])
         { // start of sort()
              // for loop
              for(int pass = 1; pass < tempArray.length; pass++)
                   for(int element = 0; element < tempArray.length -1; element++)
                   if(tempArray[element].compareTo(tempArray[element+1])>0)
                        swap(name, element, element+1);
                        swap(surname, element, element+1);
                        swap(home, element, element+1);
                        swap(work, element, element+1);
                        swap(cell, element, element+1);
              addTextToTextPane();
         } // end of sort()
         // The swap method
         public void swap(String swapArray[], int first, int second)
         { // start of swap()
              String hold;
              hold = swapArray[first];
              swapArray[first] = swapArray[second];
              swapArray[second] = hold;
         } // end of swap()
         // method to search for a name
         public void searchForName(String searchField, String searchArray[])
         { // start of searchForName()
              try
                   Document doc = displayPane.getDocument();                         // assign text to an object
                   doc.remove(0,doc.getLength());                                        // clear the screen
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   String searchValue = JOptionPane.showInputDialog(null,"Please enter the 1st name of the person you would like to see phone numbers for or press cancel to exit.");
                   boolean found = false;
                   if(searchValue == null) finish();                                   // if user clicks cancel
                   //search the array
                   for(int i=0; i < name.length; i++)
                        if(searchValue.compareTo(searchArray[i])==0)
                             doc.insertString(doc.getLength(), name[i] +"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), surname[i] +"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), home[i]+"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), work[i]+"\t",displayPane.getStyle("regular"));
                             doc.insertString(doc.getLength(), cell[i]+"\t",displayPane.getStyle("regular"));
                             found = true;
                   if(found == false)
                        JOptionPane.showMessageDialog(null,"No contact with that name found.","No result found",JOptionPane.INFORMATION_MESSAGE);
                        sort(name);
              catch(BadLocationException ble)
                   System.err.println("Could not insert text.");
         } // end of searchForName()
         // Method to modify contact
         public void modifyContact(String searchField, String searchArray[])
         { // start of modifyContact()
              try
                   Document doc = displayPane.getDocument();                         // assign text to an object
                   doc.remove(0,doc.getLength());                                        // clear the screen
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
                   String modifyValue = JOptionPane.showInputDialog(null,"Please enter the 1st name of the person you would like to change details for. Or press cancel to exit");
                   boolean found = false;
                   if(modifyValue == null)      finish();                              // if user clicks cancel
                   //search the array
                   for(int i=0; i < name.length; i++)
                        if(modifyValue.compareTo(searchArray[i])==0)
                             // To change the name
                             String oldName = name[i];
                             String newName = JOptionPane.showInputDialog(null,"Please enter a new name if you would like to change the name for "+name[i]+". Or press cancel to exit");
                             if(newName == null)
                                  name[i] = oldName;                                        // if user clicks cancel keep old entry
                                  finish();
                             if(newName.equals(""))                                        // if no data entered then name will stay same
                                  JOptionPane.showMessageDialog(null,"You did not enter a name in the name field.\nOld name will be kept.","Information Message",JOptionPane.INFORMATION_MESSAGE);
                                  name[i] = oldName;
                                  addTextToTextPane();
                             else
                                  name[i] = newName;                                        // new name is saved into array
                                  addTextToTextPane();
                             //To change the surname
                             String oldSurname = surname[i];
                             String newSurname = JOptionPane.showInputDialog(null,"Please enter a new surname if you would like to change the surname for "+name[i]+". Or press cancel to exit");
                             if(newSurname == null)
                                  surname[i] = oldSurname;                              // if user clicks cancel keep old entry
                                  finish();
                             if((oldSurname.length()>0) && newSurname.length()<=0)          // if surname existed but no new surname was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the surname for "+name[i]+".\nAre you sure you would like to remove the surname for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old surname and leave no surname in place
                                       surname[i] = newSurname;                         // new surname is saved into the array
                                  else                                                       // user does not wish to remove surname
                                       surname[i] = oldSurname;                         // keep the old surname
                             else                                                            // just replace the surname with new one as everything seems fine
                                  surname[i] = newSurname;
                             //To change the work number of contact
                             String oldWork = work[i];
                             String newWork = JOptionPane.showInputDialog(null,"Please enter a new work number if you would like to change the work number for "+name[i]+". Or press cancel to exit");
                             if(newWork == null)
                                  work[i] = oldWork;                                        // user clicks cancel keep old entry
                                  finish();
                             if((oldWork.length()>0) && newWork.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the work number for "+name[i]+".\nAre you sure you would like to remove the work number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       work[i] = newWork;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       work[i] = oldWork;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  work[i] = newWork;
                             //To change the work number of contact
                             String oldHome = home[i];
                             String newHome = JOptionPane.showInputDialog(null,"Please enter a new home number if you would like to change the home number for "+name[i]+". Or press cancel to exit");
                             if(newHome == null)
                                  home[i] = oldHome;                                        // if user clicks cancel keep old value
                                  finish();
                             if((oldHome.length()>0) && newHome.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the home number for "+name[i]+".\nAre you sure you would like to remove the home number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       home[i] = newHome;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       home[i] = oldHome;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  home[i] = newHome;
                             //To change the cell number
                             String oldCell = cell[i];
                             String newCell = JOptionPane.showInputDialog(null,"Please enter a new cell number if you would like to change the cell number for "+name[i]+". Or press cancel to exit");
                             if(newCell == null)
                                  cell[i] = oldCell;                                        // if user clicks cancel keep old value
                                  finish();
                             if((oldCell.length()>0) && newCell.length()<=0)          // if number existed but no new number was entered
                                  int answer = JOptionPane.showConfirmDialog(null,"You are about to remove the Cell number for "+name[i]+".\nAre you sure you would like to remove the cell number for this contact?","Please confirm the following",JOptionPane.YES_NO_OPTION);
                                  if(answer == JOptionPane.YES_OPTION)               // user wishes to remove old number and leave no number in place
                                       cell[i] = newCell;                                   // new number is saved into the array
                                  else                                                       // user does not wish to remove number
                                       cell[i] = oldCell;                                   // keep the old number
                             else                                                            // just replace the number with new one as everything seems fine
                                  cell[i] = newCell;
                             found = true;
                        addTextToTextPane();
                   if(found == false)
                        JOptionPane.showMessageDialog(null,"No contact with that name found.","No result found",JOptionPane.INFORMATION_MESSAGE);
                        sort(name);
                        addTextToTextPane();
              catch(BadLocationException ble)
                   System.err.println("Could not insert text.");
         } // end of searchForName()
         // finish method for cancel button
         public void finish()
              JOptionPane.showMessageDialog(null,"This program will now close and automatically save all data entered. You may restart the program to modify any changes.","Information Message",JOptionPane.INFORMATION_MESSAGE);
              System.exit(0);
         // method to save data to file
         public void save()
              try
                   for(int i=0; i < name.length; i++)
                        output.writeUTF(name[i]);
                        output.writeUTF(surname[i]);
                        output.writeUTF(work[i]);
                        output.writeUTF(home[i]);
                        output.writeUTF(cell[i]);
                   JOptionPane.showMessageDialog(null,"Data succesfully saved to file.","Information message",JOptionPane.INFORMATION_MESSAGE);
              catch(IOException io)
                   System.exit(1);
         public static void main(String[] args)
         { // start of main()
              // Set look and feel of interface
              try
              { // start of try block
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } // end of try block
              catch(Exception e)
              { // start of catch block
                   JOptionPane.showMessageDialog(null,"There was an error in setting the look and feel of this application","Error",JOptionPane.INFORMATION_MESSAGE);
              } // end of catch block
              ContactsListInterface cli = new ContactsListInterface();
              cli.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              cli.setJMenuBar(cli.createMenuBar());
              cli.setContentPane(cli.createContentPane());
              cli.setSize(520,500);
              cli.setVisible(true);
              cli.setResizable(false);
         } // end of main()
    } //end of classBefore thinking I am lazy I dont want you to correct my code. Just give me a few pointers on how to get my arrays back from the file and how to set my strings to  a non null value that wont show when my program starts.
    Edited by: Yucca on Mar 24, 2008 7:24 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              

    Yucca wrote:
    It's pretty easy to write objects to file, but it depends on what you want to do with that file. Do you want it to be a human-readable text file? Is it only to be used by your program? The file is to be used by my program to save to and to read from. But I understand now that saving each entry as a string and not writing it to an array may be easier. Do I use the buffered reader instead of InputStreamReader? Oh sorry I forgot to mention that the file I save to will later be used when I convert my application to a database type/SQL tyype aplication.
    Edited by: Yucca on Mar 24, 2008 8:06 PMIt sounds to me like object serialization would be the easiest for what you want to do. Read through this:
    http://java.sun.com/developer/technicalArticles/Programming/serialization/
    And these apis:
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectOutputStream.html
    http://java.sun.com/j2se/1.5.0/docs/api/java/io/ObjectInputStream.html

  • For all users having probs with OO ALV Grid

    I wanted to put this in the WIKI but it keeps bombing out when I try and save so I've put this here -- Maybe a MOD can move it for me.
    This generic class should give you far more insite into using an EDITABLE ALV table than the standard documentation.
    If you follow the steps you should be able to code very quickly a decent useable ALV OO program which can retrieve and manipulate data very easily.  The events are (hopefully) well documented as are all the steps.
    Once you understand the basics you can add more functionality like colouring Cells, adding hyperlinks etc etc.
    I've always found that stupid SEAT / AIRLINE application SAP uses for its examples far too overblown and in reality who would ever use a SAP system for Airline reservations anyway.
    The class here describes a much simpler application which CLEARLY (I hope) explains how the whole thing works.
    Jimbo's generic class for using the OO ALV GRID Class CL_GUI_ALV_GRID
    from an application program to display and manipulate ANY table
    with minimal coding needed in the Calling application program.
    Handles the following EVENTS
    1) TOOLBAR BUTTONS
    (you can add more to the toolbar method
      if you need even more functionality).
    2) DOUBLE CLICK
    3) ENTER KEY PRESSED
    4) DATA CHANGED
    5) DATA CHANGED FINISHED
    Methods available
    PUBLIC METHODS  ( Can be called directly from the application program).
    1) display_grid  displays grid with toolbar
       Table and FCAT are built dynamically - user only needs to
       define the table structure (can be DDIC or User fields)
    2) change_title  - changes title at the top of the Grid
    3) refresh_grid   - refreshes grid after table updated etc.
    4) build_dynamic_structures - this method creates a dynamic table and a dynamic FCAT
       using the structure defined in the calling application program
    PRIVATE METHODS (Internal Methods used within the class)
    1) verwerk - returns to FORM VERWERK in calling application program
       (Via Toolbar). The application program can then do any special processing
       at this point e.g update SAP tables etc.
    2) download_to_excel (via Toolbar). This creates an EXCEL spreadsheet
       directly which can be downloaded / saved to a file if required,
    3) return_structure - internal method returns the structure
       of the table defined in the calling application program. This is needed in order
       to build the dynamic table and Field Catalog.
    4) create_dynamic_table  - creates a dynamic table from the structure defined in
       the calling application program
    5) create_dynamic_fcat  - creates the dynamic field catalog from the structure
       defined in the application program.
    6) dubbleklik entered when user double clicks a cell
    activated by EVENT DOUBLE_CLICK.
    returns to FORM DUBBELKLIK  in the
    calling application program
       COOKBOOK STEP BY STEP instructions on how to use this class
       in your application program.
       In the application program :
    1) define a blank screen 100  - SE51 with a custom container
       on it called CCONTAINER1.
       you need the following logic in the screen
       The PAI is only used if you have defined a STATUS with SE41 and you exit the
       application program via the standard SAP buttons on the
       top of the Screen (NOT the GRID toolbar).
         PROCESS BEFORE OUTPUT.
          MODULE STATUS_0100.
         PROCESS AFTER INPUT.
         MODULE USER_COMMAND_0100.
    2) (optional) define a STATUS with a titlebar - SE41
       you only need this if you want the standard EXIT and menu buttons on the
       top line of the screen
    3) If you want to have your OWN colum names on the grid
       add the following macro to the start of your program
         DEFINE col_name.
         read  table it_fldcat into  wa_it_fldcat index &1.
         wa_it_fldcat-coltext = &2.
         modify it_fldcat from wa_it_fldcat index &1.
         END-OF-DEFINITION.
    4) Define the following Field symbols
       <fs1>           TYPE  ANY,
       <fs2>           TYPE  STANDARD TABLE,
       <fs3>           TYPE ANY,
       <field_catalog> TYPE STANDARD TABLE,
       <dyn_table>    TYPE  STANDARD TABLE,
       <orig_table>   TYPE  STANDARD TABLE,
       <dyn_field>,
       <dyn_wa>.
    5) After the field-symbols add the code in this class
        as an INCLUDE
        e.g INCLUDE ZZJIMBOXX_INCL.
    6) define your Internal table as follows
        TYPES:  BEGIN OF s_elements,
                  Your structure
                your structure etc.
                END OF  s_elements.
    For example
    INCLUDE  <icon>.
    TABLES: VAPMA.
    *TYPES:  BEGIN OF s_elements,
    vbeln   TYPE vapma-vbeln,
    posnr   TYPE vapma-posnr,
    matnr   TYPE vapma-matnr,
    kunnr   TYPE vapma-kunnr,
    werks   TYPE vapma-werks,
    vkorg   TYPE vapma-vkorg,
    vkbur   TYPE vapma-vkbur,
    status  TYPE c,
    *END OF  s_elements.
    7) Define the following data  IN YOUR APPLICATION PROGRAM
       (note here only data is described
       that relates to using THIS CLASS. Data purely used internally
       in the application program is NOT shown here).
    DATA: z_object          TYPE REF TO zcl_dog,  "Instantiate our class
          grid_container1    TYPE REF TO cl_gui_custom_container,
          t_elements         TYPE TABLE OF s_elements, "refers to our ITAB
          wa_elements        TYPE s_elements,
          wa_dyn_table_line  TYPE REF TO DATA,
          it_fldcat          TYPE lvc_t_fcat,
          i_gridtitle        TYPE lvc_title,
          wa_it_fldcat       TYPE lvc_s_fcat,
          new_table          TYPE REF TO DATA,
          dy_table           TYPE REF TO data,
          dy_line            TYPE REF TO data,
          row_id             TYPE sy-index.
    8) insert the following code at the start of the application program.
    *START-OF-SELECTION.
    *CALL SCREEN 100.
    *END-OF-SELECTION.
    *MODULE status_0100 OUTPUT.
    *ASSIGN  wa_elements TO <fs1>.
    *CREATE OBJECT z_object EXPORTING z_object = z_object. "Instantiate the class
    *CALL METHOD z_object->build_dynamic_structures
           CHANGING it_fldcat = it_fldcat.
    9) if you inserted the macro in step 3) then
       define your own column names as follws
      col_name 1 'Name1'.
      col_name 2 'Name2'.
      etc. The number is the colum number you want and the name is
      the name you want to assign to the column.
    for example using the table shown above
      col_name 1 'Order Nr'.
      col_name 2 'Item'.
      col_name 3 'Material'.
      col_name 4 'Customer'.
      col_name 5 'Plant'.
      col_name 6 'Sales Org'.
      col_name 7 'Sales Office'.
      col_name 8 'Status'.
    10)  perform a routine that fills your dynamic table and
         display the GRID. If you created a status with SE41 you can set
         a title etc. Further processing is dependent on the users action
         after the GRID is displayed for example if a Cell is double clicked,
         dat is entered, a toolbar button is pressed or a SAP ICON on top of the screen is pressed.
    PERFORM populate_dynamic_itab.
    CALL METHOD z_object->display_grid
          CHANGING it_fldcat = it_fldcat.
    SET PF-STATUS '0001'.
    SET TITLEBAR '000'.
    ENDMODULE.
    11) If you added a STATUS via SE41 you can exit the program via the
    standard SAP buttons at the top of the screen
    otherwise exit via the exit button on the toolbar.
    You only need this piece of code if you defined a STATUS in the application program
    MODULE user_command_0100 INPUT.
    CASE sy-ucomm.
       WHEN 'BACK'.
         LEAVE PROGRAM.
       WHEN 'EXIT'.
         LEAVE PROGRAM.
       WHEN 'RETURN'.
         LEAVE PROGRAM.
       WHEN OTHERS.
    ENDCASE.
    12)  to populate the dynamic table you only need to code something like this
    remember the class has already created and structured the field-symbol <dyn_table>
    so you don't have to do anything other than just select the fields you want
    filled and from what data source(es).
    *FORM populate_dynamic_itab.
    *SELECT vbeln posnr matnr kunnr werks vkorg vkbur
          UP TO 200 rows
          FROM vapma
          INTO  CORRESPONDING FIELDS OF TABLE <dyn_table>.
    if you want to keep the original table before making any changes etc code
    the following
    create 2nd Dyn table to hold original data. We can use
    the same field catalog as for the original table
    as we are just creating an identical copy here.
    *CALL METHOD cl_alv_table_create=>create_dynamic_table
       EXPORTING
            it_fieldcatalog = it_fldcat
         IMPORTING
            ep_table = dy_table.
      ASSIGN dy_table->* TO <orig_table>.
    CREATE DATA dy_line LIKE LINE OF <orig_table>.
    ASSIGN dy_line->* TO <dyn_wa>.
    <orig_table> = <dyn_table>.
    ENDFORM.
    13) you need these 2 processing routines in your application program.
    FORM VERWERK.  "Entered from VERW on toolbar
    *break-point 1.
    Orig table is in dynamic table <orig_table>
    ALV GRID changed table is in <dyn_table>.
    *Loop at <orig_table>  into <dyn_wa>.
      Do what you want here
    end
    endloop.
    ENDFORM.
    *form dubbleklik using     "Entered when a cell is double clicked
           e_row   type LVC_S_ROW
           e_column type LVC_S_col
           es_row_no type lvc_s_roid.
           break-point 1.
    Get Row id into a variable for this program.
           row_id =  e_row.
            SET TITLEBAR '001'.      "If you defined a status in SE41
           i_gridtitle = 'Grid Title Changed'.
           CALL METHOD  z_object->change_title
             EXPORTING i_gridtitle = i_gridtitle.
           PERFORM refresh.
    endform.
    The REFRESH routine is optional but after a double click I assume
    you want to do some processing
    and re-display the data
    so as a sample code something like
    *FORM refresh.
    data: ord_nr  TYPE vapma-vbeln.  "Your data
    *READ TABLE  <dyn_table> index row_id into wa_elements.
       ord_nr = wa_elements-vbeln.
    You've now got the Row double clicked so pick out the data element(s)
    you wnat to process and do your processing
    *set parameter id 'AUN'  field ord_nr.
    *CALL TRANSACTION  'VA02' AND SKIP FIRST SCREEN.
    You can update the dynamic table for example
    *wa_elements-status = 'C'.
    *modify <dyn_table> from wa_elements index row_id.
    now redisplay the updated grid.
    *CALL METHOD z_object->refresh_grid.
    *ENDFORM.
    *************Class ZCL_DOG*************
    CLASS zcl_dog DEFINITION.
    PUBLIC SECTION.
    METHODS:
      constructor
         IMPORTING
                      z_object TYPE REF TO zcl_dog,
       display_grid
         CHANGING
                      it_fldcat TYPE lvc_t_fcat,
           build_dynamic_structures
         CHANGING        it_fldcat TYPE lvc_t_fcat,
        change_title
         IMPORTING
                i_gridtitle  TYPE lvc_title,
         refresh_grid.
      PRIVATE SECTION.
       METHODS:
        on_user_command FOR EVENT before_user_command OF cl_gui_alv_grid
          IMPORTING       e_ucomm
                          sender,
        on_toolbar FOR EVENT toolbar OF cl_gui_alv_grid
          IMPORTING      e_object
                         e_interactive,
         on_dubbelklik FOR EVENT double_click OF cl_gui_alv_grid
          IMPORTING e_row
                    e_column
                    es_row_no,
        handle_data_changed
                 FOR EVENT data_changed OF cl_gui_alv_grid
                 IMPORTING er_data_changed,
        handle_data_changed_finished
                 FOR EVENT data_changed_finished OF cl_gui_alv_grid
                 IMPORTING e_modified
                           et_good_cells,
        verwerk
                IMPORTING program TYPE sy-repid,
        download_to_excel,
        dubbleklik
                IMPORTING
                     e_row  type  LVC_S_ROW
                     e_column   TYPE LVC_S_COL
                     es_row_no  type lvc_s_ROID
                     program type sy-repid,
         return_structure,
         create_dynamic_fcat
          EXPORTING       it_fldcat TYPE lvc_t_fcat,
          create_dynamic_table
          IMPORTING       it_fldcat TYPE lvc_t_fcat
          EXPORTING       dy_table  TYPE REF TO DATA.
    DATA:
        lr_rtti_struc    TYPE REF TO cl_abap_structdescr,        "RTTI
        zog              LIKE LINE OF lr_rtti_struc->components, "RTTI
        wa_it_fldcat     TYPE lvc_s_fcat,
        it_fldcat        TYPE lvc_t_fcat,
        dy_table         TYPE REF TO data,
        dy_line          TYPE REF TO data,
        struct_grid_lset TYPE lvc_s_layo,
        e_row            TYPE LVC_S_ROW,
        e_column         TYPE lvc_s_col,
        es_rowid         TYPE lvc_s_roid,
        grid_container1  TYPE REF TO cl_gui_custom_container,
        grid1            TYPE REF TO cl_gui_alv_grid,
        ls_layout        TYPE kkblo_layout,
        lt_fieldcat_wa   TYPE kkblo_fieldcat,
        l_mode           TYPE raw4,
        celltab          TYPE LVC_T_STYL,
        wa_celltab       TYPE lvc_s_styl,
        lt_fieldcat      TYPE kkblo_t_fieldcat,
       l_tabname         TYPE slis_tabname.
    TYPES:
       struc            LIKE  zog.
    DATA:
        zogt           TYPE TABLE OF struc.
       ENDCLASS.
    CLASS zcl_dog IMPLEMENTATION.
    METHOD constructor.
       CREATE OBJECT grid_container1
           EXPORTING
                   container_name = 'CCONTAINER1'.
        CREATE OBJECT  grid1
            EXPORTING
                  i_parent = grid_container1.
        SET HANDLER z_object->on_user_command for grid1.
        SET HANDLER z_object->on_toolbar for grid1.
        SET HANDLER Z_OBJECT->handle_data_changed_finished FOR grid1.
        SET HANDLER Z_OBJECT->on_dubbelklik FOR grid1.
        CALL METHOD grid1->register_edit_event
            EXPORTING
                    i_event_id = cl_gui_alv_grid=>mc_evt_enter.
    ENDMETHOD.
    METHOD refresh_grid.
      CALL METHOD cl_gui_cfw=>flush.
      CALL METHOD grid1->refresh_table_display.
    ENDMETHOD.
    METHOD on_dubbelklik.
    CALL METHOD me->dubbleklik
             EXPORTING
                     e_row  = e_row
                     e_column =  e_column
                     es_row_no = es_row_no
                     program  = sy-repid.
    break-point 1.
    ENDMETHOD.
    METHOD  handle_data_changed.
    Insert user code here if required
    this method is entered if user ENTERS DATA.
    ENDMETHOD.
    METHOD handle_data_changed_finished.
    Insert user code here if required
    Method entered here after data entry has finished.
    ENDMETHOD.
    METHOD return_structure.
      lr_rtti_struc ?= cl_abap_structdescr=>DESCRIBE_BY_DATA( <fs1> ).
      zogt[]  = lr_rtti_struc->components.
      ASSIGN zogt[] TO <fs2>.
      ENDMETHOD.
    METHOD create_dynamic_fcat.
        LOOP AT <fs2>  INTO zog.
          CLEAR wa_it_fldcat.
          wa_it_fldcat-fieldname = zog-name .
          wa_it_fldcat-datatype = zog-type_kind.
          wa_it_fldcat-inttype = zog-type_kind.
          wa_it_fldcat-intlen = zog-length.
          wa_it_fldcat-decimals = zog-decimals.
          wa_it_fldcat-coltext = zog-name.
          wa_it_fldcat-lowercase = 'X'.
          APPEND wa_it_fldcat TO it_fldcat .
          ASSIGN it_fldcat[] TO <field_catalog>.
          ENDLOOP.
           ASSIGN  it_fldcat[] TO <field_catalog>.
        ENDMETHOD.
    METHOD  download_to_excel.
    break-point 5.
    CALL FUNCTION  'LVC_TRANSFER_TO_KKBLO'
        EXPORTING
          it_fieldcat_lvc   = <field_catalog>
         is_layout_lvc     = m_cl_variant->ms_layout
           is_tech_complete  = ' '
        IMPORTING
          es_layout_kkblo   = ls_layout
          et_fieldcat_kkblo = lt_fieldcat.
    LOOP AT lt_fieldcat INTO lt_fieldcat_wa.
       CLEAR lt_fieldcat_wa-tech_complete.
        IF lt_fieldcat_wa-tabname IS initial.
           lt_fieldcat_wa-tabname = '1'.
           MODIFY lt_fieldcat FROM lt_fieldcat_wa.
        ENDIF.
        l_tabname = lt_fieldcat_wa-tabname.
    ENDLOOP.
    CALL FUNCTION 'ALV_XXL_CALL'
        EXPORTING
          i_tabname           = l_tabname
          is_layout           = ls_layout
          it_fieldcat         = lt_fieldcat
          i_title             = sy-title
        TABLES
          it_outtab           = <dyn_table>
        EXCEPTIONS
          fatal_error         = 1
          no_display_possible = 2
          others              = 3.
      IF  sy-subrc <> 0.
         message id sy-msgid type 'S' number sy-msgno
                with sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
        ENDIF.
    ENDMETHOD.
    METHOD create_dynamic_table.
    CALL METHOD cl_alv_table_create=>create_dynamic_table
        EXPORTING
             it_fieldcatalog = it_fldcat
          IMPORTING
             ep_table = dy_table.
    ENDMETHOD.
    METHOD build_dynamic_structures.
    CALL METHOD me->return_structure.
    CALL METHOD me->create_dynamic_fcat
       IMPORTING
         it_fldcat = it_fldcat.
    CALL METHOD me->create_dynamic_table
        EXPORTING
          it_fldcat = it_fldcat
        IMPORTING
          dy_table        = dy_table.
         ASSIGN dy_table->* TO <dyn_table>.
    CREATE DATA dy_line LIKE LINE OF <dyn_table>.
    ASSIGN dy_line->* TO <dyn_wa>.
    ENDMETHOD.
    METHOD display_grid.
      struct_grid_lset-edit = 'X'. "To enable editing in ALV
      struct_grid_lset-grid_title = 'Bulkwijzigingen inkoopprijzen'.
      struct_grid_lset-ctab_fname = 'T_CELLCOLORS'.
      struct_grid_lset-stylefname = 'CELLTAB'.
      CALL METHOD grid1->set_ready_for_input
          EXPORTING
               i_ready_for_input = '1'.
      CALL METHOD grid1->set_table_for_first_display
          EXPORTING
               is_layout       = struct_grid_lset
        CHANGING
               it_outtab       = <dyn_table>
               it_fieldcatalog = it_fldcat.
    ENDMETHOD.
    METHOD change_title.
      CALL METHOD grid1->set_gridtitle
       EXPORTING
       i_gridtitle =  i_gridtitle.
      ENDMETHOD.
    METHOD on_user_command.
      CASE e_ucomm.
          WHEN 'EXIT'.
            LEAVE PROGRAM.
         WHEN 'EXCEL'.
         CALL METHOD me->download_to_excel.
          WHEN 'SAVE'.
          WHEN 'VERW'.
          CALL METHOD me->verwerk
               EXPORTING
                  PROGRAM = SY-REPID.
      ENDCASE.
    ENDMETHOD.                    "on_user_command
    METHOD on_toolbar.
    User can add extra functionality by adding extra
    buttons if required. Functionality can also be simplified by removing buttons.
    DATA: ls_toolbar TYPE stb_button.
         CLEAR ls_toolbar.
         MOVE 0 TO ls_toolbar-butn_type.
         MOVE 'EXIT' TO ls_toolbar-function.
         MOVE SPACE TO ls_toolbar-disabled.
         MOVE icon_system_end TO ls_toolbar-icon.
         MOVE 'Click2Exit' TO ls_toolbar-quickinfo.
         APPEND ls_toolbar TO e_object->mt_toolbar.
         CLEAR ls_toolbar.
         MOVE  0 TO ls_toolbar-butn_type.
         MOVE 'SAVE' TO ls_toolbar-function.
         MOVE SPACE TO ls_toolbar-disabled.
         MOVE  icon_system_save TO ls_toolbar-icon.
         MOVE 'Save data' TO ls_toolbar-quickinfo.
         APPEND ls_toolbar TO e_object->mt_toolbar.
         CLEAR ls_toolbar.
         MOVE  0 TO ls_toolbar-butn_type.
         MOVE 'EDIT' TO ls_toolbar-function.
         MOVE  SPACE TO ls_toolbar-disabled.
         MOVE  icon_toggle_display_change TO ls_toolbar-icon.
         MOVE 'Edit data' TO ls_toolbar-quickinfo.
         MOVE  'EDIT' TO ls_toolbar-text.
         APPEND ls_toolbar TO e_object->mt_toolbar.
         CLEAR ls_toolbar.
         MOVE  0 TO ls_toolbar-butn_type.
         MOVE 'VERW' TO ls_toolbar-function.
         MOVE  SPACE TO ls_toolbar-disabled.
         MOVE   icon_businav_process to ls_toolbar-icon.
         MOVE 'Verw.' TO ls_toolbar-quickinfo.
         MOVE  'VERW' TO ls_toolbar-text.
         APPEND ls_toolbar TO e_object->mt_toolbar.
          CLEAR ls_toolbar.
         MOVE  0 TO ls_toolbar-butn_type.
         MOVE 'EXCEL' TO ls_toolbar-function.
         MOVE  SPACE TO ls_toolbar-disabled.
         MOVE  icon_xxl TO ls_toolbar-icon.
         MOVE 'Excel' TO ls_toolbar-quickinfo.
         MOVE  'EXCEL' TO ls_toolbar-text.
         APPEND ls_toolbar TO e_object->mt_toolbar.
       ENDMETHOD.
       METHOD verwerk.
          PERFORM verwerk IN PROGRAM (program).
          LEAVE PROGRAM.
      ENDMETHOD.
      METHOD dubbleklik.
      PERFORM dubbleklik IN PROGRAM (program)
        USING
            e_row
            e_column
            es_row_no.
      ENDMETHOD.
    ENDCLASS.
    Cheers
    Jimbo

    Hi Dinu,
    Before analysing ALV, please cross check the behaviour of the calling program.
    Is the control really going to the application server when you do all the above process?
    If so, when user makes some changes are they saved in the data base / affected the internal table which you are using for ALV?
    Regards
    Surya.

  • SWING GUI blockes when doing a DB action with microsoft nativ JDBC driver

    hi,
    in a bigger project i have the problem that if i perform a DB action the GUI is blocked. It does not matter if i do the DB Action in invokeLater or
    in a SwingWorker or in a new Thread if i call the DB Action and i move another window over my window it is not refreshed.
    normally the GUI shouln�t be blocked if i use invokeLater. maybe it
    has something to do that i use the native DB driver? I am using JDK
    1.4. has anyone ever encounterd the same problem?
    alex
    package swingtest;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.sql.*;
    public class GUIProblem extends JDialog {   
    // this method does a simple DB call to generate some load
    public void doMyDBCall()
    try {
    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
    Connection con = DriverManager.getConnection ("jdbc:microsoft:sqlserver://abgvdr71:1433;databasename=v52li;","sa","");
    Statement question0 = con.createStatement();
    ResultSet rs0=null;
    rs0 = question0.executeQuery("select * from intercept_24");
    boolean more=rs0.next();
    while (more) {    more=rs0.next();}
    catch (Exception sql)
    { sql.printStackTrace(); }
    public void doItinvokeLater()
    SwingUtilities.invokeLater(new Runnable(){    public void run(){       
    doMyDBCall();     
    public void doItSwingWorker()
    SwingWorker worker = new SwingWorker() {
    public Object construct() {
    System.out.println("worker start");
    doMyDBCall();
    return null;
    worker.start();
    System.out.println("finished .....");
    Object view = (Object) worker.get();
    public GUIProblem (){
    super((JFrame)null,"",true);
    JButton button = new JButton("do it");
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event)
    // calls it direct -> GUI blocked
    //doMyDBCall();
    // with invoke later -> GUI blocked
    //doItinvokeLater();
    // with the swingWorker -> GUI also blocks
    doItSwingWorker();     
    getContentPane().add(button);
    setSize(200,200);
    setVisible(true);
    public static void main(String [] args)
    {  new GUIProblem(); }
    }

    The invokeLater runs the Runnable in the event thread, so yes, that will block your GUI. You ALMOST got the SwingWorker right. DB call in the construct() method -- the construct() method executes outside the event thread, the finished() method executes in the event thread. The only problem is, you did a worker.get() method in your event thread (right after worker.start(0, and get() blocks until result is ready from construct() -- so, bingo, you're jammed up waiting in you event thread.

  • Why do I get the following exception when I press the cancel buuton?

    My code is not complete as I am stubbing my code. Can someone tell me why i get the following exception
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
            at Phonebook.createNew(Phonebook.java:244)
            at Phonebook.actionPerformed(Phonebook.java:222)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:19
    95)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.jav
    a:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel
    .java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
    istener.java:236)
            at java.awt.AWTEventMulticaster.mouseReleased(AWTEventMulticaster.java:2
    72)
            at java.awt.Component.processMouseEvent(Component.java:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThre
    ad.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.
    java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThre
    ad.java:173)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)in the following code whenever I press the cancel button in the part of code that tests fro when a user clicks the create button.
         Filename:     ContactsListInterface.java
         Date:           16 March 2008
         Programmer:     Yucca Nel
         Purpose:     Provides a GUI for entering names and contact numbers into a telephone directory.
                        Also allows options for searching for a specific name and deleting of data from the record
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import java.io.*;
    import java.util.*;
    import java.text.*;
    public class Phonebook extends JFrame implements ActionListener
    { //start of class
         // construct fields, buttons, labels,text boxes, ArrayLists etc
         JTextPane displayPane = new JTextPane();
         JLabel listOfContacts = new JLabel("List Of Contacts");               // creates a label for the scrollpane
         JButton createButton = new JButton("Create");
         JButton searchButton = new JButton("Search");
         JButton modifyButton = new JButton("Modify");
         JButton deleteButton = new JButton("Delete");
         ArrayList fNameList = new ArrayList();
         ArrayList sNameList = new ArrayList();
         ArrayList hList = new ArrayList();
         ArrayList wList = new ArrayList();
         ArrayList cList = new ArrayList();
         public String name, surname, home, work, cell;
         // create an instance of the ContactsListInterface
         public Phonebook()
         { // start of cli()
              super("Phonebook Interface");
         } // end of cli()
         public JMenuBar createMenuBar()
         { // start of the createMenuBar()
              // construct and populate a menu bar
              JMenuBar mnuBar = new JMenuBar();                    // creates a menu bar
              setJMenuBar(mnuBar);
              JMenu mnuFile = new JMenu("File",true);               // creates a file menu in the menu bar which is visible
                   mnuFile.setMnemonic(KeyEvent.VK_F);
                   mnuFile.setDisplayedMnemonicIndex(0);
                   mnuFile.setToolTipText("File Options");
                   mnuBar.add(mnuFile);
              JMenuItem mnuFileExit = new JMenuItem("Save And Exit");     // creates an exit option in the file menu
                   mnuFileExit.setMnemonic(KeyEvent.VK_X);
                   mnuFileExit.setDisplayedMnemonicIndex(1);
                   mnuFileExit.setToolTipText("Close Application");
                   mnuFile.add(mnuFileExit);
                   mnuFileExit.setActionCommand("Exit");
                   mnuFileExit.addActionListener(this);
              JMenu mnuEdit = new JMenu("Edit",true);               // creates a menu for editing options
                   mnuEdit.setMnemonic(KeyEvent.VK_E);
                   mnuEdit.setDisplayedMnemonicIndex(0);
                   mnuEdit.setToolTipText("Edit Options");
                   mnuBar.add(mnuEdit);
              JMenu mnuEditSort = new JMenu("Sort",true);          // creates an option for sorting entries
                   mnuEditSort.setMnemonic(KeyEvent.VK_S);
                   mnuEditSort.setDisplayedMnemonicIndex(0);
                   mnuEdit.add(mnuEditSort);
              JMenuItem mnuEditSortByName = new JMenuItem("Sort By Name");          // to sort entries by name
                   mnuEditSortByName.setMnemonic(KeyEvent.VK_N);
                   mnuEditSortByName.setDisplayedMnemonicIndex(8);
                   mnuEditSortByName.setToolTipText("Sort entries by first name");
                   mnuEditSortByName.setActionCommand("Name");
                   mnuEditSortByName.addActionListener(this);
                   mnuEditSort.add(mnuEditSortByName);
              JMenuItem mnuEditSortBySurname = new JMenuItem("Sort By Surname");     // to sort entries by surname
                   mnuEditSortBySurname.setMnemonic(KeyEvent.VK_R);
                   mnuEditSortBySurname.setDisplayedMnemonicIndex(10);
                   mnuEditSortBySurname.setToolTipText("Sort entries by surname");
                   mnuEditSortBySurname.setActionCommand("Surname");
                   mnuEditSortBySurname.addActionListener(this);
                   mnuEditSort.add(mnuEditSortBySurname);
              JMenu mnuHelp = new JMenu("Help",true);                    // creates a menu for help options
                   mnuHelp.setMnemonic(KeyEvent.VK_H);
                   mnuHelp.setDisplayedMnemonicIndex(0);
                   mnuHelp.setToolTipText("Help options");
                   mnuBar.add(mnuHelp);
              JMenuItem mnuHelpHelp = new JMenuItem("Help");          // creates a help option for help topic
                   mnuHelpHelp.setMnemonic(KeyEvent.VK_P);
                   mnuHelpHelp.setDisplayedMnemonicIndex(3);
                   mnuHelpHelp.setToolTipText("Help Topic");
                   mnuHelpHelp.setActionCommand("Help");
                   mnuHelpHelp.addActionListener(this);
                   mnuHelp.add(mnuHelpHelp);
              JMenuItem mnuHelpAbout = new JMenuItem("About");     // creates a about option for info about api
                   mnuHelpAbout.setMnemonic(KeyEvent.VK_T);
                   mnuHelpAbout.setDisplayedMnemonicIndex(4);
                   mnuHelpAbout.setToolTipText("About this program");
                   mnuHelpAbout.setActionCommand("About");
                   mnuHelpAbout.addActionListener(this);
                   mnuHelp.add(mnuHelpAbout);
              return mnuBar;
         } // end of the createMenuBar()
         // create the content pane
         public Container createContentPane()
         { // start of createContentPane()
              //construct and populate panels and content pane
              JPanel labelPanel = new JPanel(); // panel is only used to put the label for the textpane in
                   labelPanel.setLayout(new FlowLayout());
                   labelPanel.add(listOfContacts);
              JPanel displayPanel = new JPanel();// panel is used to display all the contacts and thier numbers
                   setTabsAndStyles(displayPane);
                   displayPane = addTextToTextPane();
                   displayPane.setEditable(false);
              JScrollPane scrollPane = new JScrollPane(displayPane);
                   scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); // pane is scrollable vertically
                   scrollPane.setWheelScrollingEnabled(true);// pane is scrollable by use of the mouse wheel
                   scrollPane.setPreferredSize(new Dimension(400,320));
              displayPanel.add(scrollPane);
              JPanel workPanel = new JPanel();// panel is used to enter, edit and delete data
                   workPanel.setLayout(new FlowLayout());
                   workPanel.add(createButton);
                        createButton.setToolTipText("Create a new entry");
                        createButton.addActionListener(this);
                   workPanel.add(searchButton);
                        searchButton.setToolTipText("Search for an entry by name number or surname");
                        searchButton.addActionListener(this);
                   workPanel.add(modifyButton);
                        modifyButton.setToolTipText("Modify an existing entry");
                        modifyButton.addActionListener(this);
                   workPanel.add(deleteButton);
                        deleteButton.setToolTipText("Delete an existing entry");
                        deleteButton.addActionListener(this);
              labelPanel.setBackground(Color.red);
              displayPanel.setBackground(Color.red);
              workPanel.setBackground(Color.red);
              // create container and set attributes
              Container c = getContentPane();
                   c.setLayout(new BorderLayout(30,30));
                   c.add(labelPanel,BorderLayout.NORTH);
                   c.add(displayPanel,BorderLayout.CENTER);
                   c.add(workPanel,BorderLayout.SOUTH);
                   c.setBackground(Color.red);
              // add a listener for the window closing and save
              addWindowListener(
                   new WindowAdapter()
                        public void windowClosing(WindowEvent e)
                             int answer = JOptionPane.showConfirmDialog(null,"Are you sure you would like to save all changes and exit?","File submission",JOptionPane.YES_NO_OPTION);
                             if(answer == JOptionPane.YES_OPTION)
                                  System.exit(0);
              return c;
         } // end of createContentPane()
         protected void setTabsAndStyles(JTextPane displayPane)
         { // Start of setTabsAndStyles()
              // set Font style
              Style fontStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
              Style regular = displayPane.addStyle("regular", fontStyle);
              StyleConstants.setFontFamily(fontStyle, "SansSerif");
              Style s = displayPane.addStyle("bold", regular);
              StyleConstants.setBold(s,true);
         } // End of setTabsAndStyles()
         public JTextPane addTextToTextPane()
         { // start of addTextToTextPane()
              Document doc = displayPane.getDocument();
              try
              { // start of tryblock
                   // clear previous text
                   doc.remove(0,doc.getLength());
                   // insert titles of columns
                   doc.insertString(0,"NAME\tSURNAME\tHOME NO\tWORK NO\tCELL NO\n",displayPane.getStyle("bold"));
              } // end of try block
              catch(BadLocationException ble)
              { // start of ble exception handler
                   System.err.println("Could not insert text.");
              } // end of ble exception handler
              return displayPane;
         } // end of addTextToTextPane()
         // code to process user clicks
         public void actionPerformed(ActionEvent e)
         { // start of actionPerformed()
              String arg = e.getActionCommand();
              // user clicks create button
              if(arg.equals("Create"))
                   createNew();
              if(arg.equals("Search"))
              if(arg.equals("Modify"))
              if(arg.equals("Delete"))
              if(arg.equals("Exit"))
         } // end of actionPerformed()
         // method to create a new contact
         public void createNew()
         { // start of create new contact()
              name = JOptionPane.showInputDialog(null,"Please enter the new contacts first name or press cancel to exit.");
              if(name == null)     finish();                         // if user clicks cancel
              if(name.length() <=0)
                   JOptionPane.showMessageDialog(null,"You did not enter a valid name.\nPlease make sure you enter data correctly.","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();                                   // To return to the create method
              surname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname or press cancel to exit.");
              if(surname == null)     finish();                         // if user clicks cancel
              if(surname.equals(""))
                   int answer = JOptionPane.showConfirmDialog(null,"You did not enter a surname.\nAre you sure you wish to leave the surname empty?","No data entered",JOptionPane.YES_NO_OPTION);   // Asks if data was valid
                   if(answer == JOptionPane.NO_OPTION)
                        surname = JOptionPane.showInputDialog(null,"Please enter the new contacts surname.");
              home = JOptionPane.showInputDialog(null,"Please enter the new contacts home number or press cancel to exit.");
              if(home == null)   finish();                    // if user clicks cancel
              work = JOptionPane.showInputDialog(null,"Please enter the new contacts work number or press cancel to exit.");
              if(work == null)     finish();                    // if user clicks cancel
              cell = JOptionPane.showInputDialog(null,"Please enter the new contacts cell number or press cancel to exit.");
              if(cell == null)     finish();                    // if user clicks cancel
         } // end of create new contact()
         // method to close applicatin
         public void finish()
         // method to search a contact
         public static void main(String[] args)
         { // start of main()
              // Set look and feel of interface
              try
              { // start of try block
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
              } // end of try block
              catch(Exception e)
              { // start of catch block
                   JOptionPane.showMessageDialog(null,"There was an error in setting the look and feel of this application","Error",JOptionPane.INFORMATION_MESSAGE);
              } // end  of catch block
              Phonebook p = new Phonebook();
              p.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              p.setJMenuBar(p.createMenuBar());
              p.setContentPane(p.createContentPane());
              p.setSize(520,500);
              p.setVisible(true);
              p.setResizable(false);
         } // end of main()
    } //end of class

    Yucca wrote:
    Line 244 is where I test for if the user actuallu entered a String at all. Is there an alternative way of writing that code?
    if(name.length() <=0)
                   JOptionPane.showMessageDialog(null,"You did not enter a valid name.\nPlease make sure you enter data correctly.","Error",JOptionPane.ERROR_MESSAGE);
                   createNew();                                   // To return to the create method
    Change:
    if(name == null)     finish();     To
    if(name == null) {
        finish();
        return;
    }

  • Problem seeing a jframe components

    Hello,
    My problem is this. I have a main jframe. Now on my main jframe i have to do a time expensive procedure called refresh(); While this procedure is running i want to display a message in a JWindow that says "Please wait". Problem is that no matter what the JWindow object won't show its components until the procedure refresh is done. That means of course that my JWindow is pointless.
    So I tried with swingworker to create a thread that runs the procedure refresh(). But that doesn't seem to work.
    final please_wait ff= new please_wait();//this is my JWindow
    final SwingWorker worker = new SwingWorker() {
    public Object construct() {
    Runnable doWorkRunnable = new Runnable() {
    public void run() {   refresh();//this is the time consumming procedure }
    SwingUtilities.invokeLater(doWorkRunnable);
    return "s"; //return value not used by this program
    //Runs on the event-dispatching thread.
    public void finished() {
    ff.dispose(); ///here i destroy the JWindow because the time consuming procedure is over
    worker.start();

    I believe you have misunderstood the use of the invokeLater() method. It isn't used to execute time consuming tasks. You would use invokeLater() to put a GUI operation on the event dispatcher thread from a thread you have spawned off to execute outside of the event dispather thread i.e. from the thread you will use to execute your time consuming task (Since all GUI operations should be executed from the event dispatcher thread).
    Your steps of actions here would be (assuming what ever kicks off your time consuming task happens from an event listener...like a button press):
    1) Construct and display our JWindow
    2) Spawn a new thread with your time consuming task in it.
    3) When your time consuming task is done remove your JWindow by putting a call to its dispose() method in a Runnable object which you pass to SwingUtilities.invokeLater(Runnable).
    You can replace steps 2 and 3 with SwingWorker if you prefer (and it appears you do) since it encapulates this functionality. SwingWorker's finished method is where you would dispose of your JWindow and since the operations in the finished method are already executed on the event dispather thread you don't need to worry about invokeLater.

  • Captivate 7 - The Exit Bug and a Solution

    Hey Everyone,
    I wanted to take a second and share some good information I found in regards to SCORM and the Exit functionality in Captivate 7. Below is the blog post that shows how to make the Adobe Exit functionality "SCORM Compliant" and solved my issues when uploading my project and getting them to exit. Hope this helps
    Captivate 7, Exit Bug and a Solution
    Several of our Inquisiq R3 users have alerted us to the fact that courses developed with Captivate 7 published to HTML5 and SWF do not close properly when using the “Exit” button, forcing the user instead to manually close the browser window by clicking the “X” in the upper-right corner of the browser window.
    Through our investigation into this issue, it appears that the process that Adobe has implemented when clicking the “Exit” button is to simply attempt to close the content window and rely on the LMS to capture and commit the session data. Nowhere did we see that the content was actually calling the “LMSFinish()” [SCORM 1.2] or “Terminate()” [SCORM 2004] methods in the LMS’s SCORM API to commit the lesson data to the LMS as required by the SCORM specification.
    Adobe uses their own defined function, “DoCPExit,” to close a lesson window.  This method contains a “window.close()” call and additional logic to “bubble up” the command through the frame parents (if they exist and also contain the “DoCPExit” method - presumably because they would also be Adobe-published content files within your package).
    There are several flaws to this approach.
    By not calling “LMSFinish()” or “Terminate(),” the content is, by definition, not SCORM conformant.  Part of the minimum requirements for conformance are that the content calls the initialization method “LMSInitialize()” in SCORM 1.2 or “Initialize()” in SCORM 2004 and the  termination method “LMSFinish()” in SCORM 1.2 or “Terminate()” in SCORM 2004. The LMS is not required to clean up the data left behind when the content fails to make this call. So if your LMS doesn’t take this additional step (of setting ‘LMSFinish’ or ‘Terminate’ if the lesson does not), your data will be completely lost…i.e. no record of you taking the lesson will be recorded.
    The call to close the browser window will fail if the LMS is running the content within a frame or iframe. Since the SCORM specification allows content to be launched in frames or iframes (in addition to new browser windows), lessons need to be able to accommodate this scenario. Even with the “bubble up” logic, once the call reaches the top most content window, and the next parent window in line is the LMS container page, the call will no longer be passed and a “window.close()” call will be fired within the framed page.  When this call is made, nothing will happen as a framed page cannot close the browser window using this command. Through our investigation, we’ve learned that at least 4 other well-known LMSs have experienced this particular issue.
    Ironically, the solution that we’ve discovered is not only SCORM conformant, but also very simple and follows what we would consider to be SCORM “best practices”.  The foundation and logic for the solution is already contained within the published Captivate files (and it is the same solution whether you publish to SCORM 1.2 or SCORM 2004).
    We simply modify the “DoCPExit” method that is contained within the “Utilities.js” file to call the “Finish()” method.  Just replace all the code appearing between the “{“and the “}” as you see here:
    function DoCPExit(){     Finish();
    The “Finish()” method that we have inserted is, as mentioned, already contained within the published Captivate files and contains the logic to properly set the exit parameters and correctly identify whether the content is SCORM 1.2 or SCORM 2004; it will therefore make a call to the correct close method (“LMSFinish()” or “Terminate()”) accordingly.  Once the LMS has received this command, it should take care of removing the content properly, leaving no need for any “bubble-up” logic or window close calls within the content code.
    Overall, if the lessons you develop with Captivate 7 work as expected and required in your LMS, there is no need to implement this change. However, if your lesson’s Exit button is not working as it should, and/or you are losing progress and status data when closing the lesson, the fix described here should resolve all those issues.
    The biggest issue here is that since we’re changing published code, the next time you update and publish that same Captivate project, you have to remember to change that published function code AGAIN, as Captivate will simply publish the default code.
    We have been in touch with the Captivate team to discuss this problem and they are investigating. We would hope a patch to address this flaw would be released in the near future
    All credit of this fix goes to http://blog.icslearninggroup.com/2013/10/captivate-7-exit-bug-and-solution.html

    Try clearing out your project cache (Preferences > General > Clear Cache) then republish using the option to Force Republish All Slides.
    If that doesn't resolve the issue, you may be seeing the early stages of project file corruption.  Check the suggestions in this post about troubleshooting issues where you may need to copy all slides to a new blank project shell to try and strip out corruption:
    http://www.infosemantics.com.au/adobe-captivate-troubleshooting/basic-troubleshooting-tech niques

  • Using threads (SwingWorker) to update JTree component

    Hi,
    Im having a problem trying to update a JTree component (adding child nodes to an existing node) using threads. Im using the SwingWorker3 class (http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html) for threading.
    When the user selects a node for expansion, the logic for fetching the children of the selected node is executed under the construct() method of SwingWorker.
    Once this data is obtained, the job of adding the children to the selected node is done in the finished() method which runs on the event-dispatch thread as per documentation of SwingWorker3.
    The problem Im facing is that even though the data for the children is obtained and the finished() method executes and adds the children to the selected node, they are not visible in the UI.
    If anybody knows how this can be resolved, please let me know. Any help/pointers would be greatly appreciated.
    Rgds
    Sridhar

    I added the tree.updateUI() method call in the finished() method. This renders the children (Yipee!).
    But now I have a new problem. If I collapse and again expand a node, I get a NPE. (I see all the child nodes but a exception is still thrown) The exception happens after my treeWillExpand() and treeExpanded() method implementations. So no probs in my code.
    If you know of a solution, pleeease let me know.
    TIA
    Sridhar
    Exception occurred during event dispatching:
    java.lang.NullPointerException
    at javax.swing.plaf.basic.BasicTreeUI.updateSize(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.toggleExpandState(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.handleExpandControlClick(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI.checkForClickInExpandControl(Unknown Source)
    at javax.swing.plaf.basic.BasicTreeUI$MouseHandler.mousePressed(Unknown Source)
    at java.awt.AWTEventMulticaster.mousePressed(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

  • GZIPInputStream

    hi everyone,
    I'm having problems with GZIPInputStream. I wanted to send compressed data from the server to a client, using UDP, so I gziped data before sending it.
    The problem is on the client side. I'm using this code to uncompress the data:
    DatagramSocket ds = new DatagramSocket(55555);
    DatagramPacket packet = new DatagramPacket(new byte[2048], 2048);
    while (running) {
    ds.receive(packet);
    byte[] b = new byte[ packet.getLength() ];
    System.arraycopy(packet.getData(), 0, b, 0, b.length);
    ByteArrayInputStream bin = new ByteArrayInputStream(b, 0, b.length);
    GZIPInputStream gin = new GZIPInputStream( bin );
    StringBuffer sb = new StringBuffer(128);
    byte bt;
    while ( (bt = (byte) gin.read())!=-1 ) { <=== EXCEPTION!
    sb.append( (char) bt );
    System.out.println(sb.toString());
    This code throws the following Exception:
    java.io.EOFException: Unexpected end of ZLIB input stream
    at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:211)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:133)
    at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:86)
    at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:104)
    Does anyone have an idea?
    thanks a lot for your help!
    Luis Javier

    Without seeing the code you used to gzip your data in the first place, my best offering is that you need to call the finish() method of the GZIPOutputStream once you've finished writing your data out. In fact, you should probably flush your stream(s) before calling finish().
    Hope this helps...
    Shaun

  • Make a particular row editable in ALVgrid oo

    hi all,
           i have a hotspot in my alv,when hotspot click haapen the particular row should b changed to editable, i have done till the hotspotclick event and the particular row could be poppulated , how it can be changed to editable on that particular row....
    thanks

    Hi,
        In order to make a row editable, it is required to implement an event handler class. It is required to implement the following events:
    CLASS lcl_event_handler DEFINITION .
    PUBLIC SECTION .
    METHODS:
    *--Controlling data changes when ALV Grid is editable
    handle_data_changed
    FOR EVENT data_changed OF cl_gui_alv_grid
    IMPORTING er_data_changed
    *--To be triggered after data changing is finished
    handle_data_changed_finished
    FOR EVENT data_changed_finished OF cl_gui_alv_grid
    IMPORTING e_modified
    ENDCLASS.
    CLASS lcl_event_handler IMPLEMENTATION .
    *--Handle Data Changed
    METHOD handle_data_changed .
    PERFORM handle_data_changed USING er_data_changed .
    ENDMETHOD.
    *--Handle Data Changed Finished
    METHOD handle_data_changed_finished .
    PERFORM handle_data_changed_finished USING e_modified .
    ENDMETHOD .
    ENDCLASS .
    DATA gr_event_handler TYPE REF TO lcl_event_handler .
    *--Creating an instance for the event handler
    CREATE OBJECT gr_event_handler .
    SET HANDLER gr_event_handler->handle_data_changed FOR gr_alvgrid .
    SET HANDLER gr_event_handler->handle_data_changed_finished
    FOR gr_alvgrid .
    Please search the forum: You will get a lot examples
    Regards,
    Tanmoy
    Edited by: Tanmoy Mondal on Aug 5, 2011 1:45 PM

  • How to access another java process?

    I run two java process, A and B, any possiblity to access process A from process B?
    Process A and B are started with class's main method.
    Thanks.

    masijade. wrote:
    georgemc wrote:
    laguna8 wrote:
    Socket will not be appropriate for my case.
    My case is: I write a document editor (just like UltraEdit), after starting the editor, there is one process running, then I right click a file and choose to open that file with my editor, it starts another editor process. What I want now is just to open that file with the editor that has already run.Don't see why sockets aren't appropriate there. Why did you dismiss them?Because he wants a single pre-finished method call answer, maybe? ;-)Teh Codez!! Indeed. It's pretty obvious that there's an entire subsection of forum users who automatically dismiss any reply which doesn't include code. If we produce an exhaustive list of all the methods by which IPC can be achieved, however archaic, he'll dismiss the lot, and then spend the rest of his life pondering this simple problem

  • Can Someone Explain the order of things Using Swingworker?

    Hi:
    Can someone explain very clearly the order of things using Swingworker? Please do not refer the SUN tutorials. I am totally dead in the water with a very large application and the order of things is not sensible. Also, if the worker thread is too long, the GUI gets updated, but my progress bar (killed right after in the finished method) remains running in some instances only.
    Can someone explain any debugging methods for thread work?
    I am a veteran programmer of 19 years and this one's got me. The event dispatch thread returns immediate, the GUI responds well, but the progress bar setVisible(false); ... just after in the finished() method (on Event Dispatch thread) does not go away, continues running, only on very long (large query) work. I'm truly stumped. I have successful applications of the Swingworker use, the progress bar, and everything works fine. Not this one.
    Debugging threads is what I need. Or some tool that visually shows threads as the program runs.
    Thanks for any help,
    PiratePete

    Thanks. I guess I should count my blessings when using free stuff. But I have been impressed with what the J2SDK has to offer. I have been writing a complicated application that I am going to market and most of my problems have been "design" in nature.
    Thanks again,
    PiratePete

  • Trouble from the beginning

    Hello all,
    Just starting this program and allready have compile errors that I don't understand if you could enlighten me as to why i am getting these that would be highly obliged.
    Thanks again in advance
    Here are the errors:
    A:\Chapter04\MyType.java:14: <identifier> expected
         public class static void main(String[] args)
    ^
    A:\Chapter04\MyType.java:34: '{' expected
    ^
    A:\Chapter04\MyType.java:35: '}' expected
    ^
    3 errors
    Tool completed with exit code 1
    And my code so far
    import java.io.*;
    import javax.swing.JOptionPane;
    public class MyType
         public class static void main(String[] args)
              //Declare variables
              String strChoice, strTryString, strTryInt, strTryDouble;
              int choice, tryInt;
              double tryDouble;
              boolean done = false;
              String answer = JOptionPane.showInputDialog(null, "What's My Type\n\n1) String\n2) Integer\n3) double\4) Quit the program");
              if (answer == null) finish();
              choice = Integer.parseInt(answer);
              return choice;
         // The finish method ends the program.
         public static void finish()
              System.exit(0);

    Please read this tutorial about class creation. Your errors are basic and you apparently don't understand what you're doing, so just correcting them for you does not seem to be a solution of value.
    http://java.sun.com/docs/books/tutorial/java/javaOO/classes.html
    Two hints - the errors relate to a bad method statement, and look at brackets.

  • Problem with starting more than one SwingWorker

    Hello
    I wonder if anyone could tell me if there are known problems with starting more than one SwingWorker thread at once?
    In response to an action the user performs, I need to obtain several lists of things from the server. This includes a couple of server-calls, and I want to do the server calls in a thread outside the awt-event thread. So I start a couple of SwingWorker-threads. This works fine sometimes, but not always. Sometimes code in some of the SwingWorkers finished method does not update the ui. I can see that the correct calls are made, but the ui is still not updated correctly. The problem seems to be related to the sequence of when the different thread are finished. For instance, if the sequence is like this:
    SwingWorker1.construct
    SwingWorker2.construct
    SwingWorker1.finished
    SwingWorker2.finished
    Things go fine, but if the sequence is:
    SwingWorker1.construct
    SwingWorker1.finished
    SwingWorker2.construct
    SwingWorker2.finished
    the ui-updates in SwingWorker1.finished is not done correctly.
    Can anyone help me with this?

    This is the point:
    In one SwingWorker thread you have 1 construct method, and 1 finish method - which are both invoked once.
    Therefore you only have one opportunity to update the gui in that thread. This forces you to use many threads if you want regular updates, which I try to avoid.
    Therefore, the solution!
    Have a loop in the construct method that executes the algorithm accordingly, updating the gui accordingly at regular times, maintaining just the 1 thread - becomes easier and nicer for the programmer and the JVM.
    The finish method in this case is to update the gui when all iterations are finished.
    There is nothing wrong with this. Just because you have a finish method that is called in the event-dispatching thread doesn't mean that all your update code must be in there.
    What you MUST ensure is that ALL your update code is executed in the event-dispatching thread, that is the most important thing. After all, SwingWorker is just a helper class, not the gospel template of how to update a gui.

Maybe you are looking for

  • MBA 11 (2013) pinch zoom does not work after some time, how to fix it ?

    Recently I purchased MBA 11 (2013) model ( 4GB ram & 1.3 Ghz dual core). Although I use iPhone 5 & iPad 4 but never used mac. So when I found the track pad is capable of pinch zoom(along with other gesture) I was excited. But later I found after open

  • Why Cyprus is not included in "Unlimited Europe" s...

    Dear Sir or Madam, I am user of Skype the last 2 and half years having an "Unlimited Europe" Subscription. 1) Today I discovered that  calls to Cyprus are not included in my subscription. I would like to know why you use the name "Unlimited Europe" 

  • Can't Create Invoice for PO

    SRM 7.0 Support Pack 9, Extended Classic: When attempting to create an invoice in SRM, we get error message "Purchase order contains no items for invoicing". The purchase order is in approved status and shows up in R3 (4.7).  Making it even more conf

  • Class properties of decedent class access scope error

    There seems to be what I consider a bug in the implementation of LV 2010 property nodes. If parent has a property folder with read and write accessors and child has a property folder overriding only one of the accessors, then the non-overridden prope

  • How to distinguish backing bean method invoker like struts *.do

    I want to monitor request and response time of application via access log of httpd . But the urls are the same in one backing bean. how should i do about this?