JPanel formatting

After succesfully coding a couple of panels to show correctly in my frame, I continued to develop the menu until the formatting for one of my menus reset itself. I'm not sure what happened, and if I message out the things I've changed it still doesn't format correctly. Basically the menu consists of a frame, with each menu as a smaller sized panel in the middle of the frame. The EquipPanel now resizes itself to take over the entire frame, rather than just be a smaller box inside the frame. Any help would be great, if you can spot the code or even suggest another plan of attack to build the menu. Here's the code:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class NecMenu implements ActionListener
    Font            f;
    Font            f2;
    Dimension       maxSize;
    Container       c;
    JLabel          title;
    JLabel          sign;
    JPanel          currentPanel;
    JPanel          mainPanel;
    JPanel          equipPanel;
    JPanel          gangPanel;   
    JButton         viewGangs;
    JButton         viewEquip;
    JButton         viewMain;
    JFrame          frame;
    int             titwid;
    public NecMenu()
        mainPanel   = new MainPanel();
        equipPanel  = new EquipPanel();
        gangPanel   = new GangPanel();
        title       = new JLabel( "Title", JLabel.CENTER );
        f           = new Font( "Lucida Sans", 1, 30 );
        viewGangs   = new JButton( "View Gangs" );
        viewEquip   = new JButton( "View Equipment" );
        viewMain    = new JButton( "Main Menu" );
        sign        = new JLabel( "Signature" );
        f2          = new Font( "Lucida Sans", 2, 14 );
        title.setFont( f );       
        sign.setFont( f2 );
        runMenu();
    void addComponentsToPane(Container pane)
        Dimension size = title.getPreferredSize();
        currentPanel = mainPanel;
        pane.add( title );
        pane.add( sign );
        pane.add( viewMain );
        mainPanel.setBorder( new LineBorder( Color.black, 3 ) );
        mainPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
        equipPanel.setBorder( new LineBorder( Color.black, 3 ) );
        equipPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
        gangPanel.setBorder( new LineBorder( Color.black, 3 ) );
        gangPanel.setBounds( 10, 46, frame.getWidth() - 20 - 6, 490 );
        pane.add( mainPanel );
        pane.add( gangPanel );
        pane.add( equipPanel );
        gangPanel.setVisible( false );
        equipPanel.setVisible( false );
        title.setBounds( ( frame.getWidth() - size.width ) / 2, 5, size.width, size.height );
        size = sign.getPreferredSize();
        sign.setBounds( 780 - size.width, 540, size.width, size.height );
        viewGangs.setBounds( 250, 200, 300, 30 );
        viewEquip.setBounds( 250, 300, 300, 30 );
        viewMain.setBounds( 250, 538, 300, 28 );
        viewGangs.addActionListener( this );
        viewEquip.addActionListener( this );
        viewMain.addActionListener( this );
        mainPanel.add( viewGangs );
        mainPanel.add( viewEquip );
    void createAndShowGUI()
        frame = new JFrame( "Nec" );
        frame.setSize( 800, 600 );
        JFrame.setDefaultLookAndFeelDecorated( true );
        frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        addComponentsToPane( frame.getContentPane() );
        frame.setVisible( true );
    void runMenu()
        javax.swing.SwingUtilities.invokeLater( new Runnable()
            public void run()
                createAndShowGUI();
    public void actionPerformed( ActionEvent a )
        Object source = a.getSource();
        if ( source == viewGangs )
            changePanel( gangPanel );
        else if ( source == viewEquip )
            changePanel( equipPanel );
        else if ( source == viewMain )
            changePanel( mainPanel );
    void changePanel( JPanel panel )
        currentPanel.setVisible( false );
        panel.setVisible( true );
        currentPanel = panel;
}and EquipPanel
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
import javax.swing.JComponent.*;
public class EquipPanel extends JPanel implements ChangeListener, ActionListener
    EquipPanel[]    tabs;
    String[]        tabNames;
    JTabbedPane     pane;
    Font            f;
   EquipPanel()
        int i;
        tabs        = new EquipPanel[ Equipment.types.size() ];
        tabNames    = new String[ Equipment.types.size() ];
        pane        = new JTabbedPane( JTabbedPane.TOP );
        f           = new Font( "Lucida Sans", 0, 14 );
        for ( i = 0; i < Equipment.types.size(); i++ )
            tabNames[ i ]   = Equipment.types.get( i ).toString();
            tabs[ i ]       = new EquipPanel( tabNames[ i ], this );
            pane.add( tabNames[ i], tabs[ i ] );
            pane.addChangeListener( tabs[ i ] );
        this.add( pane );
        this.setBounds( 400,200,500,300);
    EquipPanel( String name, EquipPanel main )
        ArrayList arr   = Equipment.determineArray( name );
        JButton[] buttons = new JButton[ arr.size() ];
        for ( int i = 0; i < arr.size() - 1; i++ )
            buttons[ i ] = new JButton( arr.get( i + 1 ).toString() );
            add( buttons[ i ] );
            buttons[ i ].addActionListener( main );
    public void stateChanged( ChangeEvent ce )
    public void actionPerformed( ActionEvent ae )
        String source =( ( JButton ) ae.getSource() ).getText();
}and MainPanel if you wanted to see it in action
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class MainPanel extends JPanel
    public MainPanel()
        setName( "Main" );
}Thanks guys

Read this section from the Swing tutorial on "Using Layout Managers":
http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
Absolute Positioning is what you want.

Similar Messages

  • Removing rows and inserting new rows with new data in JTAble!!! (Plz. help)

    I have a problem, The scenario is that when I click any folder that si in my JTable's first row, the table is update by removing all the rows and showing only the contents of my selected folder. Right now it's not removing the rows and instead throwing exceptions. The code is attached. The methods to look are upDateTabel(...) and clearTableData(....), after clearing all my rows then I proceed on adding my data to the Jtable and inserting rows but it's not being done. May be I have a problem in my DefaultTableModel class. Please see the code below what I am doing wrong and how should I do it. Any help is appreciated.
    Thanks
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    public class SimpleTable extends JPanel{
         /** Formats the date */
         protected SimpleDateFormat           formatter;
    /** variable to hold the date and time in a raw form for the directory*/
    protected long                          dateDirectory;
    /** holds the readable form converted date for the directories*/
    protected String                     dirDate;
    /** holds the readable form converted date for the files*/
    protected String                     fileDate;
    /** variable to hold the date and time in a raw form for the file*/
    protected long                          dateFile;
    /** holds the length of the file in bytes */
    protected long                         totalLen;
    /** convert the length to the wrapper class */
    protected Long                         longe;
    /** Vector to hold the sub directories */
    protected Vector                     subDir;
    /** holds the name of the selected directory */
    protected String                    dirNameHold;
    /** converting vector to an Array and store the values in this */
    protected File                     directoryArray[];
    /** hashtable to store the key-value pair */
    protected static Hashtable hashTable = new Hashtable();
    /** refer to the TableModel that is the default*/
    protected MyTableModel               tableModel;
    /** stores the path of the selected file */
    protected static String               fullPath;
    /** stores the currently selected file */
    protected static File selectedFilename;
    /** stores the extension of the selected file */
    protected static String           extension;
    protected int COLUMN_COUNT = 4;
         protected Vector data = new Vector( 0, 1 );
         protected final JTable table;
    /** holds the names of the columns */
    protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
    public SimpleTable(File directoryArray[])
              this.setLayout(new BorderLayout());
              this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              (SimpleTable.hashTable).clear();
              formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
              for(int k = 0; k < directoryArray.length; k++)
                   if(directoryArray[k].isDirectory())
                        dateDirectory = directoryArray[k].lastModified();
                        dirDate = formatter.format(new java.util.Date(dateDirectory));
                        data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                   else if(directoryArray[k].isFile())
                        dateDirectory = directoryArray[k].lastModified();
                        fileDate = formatter.format(new java.util.Date(dateDirectory));
                        totalLen = directoryArray[k].length();
                        longe = new Long(totalLen);
                        data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
    tableModel = new MyTableModel();
              table = new JTable( tableModel );
              table.getTableHeader().setReorderingAllowed(false);
              table.setRowSelectionAllowed(false);
              table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              table.setShowHorizontalLines(false);
              table.setShowVerticalLines(false);
              table.addMouseListener(new MouseAdapter()
    public void mouseReleased(MouseEvent e)
         Object eventTarget = e.getSource();
                        if( eventTarget == table )
                             upDateTable(table);
                             table.tableChanged( new javax.swing.event.TableModelEvent(tableModel) ) ;
              DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
              table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
              ((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    this.add(scrollPane, BorderLayout.CENTER);
    * Searches the Hashtable and returns the path of the folder or the value.
    public File findPath(String value)
         return (File)((SimpleTable.hashTable).get(value));
    * This clears the previous data in the JTable
    public void clearTableData(JTable table)
         for(int row = 0; row < table.getRowCount() ; row++)
                   //for (int col = 0; col < table.getColumnCount() ; col++)
                        tableModel.deleteSelections( row );
              tableModel.fireTableStructureChanged();
              tableModel.fireTableRowsDeleted(0,table.getRowCount());
              //table.getModel().fireTableChanged(new TableModelEvent(table.getModel()));
    private void upDateTable(JTable table)
    if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
         dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
                   File argument = findPath(dirNameHold);
                   if(argument.isFile())
                        CMRDialog.fileNameTextField.setText(argument.getName());
                        try
                             fullPath = argument.getCanonicalPath();                          
                             selectedFilename = argument.getCanonicalFile();                          
    CMRDialog.filtersComboBox.removeAllItems();
                             extension = fullPath.substring(fullPath.lastIndexOf('.'));
                             CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
                        catch(IOException e)
                             System.out.println("THE ERROR IS " + e);
                        return;
                   else if(argument.isDirectory())
                        String path = argument.getName();
                             //find the system dependent file separator
                             //String fileSeparator = System.getProperty("file.separator");
                        CMRDialog.driveComboBox.addItem(" " + path);
              subDir = Search.subDirs(argument);
              /**TBD:- needs a method to convert the vector to an array and return the array */
              directoryArray = new File[subDir.size()];
                   int indexCount = 0;
                   /** TBD:- This is inefficient way of converting a vector to an array */               
                   Iterator e = subDir.iterator();               
                   while( e.hasNext() )
                        directoryArray[indexCount] = (File)e.next();
                        indexCount++;
              /** now calls this method and clears the previous data */
              clearTableData(table);     
                   (SimpleTable.hashTable).clear();
                   //data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
                   for(int k = 0; k < directoryArray.length; k++)
                        if(directoryArray[k].isDirectory())
                             dateDirectory = directoryArray[k].lastModified();
                             dirDate = formatter.format(new java.util.Date(dateDirectory));
                             data.addElement( new MyObj( directoryArray[k].getName(), "", "File Folder", "" + dirDate ) );
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                        else if(directoryArray[k].isFile())
                             dateDirectory = directoryArray[k].lastModified();
                             fileDate = formatter.format(new java.util.Date(dateDirectory));
                             totalLen = directoryArray[k].length();
                             longe = new Long(totalLen);
                             data.addElement( new MyObj( directoryArray[k].getName(), longe + " Bytes", "", "" + fileDate ) );
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
              // tableModel.fireTableDataChanged();          
              // tableModel.fireTableRowsInserted(0,1);
              table.revalidate();
              table.validate();               
    class MyTableModel extends DefaultTableModel
              int totalRows;
              int totalCols;
              public MyTableModel()
                   super();
                   setColumnIdentifiers (columnNames);
                   this.totalRows = data.size();
                   this.totalCols = columnNames.length;
              // this will return the row count of your table
              public int getRowCount()
                   return totalRows;
              // this return the column count of your table
              public int getColumnCount()
                   return totalCols;
              // this return the data for each cell in your table
              public Object getValueAt(int row, int col)
                   MyObj obj = (MyObj)data.elementAt( row );
                   if( obj != null )
                        if( col == 0 ) return( obj.first );
                        else if( col == 1 ) return( obj.last );
                        else if( col == 2 ) return( obj.third );
                        else if( col == 3 ) return( obj.fourth );
                        else return( "" );
                   return "";
              // if you want your table to be editable then return true
              public boolean isCellEditable(int row, int col)
                   return false;
              // if your table is editable edit the data vector here and
              // call table.tableChanged(...)
              public void setValueAt(Object value, int row, int col)
              protected void deleteSelections (int rows)
                   try
                        removeRow(rows);
                   catch(ArrayIndexOutOfBoundsException e)
                        System.out.println("The error in the row index " + rows);
                   fireTableDataChanged() ;
    class MyObj
              String first;
              String last;
              String third;
              String fourth;
              public MyObj( String f, String l, String t, String fo )
                   this.first = f;
                   this.last = l;
                   this.third = t;
                   this.fourth = fo;
    #####################################

    The following code works fine but it doesn't show me the new updated date in my JTable. I tried to print the values that I am getting and it does give the values on the prompt but doesn't show me on the JTable only first two are shown and the rest of the table is filled with the same values. I don't know what's going on and am tired of this TableModel thing so pla. take a time to give me some suggestions. Thanks
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    public class SimpleTable extends JPanel {
         /** Formats the date */
         protected SimpleDateFormat           formatter;
    /** two-dimensional array to hold the information for each column */
    protected Object                     data[][];
    /** variable to hold the date and time in a raw form for the directory*/
    protected long                          dateDirectory;
    /** holds the readable form converted date for the directories*/
    protected String                     dirDate;
    /** holds the readable form converted date for the files*/
    protected String                     fileDate;
    /** variable to hold the date and time in a raw form for the file*/
    protected long                          dateFile;
    /** holds the length of the file in bytes */
    protected long                         totalLen;
    /** convert the length to the wrapper class */
    protected Long                         longe;
    /** Vector to hold the sub directories */
    protected Vector                     subDir;
    /** holds the name of the selected directory */
    protected String                    dirNameHold;
    /** converting vector to an Array and store the values in this */
    protected File                     directoryArray[];
    /** hashtable to store the key-value pair */
    protected static Hashtable hashTable = new Hashtable();
    /** refer to the TableModel that is the default*/
    protected DefaultTableModel      model;
    /** stores the path of the selected file */
    protected static String               fullPath;
    /** stores the currently selected file */
    protected static File selectedFilename;
    /** stores the extension of the selected file */
    protected static String           extension;
    protected Vector                     m = new Vector(0,1);
    /** holds the names of the columns */
    protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
    public SimpleTable(File directoryArray[])
              this.setLayout(new BorderLayout());
              this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              (SimpleTable.hashTable).clear();
              data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
              formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
              for(int k = 0; k < directoryArray.length; k++)
                   if(directoryArray[k].isDirectory())
                        data[k][0] = directoryArray[k].getName();
                        data[k][2] = "File Folder";
                        dateDirectory = directoryArray[k].lastModified();
                        dirDate = formatter.format(new java.util.Date(dateDirectory));
                        data[k][3] = dirDate;
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                   else if(directoryArray[k].isFile())
                        data[k][0] = directoryArray[k].getName();
                        totalLen = directoryArray[k].length();
                        longe = new Long(totalLen);
                        data[k][1] = longe + " Bytes";
                        dateFile = directoryArray[k].lastModified();
                        fileDate = formatter.format(new java.util.Date(dateFile));
                        data[k][3] = fileDate;
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
    model = new DefaultTableModel();
    model.addTableModelListener( new TableModelListener(){
              public void tableChanged( javax.swing.event.TableModelEvent e )
                   System.out.println("************ I am inside the table changed method ********" );
              final JTable table = new JTable(model);
              table.getTableHeader().setReorderingAllowed(false);
              table.setRowSelectionAllowed(false);
              table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              table.setShowHorizontalLines(false);
              table.setShowVerticalLines(false);
              table.addMouseListener(new MouseAdapter()
    /* public void mousePressed(MouseEvent e)
    //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
    /* if(e.getClickCount() >= 2 &&
    (table.getSelectedColumn() == 0) &&
    ((table.getColumnName(0)).equals(columnNames[0])))
         //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
         upDateTable(table);
    public void mouseReleased(MouseEvent e)
    //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
    /* if(e.getClickCount() >= 2 &&
    (table.getSelectedColumn() == 0) &&
    ((table.getColumnName(0)).equals(columnNames[0]))) */
         //System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
         upDateTable(table);
              /** set the columns */
              for(int c = 0; c < columnNames.length; c++)
                   model.addColumn(columnNames[c]);
              /** set the rows */
              for(int r = 0; r < data.length; r++)
                   model.addRow(data[r]);
              DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
              table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
              ((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    this.add(scrollPane, BorderLayout.CENTER);
    * Returns the number of columns
    public int getColumnTotal()
         return columnNames.length;
    * Returns the number of rows
    public int getRowTotal(Object directoryArray[])
         return directoryArray.length;
    private void upDateTable(JTable table)
    if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
         dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
                   File argument = findPath(dirNameHold);
                   if(argument.isFile())
                        CMRDialog.fileNameTextField.setText(argument.getName());
                        try
                             fullPath = argument.getCanonicalPath();                          
                             selectedFilename = argument.getCanonicalFile();                          
    CMRDialog.filtersComboBox.removeAllItems();
                             extension = fullPath.substring(fullPath.lastIndexOf('.'));
                             CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
                        catch(IOException e)
                             System.out.println("THE ERROR IS " + e);
                        return;
                   else if(argument.isDirectory())
                        String path = argument.getName();
                             //find the system dependent file separator
                             //String fileSeparator = System.getProperty("file.separator");
                        CMRDialog.driveComboBox.addItem(" " + path);
              subDir = Search.subDirs(argument);
              /**TBD:- needs a method to convert the vector to an array and return the array */
              directoryArray = new File[subDir.size()];
                   int indexCount = 0;
                   /** TBD:- This is inefficient way of converting a vector to an array */               
                   Iterator e = subDir.iterator();               
                   while( e.hasNext() )
                        directoryArray[indexCount] = (File)e.next();
                        indexCount++;
              /** now calls this method and clears the previous data */
              clearTableData(table);     
                   (SimpleTable.hashTable).clear();
                   data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
                   m.clear();
                   data = null;
                   data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   for(int k = 0; k < directoryArray.length; k++)
                        if(directoryArray[k].isDirectory())
                        System.out.println("Inside the if part");
                             data[k][0] = directoryArray[k].getName();
                             table.setValueAt(directoryArray[k].getName(),k,0);
                             //model.fireTableCellUpdated(k,0);
                             data[k][2] = "File Folder";
                             table.setValueAt("File Folder",k,2);
                             //model.fireTableCellUpdated(k,2);
                             dateDirectory = directoryArray[k].lastModified();
                             dirDate = formatter.format(new java.util.Date(dateDirectory));
                             data[k][3] = dirDate;
                             table.setValueAt(dirDate,k,3);
                             //model.fireTableCellUpdated(k,3);
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
                             m.add(data);
                             model.addRow(m);
                             model.fireTableDataChanged();                              
                        else if(directoryArray[k].isFile())
                   System.out.println("******* Inside the else part *******");
                             data[k][0] = directoryArray[k].getName();
                   System.out.println("The Name is == " + data[k][0]);
                             table.setValueAt(directoryArray[k].getName(),k,0);
                   System.out.println("The table cell value of the name is == " + table.getValueAt(k,0));
                             //model.fireTableCellUpdated(k,0);
                             totalLen = directoryArray[k].length();
                             longe = new Long(totalLen);
                             data[k][1] = longe + " Bytes";
                   System.out.println("The length == " + data[k][1]);
                             table.setValueAt(longe + " Bytes",k,1);
                   System.out.println("The table cell value of the length is == " + table.getValueAt(k,1));
                             //model.fireTableCellUpdated(k,0);
                             dateFile = directoryArray[k].lastModified();
                             fileDate = formatter.format(new java.util.Date(dateFile));
                             data[k][3] = fileDate;
                   System.out.println("The modified date == " + data[k][3]);
                             table.setValueAt(fileDate,k,3);
                   System.out.println("The table cell value of the name is == " + table.getValueAt(k,3));
                             //model.fireTableCellUpdated(k,0);
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    }
                             m.add(data);
                             model.addRow(m);
                             model.fireTableDataChanged();     
              // model.fireTableDataChanged();          
              // model.fireTableRowsInserted(0,1);
              table.revalidate();
              table.validate();               
         else
    * Searches the Hashtable and returns the path of the folder or the value.
    public File findPath(String value)
         return (File)((SimpleTable.hashTable).get(value));
    * This clears the previous data in the JTable
    public void clearTableData(JTable table)
         for(int row = 0; row < table.getRowCount() ; row++)
                   for (int col = 0; col < table.getColumnCount() ; col++)
                        table.setValueAt(null, row , col);
              model.fireTableStructureChanged();
    ###

  • Directory being added two times in JTable rows.(JTable Incorrect add. Rows)

    hi,
    I have a problem, The scenario is that when I click any folder that is in my JTable's row, the table is update by removing all the rows and showing only the contents of my selected folder. If my selected folder contains sub-folders it is some how showing that sub-folder two time and if there are files too that are shown correctly. e.g. If I have a parent folder FG1 and inside that folder I have one more folder FG12 and two .java files then when I click on FG1 my table should show FG12 and two .java files in separate rows, right now it is showing me the contents of FG1 folder but some how FG12 is shown on two rows i.e. first row shows FG12 second row shows FG12 third row shows my .java file and fourth row shows my .java fil. FG12 should be shown only one time. The code is attached. The methods to look are upDateTabel(...) and clearTableData(....), after clearing all my rows then I proceed on adding my data to the Jtable and inserting rows. May be addRow(... method of DefaultTableModel is called two times if it is a directory I don't know why. Please see the code below what I am doing wrong and how to fix it. Any help is appreciated.
    Thanks
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.border.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    public class SimpleTable extends JPanel {
         /** Formats the date */
         protected SimpleDateFormat           formatter;
    /** two-dimensional array to hold the information for each column */
    protected Object                     data[][];
    /** variable to hold the date and time in a raw form for the directory*/
    protected long                          dateDirectory;
    /** holds the readable form converted date for the directories*/
    protected String                     dirDate;
    /** holds the readable form converted date for the files*/
    protected String                     fileDate;
    /** variable to hold the date and time in a raw form for the file*/
    protected long                          dateFile;
    /** holds the length of the file in bytes */
    protected long                         totalLen;
    /** convert the length to the wrapper class */
    protected Long                         longe;
    /** Vector to hold the sub directories */
    protected Vector                     subDir;
    /** holds the name of the selected directory */
    protected String                    dirNameHold;
    /** converting vector to an Array and store the values in this */
    protected File                     directoryArray[];
    /** hashtable to store the key-value pair */
    protected static Hashtable hashTable = new Hashtable();
    /** refer to the TableModel that is the default*/
    protected DefaultTableModel      model;
    /** stores the path of the selected file */
    protected static String               fullPath;
    /** stores the currently selected file */
    protected static File selectedFilename;
    /** stores the extension of the selected file */
    protected static String           extension;
    /** holds the names of the columns */
    protected final String columnNames[] = {"Name", "Size", "Type", "Modified"};
         * Default constructor
         * @param File the list of files and directories to be shown in the JTable.
    public SimpleTable(File directoryArray[])
              this.setLayout(new BorderLayout());
              this.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              (SimpleTable.hashTable).clear();
              data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
              formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
              //this shows the data in the JTable i.e. the primary directory stuff.
              for(int k = 0; k < directoryArray.length; k++)
                   if(directoryArray[k].isDirectory())
                        data[k][0] = directoryArray[k].getName();
                        data[k][2] = "File Folder";
                        dateDirectory = directoryArray[k].lastModified();
                        dirDate = formatter.format(new java.util.Date(dateDirectory));
                        data[k][3] = dirDate;
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    
                   else if(directoryArray[k].isFile())
                        data[k][0] = directoryArray[k].getName();
                        totalLen = directoryArray[k].length();
                        longe = new Long(totalLen);
                        data[k][1] = longe + " Bytes";
                        dateFile = directoryArray[k].lastModified();
                        fileDate = formatter.format(new java.util.Date(dateFile));
                        data[k][3] = fileDate;
                        (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
    model = new DefaultTableModel();
    model.addTableModelListener( new TableModelListener(){
              public void tableChanged( javax.swing.event.TableModelEvent e )
              final JTable table = new JTable(model);
              table.getTableHeader().setReorderingAllowed(false);
              table.setRowSelectionAllowed(false);
              table.setBorder( BorderFactory.createEmptyBorder( 0, 0, 0, 0 ) );
              table.setShowHorizontalLines(false);
              table.setShowVerticalLines(false);
              table.addMouseListener(new MouseAdapter()
    public void mouseReleased(MouseEvent e)
    //TBD:- needs to handle the doubleClick of the mouse.
    System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
    if(e.getClickCount() >= 2 &&
    (table.getSelectedColumn() == 0) &&
    ((table.getColumnName(0)).equals(columnNames[0])))
         System.out.println("The clicked component is " + table.rowAtPoint(e.getPoint()) + "AND the number of clicks is " + e.getClickCount());
         upDateTable(table);
    upDateTable(table);
              /** set the columns */
              for(int c = 0; c < columnNames.length; c++)
                   model.addColumn(columnNames[c]);
              /** set the rows */
              for(int r = 0; r < data.length; r++)
                   model.addRow(data[r]);
              //this sets the tool-tip on the headers.
              DefaultTableCellRenderer D_headerRenderer = (DefaultTableCellRenderer ) table.getTableHeader().getDefaultRenderer();
              table.getColumnModel().getColumn(0).setHeaderRenderer(D_headerRenderer );
              ((DefaultTableCellRenderer)D_headerRenderer).setToolTipText("File and Folder in the Current Folder");
    //Create the scroll pane and add the table to it.
    JScrollPane scrollPane = new JScrollPane(table);
    //Add the scroll pane to this window.
    this.add(scrollPane, BorderLayout.CENTER);
    * Returns the number of columns
    * @return int number of columns
    public int getColumnTotal()
         return columnNames.length;
    * Returns the number of rows
    * @return int number of rows
    public int getRowTotal(Object directoryArray[])
         return directoryArray.length;
    * Update the table according to the selection made if a directory then searches and
    * shows the contents of the directory, if a file fills the appropriate fields.
    * @param JTable table we are working on
    * //TBD: handling of the files.
    private void upDateTable(JTable table)
    if((table.getSelectedColumn() == 0) && ((table.getColumnName(0)).equals(columnNames[0])))
         dirNameHold =(String) table.getValueAt(table.getSelectedRow(),table.getSelectedColumn());
                   File argument = findPath(dirNameHold);
                   if(argument.isFile())
                        CMRDialog.fileNameTextField.setText(argument.getName());
                        try
                             fullPath = argument.getCanonicalPath();                          
                             selectedFilename = argument.getCanonicalFile();                          
    CMRDialog.filtersComboBox.removeAllItems();
                             extension = fullPath.substring(fullPath.lastIndexOf('.'));
                             CMRDialog.filtersComboBox.addItem("( " + extension + " )" + " File");
                        catch(IOException e)
                             System.out.println("THE ERROR IS " + e);
                        return;
                   else if(argument.isDirectory())
                        String path = argument.getName();
                             //find the system dependent file separator
                             //String fileSeparator = System.getProperty("file.separator");
                        CMRDialog.driveComboBox.addItem(" " + path);
              subDir = Search.subDirs(argument);
              /**TBD:- needs a method to convert the vector to an array and return the array */
              directoryArray = new File[subDir.size()];
                   int indexCount = 0;
                   /** TBD:- This is inefficient way of converting a vector to an array */               
                   Iterator e = subDir.iterator();               
                   while( e.hasNext() )
                        directoryArray[indexCount] = (File)e.next();
                        indexCount++;
              /** now calls this method and clears the previous data */
              clearTableData(table);     
                   (SimpleTable.hashTable).clear();
                   data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   formatter = new SimpleDateFormat("mm/dd/yyyy hh:mm aaa");
                   data = null;
                   data = new Object[this.getRowTotal(directoryArray)][this.getColumnTotal()];
                   for(int k = 0; k < directoryArray.length; k++)
                        if(directoryArray[k].isDirectory())
                             data[k][0] = directoryArray[k].getName();
                             data[k][2] = "File Folder";
                             dateDirectory = directoryArray[k].lastModified();
                             dirDate = formatter.format(new java.util.Date(dateDirectory));
                             data[k][3] = dirDate;
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);
                             model.addRow(data[k]);
                             model.fireTableDataChanged();
                        else if(directoryArray[k].isFile())
                             data[k][0] = directoryArray[k].getName();
                             totalLen = directoryArray[k].length();
                             longe = new Long(totalLen);
                             data[k][1] = longe + " Bytes";
                             dateFile = directoryArray[k].lastModified();
                             fileDate = formatter.format(new java.util.Date(dateFile));
                             data[k][3] = fileDate;
                             (SimpleTable.hashTable).put(directoryArray[k].getName(), directoryArray[k]);                    }
                             model.addRow(data[k]);
                             model.fireTableDataChanged();
              table.revalidate();
              table.validate();               
    * Searches the Hashtable and returns the path of the folder or the value.
    * @param String name of the directory or file.
    * @return File     full-path of the selected file or directory.
    public File findPath(String value)
         return (File)((SimpleTable.hashTable).get(value));
    * This clears the previous data in the JTable and removes the rows.
    * @param     JTable table we are updating.
    public void clearTableData(JTable table)
         for(int row = table.getRowCount() - 1; row >= 0; --row)
                   model.removeRow(row);
              model.fireTableStructureChanged();

    java gurus any idea how ti fix this problem.
    thanks

  • How can I Display a Image with tiff format in Jpanel?

    How can I Display a CMYK Image with tiff format in Jpanel ? Not in ScrollingImagePanel? Thank you in advance.

    Why nobody can help me?I am very anxious!help me,please!

  • Displaying the Tiff format image in JPanel

    How can i display an .tiff formatted image in a jpanel ?

    How can i display an .tiff formatted image in a jpanel ?

  • How to update a JPanel in a JApplet

    Hi All,
    I'm trying to make my own sudoku JApplet. JApplet uses a BorderLayout() adding the sudoku Puzzle in the center, JButtons for New Games in a JPanel in the west and a GridLayout(3,3) to select the number to put in the puzzle in the east.
    The problem is: how can i update the sudoku puzzle in the center by clicking the "new game" JButton in the west?
    I use JButtons to represent numbers in the puzzle. this is how i create the JButton and set its ActionListener().
         public static JButton casella(String[] casella) {
              final JButton b = new JButton(casella[0]);
              b.setFont(new Font("SansSerif",Font.BOLD,33));
              if(casella[3].equals("1"))
                   b.setBorder(BorderFactory.createLineBorder(Color.orange));
              if(casella[3].equals("2"))
                   b.setBorder(BorderFactory.createLineBorder(Color.red));
              else
                   b.setBorder(BorderFactory.createLineBorder(Color.black));
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        if(Sudoku.NUMERO_CORRENTE>=0)
                             b.setText(String.valueOf(Sudoku.NUMERO_CORRENTE));
                        else
                             b.setText("_");
              return b;
         }this is the main class:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Sudoku extends JApplet {
         static String[][][] MATRICE = MatriceCompleta.sudoku().getArrayMatrice();
         static JPanel PANNELLO_NUMERICO = OggettiGrafici.pannelloNumerico();
         static JPanel PANNELLO_EAST = new JPanel(new GridLayout(3,1));
         static JPanel PANNELLO_WEST = new JPanel(new GridLayout(6,1));
         static JPanel PANNELLO_CASELLE = new JPanel(new GridLayout(3,3));
         static JPanel PANNELLO = new JPanel(new BorderLayout());
         static int POSIZIONE_CASELLA_X = 0;
         static int POSIZIONE_CASELLA_Y = 0;
         static int NUMERO_CORRENTE = 0;
         static JLabel LABEL_NUMERO_CORRENTE = new JLabel(String.valueOf(NUMERO_CORRENTE), JLabel.CENTER);
         static JLabel LABEL_PARTITA = new JLabel("",JLabel.CENTER);
         static JLabel LABEL_NUOVA_PARTITA = new JLabel("NUOVA PARTITA",JLabel.CENTER);
         static JButton FACILE = new JButton("Livello Facile");
         static JButton NORMALE = new JButton("Livello Medio");
         static JButton DIFFICILE = new JButton("Livello Difficile");
         static JButton CONTROLLA_ERRORI = new JButton("Controlla Errori");
         static JButton CANCELLA_NUMERO = new JButton("Cancella Numero");
         static String DIFFICOLTA = "NORMALE";
         static int i, j, k;
         public void init() {
              String[][][][] divisaInPannelli = ComandiUtili.divisioneInPannelli(MATRICE);
              JPanel p0 = new JPanel(new GridBagLayout());
              JPanel p1 = new JPanel(new GridBagLayout());
              JPanel p2 = new JPanel(new GridBagLayout());
              JPanel p3 = new JPanel(new GridBagLayout());
              JPanel p4 = new JPanel(new GridBagLayout());
              JPanel p5 = new JPanel(new GridBagLayout());
              JPanel p6 = new JPanel(new GridBagLayout());
              JPanel p7 = new JPanel(new GridBagLayout());
              JPanel p8 = new JPanel(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.fill = GridBagConstraints.BOTH;
                    // creating the sudoku puzzle panel using JButtons
              for(i=0;i<9;i++) {
                   for(j=0;j<3;j++) {
                        for(k=0;k<3;k++) {
                             JButton b = OggettiGrafici.casella(divisaInPannelli[i][k][j]);
                             c.gridx = j;
                             c.gridy = k;
                             c.ipadx = 42;
                             c.ipady = 12;
                             if(i==0)
                                  p0.add(b,c);
                             else if(i==1)
                                  p1.add(b,c);
                             else if(i==2)
                                  p2.add(b,c);
                             else if(i==3)
                                  p3.add(b,c);
                             else if(i==4)
                                  p4.add(b,c);
                             else if(i==5)
                                  p5.add(b,c);
                             else if(i==6)
                                  p6.add(b,c);
                             else if(i==7)
                                  p7.add(b,c);
                             else if(i==8)
                                  p8.add(b,c);
              PANNELLO_CASELLE.add(p0);
              PANNELLO_CASELLE.add(p1);
              PANNELLO_CASELLE.add(p2);
              PANNELLO_CASELLE.add(p3);
              PANNELLO_CASELLE.add(p4);
              PANNELLO_CASELLE.add(p5);
              PANNELLO_CASELLE.add(p6);
              PANNELLO_CASELLE.add(p7);
              PANNELLO_CASELLE.add(p8);
              PANNELLO_EAST.add(PANNELLO_NUMERICO);
              PANNELLO_EAST.add(LABEL_NUMERO_CORRENTE);
              PANNELLO_EAST.add(LABEL_PARTITA);
              PANNELLO_WEST.add(LABEL_NUOVA_PARTITA);
              PANNELLO_WEST.add(FACILE);
              PANNELLO_WEST.add(NORMALE);
              PANNELLO_WEST.add(DIFFICILE);
              PANNELLO_WEST.add(CONTROLLA_ERRORI);
              PANNELLO_WEST.add(CANCELLA_NUMERO);
              PANNELLO.add(PANNELLO_CASELLE, BorderLayout.CENTER);
              PANNELLO.add(PANNELLO_EAST, BorderLayout.EAST);
              PANNELLO.add(PANNELLO_WEST, BorderLayout.WEST);
              add(PANNELLO);
         public void paint(Graphics g) {
              super.paint(g);
    }How can i update the sudoku puzzle (JPanel with 9x9 JButtons) by clicking on a "new game" JButton?
    Thank You very much in advance!

    Hi SD,
    How are you drawing the image on the JPanel?
    Are you using JLabel with image and adding it to Panel or using
    drawImage to get the image on the panel (Only jpeg and gif formats are supported here).
    DrawImage should automatically refresh, if not call repaint().
    That should refresh the Screen.
    Regards
    Chandra Mohan

  • How to open a JPanel

    Hi
    I have created a JPanel in JDeveloper 10.1.3. It has a main method with (see below) but when opened from my application I must use something else than JUTestFrame but what? How should the JPanel be opened the right way?
    public static void main(String [] args) {
    try {
    UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
    } catch (ClassNotFoundException cnfe) {
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception exemp) {
    exemp.printStackTrace();
    } catch (Exception exemp) {
    exemp.printStackTrace();
    CurrencyRateEdit panel = new CurrencyRateEdit();
    panel.setBindingContext(JUTestFrame.startTestFrame("mypackage.DataBindings.cpx", "null", panel, panel.getPanelBinding(), new Dimension(400,300)));
    panel.revalidate();
    }

    Thanks for the input, unfortunately using the JFrame provided by the JDev wizard is what we are trying to avoid. We do not want a JFrame of any kind.
    I have it working now with a JPanel as the top level container for the ADF plumbing. This allows me to place the ADF bindings virtually anywhere without any type of boarders. Here is how I did it. (by the way I am still testing out Erik's recommendation)
    1) create a default application with an empty runable panel. (the main() can be moved out later but makes it easy for testing) The code here assumes you are using all the default naming in the wizard. If not you will have to make the appropriate changes.
    2) Just under the class definition create an instance of a class named "appPanel". This class will be defined below and is a gutted/modified version of JUTestFrame which extends JPanel instead of JFrame. It should look something like this:
    public class Panel1 extends JPanel implements JUPanel {       
    public appPanel canvas = new appPanel();
    3) In the main() function change
    panel.setBindingContext(JUTestFrame.startTestFrame( ...
    to:
    panel.setBindingContext(panel.canvas.startTestFrame( ... //canvas is the name I chose in step 2.
    4) If, in this test app, you don't already have a container (JForm or other) for the ADF JPanel you can create one for testing like this:
    At the bottom of the main() function put :
    JFrame xx = new JFrame();
    xx.add(panel);
    xx.setVisible(true);
    5) Create the class file appPanel (menu: new >simple file > Java Class. and replace all of the contents with: (excuse the formatting. I don't know why they don't make developer forums more code friendly)
    package mypackage;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.GridLayout;
    import java.awt.event.KeyEvent;
    import java.beans.PropertyVetoException;
    import javax.swing.JPanel;
    import javax.swing.JInternalFrame;
    import javax.swing.JScrollPane;
    import java.util.HashMap;
    import oracle.jbo.uicli.UIMessageBundle;
    import oracle.jbo.uicli.jui.JUPanelBinding;
    import oracle.jbo.uicli.jui.JUEnvInfoProvider;
    import oracle.jbo.uicli.controls.JUErrorHandlerDlg;
    import oracle.jbo.uicli.controls.JClientPanel;
    import oracle.jbo.uicli.binding.JUApplication;
    import oracle.jbo.uicli.mom.JUMetaObjectManager;
    import oracle.adf.model.BindingContext;
    import oracle.adf.model.DataControlFactory;
    import oracle.adf.model.binding.DCDataControl;
    import oracle.jbo.uicli.controls.*;
    public class appPanel extends JPanel
    private JUPanelBinding panelBinding = null;
    private DCDataControl dataControl;
    private BindingContext mCtx;
    appPanel frame;
    public appPanel() {
    try {
    jbInit();
    } catch (Exception e) {
    e.printStackTrace();
    public BindingContext startTestFrame(String cpxName, String dcName, JPanel panel, JUPanelBinding panelBinding, Dimension size)
    if (!(panel instanceof JUPanel))
    System.err.println(UIMessageBundle.getResString(UIMessageBundle.STR_TUI_ERROR_JCLIENTPANEL));
    return null;
    frame = new appPanel(cpxName, dcName, panelBinding, panel);
    frame.adjustFrameSize(size);
    return frame.getBindingContext();
    public appPanel(JUPanelBinding designTimePanelBinding, JPanel panel)
    this.setLayout(new GridLayout());
    JScrollPane scPane = new JScrollPane(panel);
    this.add(scPane);
    JUMetaObjectManager.setBaseErrorHandler(new JUErrorHandlerDlg());
    //mom will pass properties in case it's null
    JUApplication app = JUMetaObjectManager.createApplicationObject(designTimePanelBinding.getApplicationName(), null, new JUEnvInfoProvider());
    panelBinding = new JUPanelBinding(designTimePanelBinding.getApplicationName(), panel);
    panelBinding.setApplication(app);
    ((JClientPanel)panel).setPanelBinding(panelBinding);
    panelBinding.execute();
    dataControl = app;
    public appPanel(String cpxName, String dcName, JUPanelBinding panelBinding, JPanel panel)
    this.setLayout(new GridLayout());
    JScrollPane scPane = new JScrollPane(panel);
    this.add(scPane);
    createBindingCtxAndSetUpMenu(cpxName, dcName, panelBinding);
    private void createBindingCtxAndSetUpMenu(String cpxName, String dcName, JUPanelBinding panelBinding)
    JUMetaObjectManager.setBaseErrorHandler(new JUErrorHandlerDlg());
    JUMetaObjectManager.getJUMom().setJClientDefFactory(null);
    mCtx = new BindingContext();
    HashMap map = new HashMap(4);
    map.put(DataControlFactory.APP_PARAMS_BINDING_CONTEXT, mCtx);
    JUMetaObjectManager.loadCpx(cpxName, map);
    DCDataControl app = (DCDataControl)mCtx.get(dcName);
    if (app != null)
    dataControl = app;
    app.setClientApp(DCDataControl.JCLIENT);
    else
    mCtx.setClientAppType(DCDataControl.JCLIENT);
    panelBinding = panelBinding.setup(mCtx, null);
    public DCDataControl getDataControl()
    return dataControl;
    public BindingContext getBindingContext()
    return mCtx;
    void adjustFrameSize(Dimension size)
    setSize(size);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    if (size.height > screenSize.height)
    size.height = screenSize.height;
    if (size.width > screenSize.width)
    size.width = screenSize.width;
    setLocation((screenSize.width - size.width) / 2, (screenSize.height - size.height) / 2);
    setVisible(true);
    private static final char MNEMONICINDICATOR = '&';
    public static final int MNEMONIC_INDEX_NONE = -1;
    * Returns the key code for the mnemonic in the string. Returns
    * VK_UNDEFINED if the string does not contain a mnemonic.
    public int getMnemonicKeyCode(String string)
    if (string == null)
    return KeyEvent.VK_UNDEFINED;
    // Minus one, because a trailing ampersand doesn't count
    int lengthMinusOne = string.length() - 1;
    int i = 0; // Index in the source sting
    while (i < lengthMinusOne)
    int index = string.indexOf(_MNEMONIC_INDICATOR, i);
    // Are we at the end of the string?
    if ((index == -1) || (index >= lengthMinusOne))
    break;
    char ch = string.charAt(index + 1);
    // if this isn't a double ampersand, return
    if (ch != MNEMONICINDICATOR)
    // VK_* constants are all for upper case characters
    return(int) Character.toUpperCase(ch);
    // Skip over the double ampersand
    i = index + 2;
    return KeyEvent.VK_UNDEFINED;
    * Removes non-displayable inline mnemonic characters.
    * In order to specify a mnemonic character in a translatable string
    * (eg. in a resource file), a special character is used to indicate which
    * character in the string should be treated as the mnemonic. This method
    * assumes that an ampersand ('&') character is used as the mnemonic
    * indicator, and removes (single) ampersands from the input string. A
    * double ampersand sequence is used to indicate that an ampersand should
    * actually appear in the output stream, in which case one of the ampersands
    * is removed.
    * Clients should call this method after calling
    * StringUtils.getMnemonicIndex() and before displaying the string. The
    * returned string should be used in place of the input string when
    * displaying the string to the end user. The returned string may be the
    * same as the input string if no mnemonic indicator characters are found,
    * but this is not guaranteed.
    * @see #getMnemonicIndex
    public String stripMnemonic(String string)
    if (string == null)
    return null;
    int length = string.length();
    // Single character (or empty) strings can't have a mnemonic
    if (length <= 1)
    return string;
    StringBuffer buffer = null;
    int i = 0;
    while (i < length)
    int index = string.indexOf(_MNEMONIC_INDICATOR, i);
    // We've reached the append. Append the rest of the
    // string to the buffer, if one exists, then exit
    if ((index < 0) || (index >= length - 1))
    if (buffer != null)
    buffer.append(string.substring(i));
    break;
    if (buffer == null)
    // If the string starts with an ampersand, but not a double
    // ampersand, then we just want to return
    // stripMnemonic(string.substring(1)). This is basically
    // what we do here, only I've optimized the tail recursion away.
    if ((index == 0) && (string.charAt(1) != MNEMONICINDICATOR))
    string = string.substring(1);
    length--;
    continue;
    else
    // Allocate the buffer. We can reserve only space
    // (length - 1), because, by now, we know there's at least
    // 1 ampersand
    buffer = new StringBuffer(length - 1);
    // Append the bits of the string before the ampersand
    buffer.append(string.substring(i, index));
    // And append the character after the ampersand
    buffer.append(string.charAt(index + 1));
    // And skip to after that character
    i = index + 2;
    // If we never allocated a buffer, then there's no mnemonic
    // at all, and we can just return the whole string
    if (buffer == null)
    return string;
    return new String(buffer);
    private void jbInit() throws Exception {
    And now you have an ADF implementation that exists purely in a JPanel to be placed anywhere.
    Again I am still testing Erik's recomendation which may prove to be a better implementation; but I wanted to share what I have working.
    I hope this helps someone out. Good luck.
    SMartel

  • Problem with jpanel and revalidate()

    i have made a calendar. on click on jlabel you can switch month/year and there is the problem. for example when i switch from february to march and back again, then the panel don�t update. but why?
    i hope you understand what i mean.(I am german and can�t englisch)
    here is the code(i have mixed german in english in the code, i hope you understand even so.)
    package organizer.gui;
    import organizer.*;
    import java.text.SimpleDateFormat;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class Kalender extends JPanel {
    private Calendar calendar;
    private JPanel days;
    private JLabel monthLabel;
    private SimpleDateFormat monthFormat = new SimpleDateFormat("dd MMM yyyy");
    private TerminManager manger;
    public Kalender(TerminManager manager) {
       super();
       this.manger=manager;
       this.calendar=Calendar.getInstance();
       this.initializeJPanel();
       this.updatePanel();
    protected void updatePanel() {
       monthLabel.setText(monthFormat.format(calendar.getTime()));
       if(days!=null) {
         days.removeAll();
       }else {
         days = new JPanel(new GridLayout(0, 7));
       days.setOpaque(true);
       for (int i = 1; i <=7; i++) {
         int dayInt = ( (i + 1) == 8) ? 1 : i + 1;
         JLabel label = new JLabel();
         label.setHorizontalAlignment(JLabel.CENTER);
         if (dayInt == Calendar.SUNDAY) {
           label.setText("Son");
         else if (dayInt == Calendar.MONDAY) {
           label.setText("Mon");
         else if (dayInt == Calendar.TUESDAY) {
           label.setText("Die");
         else if (dayInt == Calendar.WEDNESDAY) {
           label.setText("Mit");
         else if (dayInt == Calendar.THURSDAY) {
           label.setText("Don");
         else if (dayInt == Calendar.FRIDAY) {
           label.setText("Fre");
         else if (dayInt == Calendar.SATURDAY) {
           label.setText("Sam");
         days.add(label);
       Calendar setupCalendar = (Calendar) calendar.clone();
       setupCalendar.set(Calendar.DAY_OF_MONTH, 1);
       int firstday = setupCalendar.get(Calendar.DAY_OF_WEEK);
       for (int i = 1; i < (firstday - 1); i++) {
         days.add(new JLabel(""));
       for (int i = 1; i <=setupCalendar.getActualMaximum(Calendar.DAY_OF_MONTH); i++) {
         int day = setupCalendar.get(Calendar.DAY_OF_MONTH);
         final Date d = setupCalendar.getTime();
         final JLabel label = new JLabel(String.valueOf(day));
         label.setOpaque(true);
         if(this.manger.isTerminAtDay(d)) {
           String s="<html><center>" + day + "<br>";
           if(this.manger.isBirthdayAtDay(d)) {
             s+="Geburtstag<br>";
           if(this.manger.isOtherTerminAtDay(d)) {
             s+="Termin";
           label.setText(s);
           label.addMouseListener(new MouseListener() {
              * mouseClicked
              * @param e MouseEvent
             public void mouseClicked(MouseEvent e) {
               Termin[] t = Kalender.this.manger.getTermineAtDay(d);
               if (t.length == 1) {
                 new TerminDialog(null, t[0]);
               else {
                 new TerminAuswahlDialog(null, t, d);
              * mouseEntered
              * @param e MouseEvent
             public void mouseEntered(MouseEvent e) {
              * mouseExited
              * @param e MouseEvent
             public void mouseExited(MouseEvent e) {
              * mousePressed
              * @param e MouseEvent
             public void mousePressed(MouseEvent e) {
              * mouseReleased
              * @param e MouseEvent
             public void mouseReleased(MouseEvent e) {
         final Color background=label.getBackground();
         final Color foreground=label.getForeground();
         label.setHorizontalAlignment(JLabel.CENTER);
         label.addMouseListener(new MouseAdapter() {
           public void mouseEntered(MouseEvent e) {
             label.setBackground(Color.BLUE);
             label.setForeground(Color.RED);
           public void mouseExited(MouseEvent e) {
             label.setBackground(background);
             label.setForeground(foreground);
         days.add(label);
         setupCalendar.roll(Calendar.DAY_OF_MONTH,true);
       this.add(days, BorderLayout.CENTER);
       this.revalidate();
    private JLabel createUpdateButton(final int field,final int amount) {
       final JLabel label = new JLabel();
       final Border selectedBorder = new EtchedBorder();
       final Border unselectedBorder = new EmptyBorder(selectedBorder
           .getBorderInsets(new JLabel()));
       label.setBorder(unselectedBorder);
       label.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent e) {
           calendar.add(field, amount);
           Kalender.this.updatePanel();
         public void mouseEntered(MouseEvent e) {
           label.setBorder(selectedBorder);
         public void mouseExited(MouseEvent e) {
           label.setBorder(unselectedBorder);
       return label;
    private void initializeJPanel() {
       JPanel header = new JPanel();
       JLabel label;
       label = this.createUpdateButton(Calendar.YEAR, -1);
       label.setText("<<");
       header.add(label);
       label = this.createUpdateButton(Calendar.MONTH, -1);
       label.setText("<");
       header.add(label);
       monthLabel=new JLabel("");
       header.add(monthLabel);
       label = this.createUpdateButton(Calendar.MONTH, 1);
       label.setText(">");
       header.add(label);
       label = this.createUpdateButton(Calendar.YEAR, 1);
       label.setText(">>");
       header.add(label);
       this.setLayout(new BorderLayout());
       this.add(header, BorderLayout.NORTH);
    }

    I got you code to compile and run and made a single change to get it to work; adding a call to repaint at the end of the updatePanel method.
            this.add(days, BorderLayout.CENTER);
            this.revalidate();
            repaint();
        }Whenever you change the size of a containers components or add/remove components you must ask the container to run through its component hierarchy and check the size requirements of all its children and lay them out again, ie, do a new layout. The JComponent method for this isrevalidate. If you are working in the AWT you must use the Component/(overridden in)Container method validate, sometimes preceded by a call to the invalidate method. Some people prefer the validate method over revalidate. These are methods used to update guis by asking for a renewed layout. For economy you can call one (sometimes with invalidate, but rarely) of these methods on the smallest component/container that includes all the containers needing the renewed layout, ie, keep the action as localized as possible.
    When the rendering of components has changed, things like colors, borders and text, we need to ask the components to repaint themselves. The easy way to do this is to call repaint on the gui. For economy you can call repaint on the smallest component that contains all the components needing repainting. Some classes like those in the JTextComponent group have their own internal repainting calls so they will repaint themselves when changes are made.
    In making guis, especially elaborate ones, it seems to take some playful experimentation to find out what is needed to get what you want. Sometimes it is a call to revalidate, sometimes a call to repaint, sometimes both. You just have to experiment.

  • Problem with jframe has jtextfield and jpanel

    hi all
    i ve a jframe with some components on it
    of these components a jpanel that i repaint each time i want
    and a textfield for chatting between players
    the problem is as follows
    some times when i click the textfield after repaining the panel
    it can not be activated and the caret does not appear
    when i click any other component out or in the frame
    and return i get it active and in a good state
    i use single buffer for repapint
    thanks for reading
    i'm waiting for response

    Your best bet here is to show us your code. We don't want to see all of it, but rather you should condense your code into the smallest bit that still compiles, has no extra code that's not relevant to your problem, but still demonstrates your problem, in other words, an SSCCE (Short, Self Contained, Correct (Compilable), Example). For more info on SSCCEs please look here:
    [http://homepage1.nifty.com/algafield/sscce.html|http://homepage1.nifty.com/algafield/sscce.html]
    Again, if the code is compilable and runnable more people will be able to help you.
    Also, when posting your code, please use code tags so that your code will retain its formatting and be readable. To do this, you will need to paste already formatted code into the forum, highlight this code, and then press the "code" button at the top of the forum Message editor prior to posting the message. You may want to click on the Preview tab to make sure that your code is formatted correctly. Another way is to place the tag &#91;code] at the top of your block of code and the tag &#91;/code] at the bottom, like so:
    &#91;code]
      // your code block goes here.
      // note the differences between the tag at the top vs the bottom.
    &#91;/code]

  • Display image in JPanel without saving any file to disk

    Hi,
    I am fetching images from database. I am saving this image, display in JPanel and delete it. But this is not actually I want.
    I wish to fetch this image as stream , store in memory and display in JPanel without saving any fiel in disk.
    I wonder if it is Possible or any used implementation that I can use in my project. Any idea or experienced knowledge is enough.
    Thanks

    In what format is the image coming to you from the database? If it's an InputStream subclass, just use javax.imageio.ImageIO:
    InputStream in = getImageInputStream();
    BufferedImage image = null;
    try {
       image = ImageIO.read(in);
    } finally {
       in.close();
    // ... Display image in your JPanel as you have beenIf you receive the image as an array of bytes, use the same method as above, but with a ByteArrayInputStream:
    byte[] imageData = getImageData();
    ByteArrayInputStream in = new ByteArrayInputStream(imageData);
    BufferedImage image = null;
    try {
       image = ImageIO.read(in);
    } finally {
       in.close();
    // ... Display image in your JPanel as you have been

  • Help needed in printing a JPanel in Swing..

    Hi,
    I'm working on a Printing task using Swing. I'm trying to print a JPanel. All i'm doing is by creating a "java.awt.print.Book" object and adding (append) some content to it. And these pages are in the form of JPanel. I've created a separate class for this which extends the JPanel. I've overridden the print() method. I have tried many things that i found on the web and it simply doesn't work. At the end it just renders an empty page, when i try to print it. I'm just pasting a sample code of the my custom JPanel's print method here:
    public int print(Graphics g, PageFormat pageformat, int pagenb)
        throws PrinterException {
    //if(pagenb != this.pagenb) return Printable.NO_SUCH_PAGE;
    Graphics2D g2d = (Graphics2D)g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2d.setClip(0, 0, this.getWidth(), this.getHeight());
    g2d.setColor(Color.BLACK);
    //disable double buffering before printing
    RepaintManager rp = RepaintManager.currentManager(this);
    rp.setDoubleBufferingEnabled(false);
    this.paint(g2d);
    rp.setDoubleBufferingEnabled(true);
    return Printable.PAGE_EXISTS;     
    }Please help me where i'm going wrong. I'm just trying to print the JPanel with their contents.
    Thanks in advance.

    Hi,
    Try this
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.LayoutManager;
    import java.awt.event.ActionEvent;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.swing.AbstractAction;
    import javax.swing.JColorChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    public class PrintablePanel extends JPanel implements Printable {
        private static final long serialVersionUID = 1L;
        public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final PrintablePanel target = new PrintablePanel(
                   new BorderLayout());
              target.add(new JColorChooser());
              frame.add(target, BorderLayout.CENTER);
              JToolBar toolBar = new JToolBar();
              frame.add(toolBar, BorderLayout.PAGE_START);
              toolBar.add(new AbstractAction("Print") {
                  private static final long serialVersionUID = 1L;
                  @Override
                  public void actionPerformed(ActionEvent event) {
                   PrinterJob printerJob = PrinterJob.getPrinterJob();
                   printerJob.setPrintable(target);
                   try {
                       printerJob.print();
                   } catch (PrinterException e) {
                       e.printStackTrace();
              frame.pack();
              frame.setVisible(true);
        public PrintablePanel() {
         super();
        public PrintablePanel(LayoutManager layout) {
         super(layout);
        @Override
        public int print(Graphics g, PageFormat format, int page)
             throws PrinterException {
         if (page == 0) {
             Graphics2D g2 = (Graphics2D) g;
             g2.translate(format.getImageableX(), format.getImageableY());
             print(g2);
             g2.translate(-format.getImageableX(), -format.getImageableY());
             return Printable.PAGE_EXISTS;
         } else {
             return Printable.NO_SUCH_PAGE;
    }Piet
    Edit: Sorry. Just now I see that you want to use the Swing print mechanism. But I guess the implementation of the Printable interface remains the same.
    Edited by: pietblok on 14-nov-2008 17:23

  • HELP!!!  Adding JPanel to JPanel (long code sample)

    I need some help here. I have been stuck on this for more time than I care to admit. Now this project is due by Monday(tomorrow)! Why does the graph not appear in the tabbed pane "trend report"?? the TrendReport class on line 2131 creates the graph. Line 56 creates an instance. and line 831 adds it to the tabbed pane. everything shows up except the graph.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.text.*;
    import java.util.*;
    import java.lang.*;
    import javax.swing.JPopupMenu;
    import javax.swing.JPanel;
    import javax.swing.JMenu;
    import javax.swing.JMenuItem;
    import javax.swing.JLabel;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.JTable;
    import javax.swing.filechooser.*;
    /*<br>
    *A332IWon Class<br>
    *CIS 32 / Cuesta College<br>
    *Assignment     3<br>
    *Due Date 10-08-03<br>
    *<br>
    *<br>
    *<br> >>>>>>>>> Start filling in your class discription here <<<<<<<<<<<<
            >>>>>>>>> And Start filling in your method discriptions <<<<<<<<<<<
    *<br>
    *<br>@author<br>
    *Chris Hoffman, Michael Krempely, Rudy Kalnin, Scott Thayer and Frank Randise<br>
    *@version 10.16<br>
    *<br>
    *<br>
    public class A332IWon extends JFrame
         * Class to handle all data input, output, sorting and display handling.
        private A332IWonEngine engine = new A332IWonEngine();
          * Instance of the inner class "QuickTable" called "quickTabke"
         private QuickTable quickTable = new QuickTable();
          * Instance of the inner class "BasicPayTable" called "basicPayTable"
        private BasicPayTable basicPayTable = new BasicPayTable();
         * Instance of the inner class "TrendReport" called "trendReport"
        private TrendReport trendReport = new TrendReport();       
          * Container that holds all panels, labels, and text fields
         private Container c = getContentPane();
          * The menu bar at the top of the application
         private JMenuBar bar = new JMenuBar();
          * Menu bar header called "File"
         private JMenu menuFile = new JMenu("File");
          * Menu bar header called "Edit"
         private JMenu menuEdit = new JMenu("Edit");
          * Menu bar header called "Reports"
        private JMenu menuReports = new JMenu("Reports");
          * Menu bar header called "Help"
        private JMenu menuHelp = new JMenu("Help");
          * Menu item called "Import" a sub menu item of "menuFile"
         private JMenuItem fileImport = new JMenu("Import");
          * Menu item called "Employee Text File" a sub menu item of "fileImport"
          * which in turn is a sub item of "menuFile"
         private JMenuItem fileEmpTxtFile = new JMenuItem("Employee Text File");
          * Menu item called "Pay Info File" a sub menu item of "fileImport"
          * which in turn is a sub item of "menuFile"
         private JMenuItem filePayInfoFile = new JMenuItem("Pay Info File");
          * Menu item called "Open" a sub menu item of "menuFile"
           private JMenuItem fileOpen = new JMenuItem("Open");
          * Menu item called "Save" a sub menu item of "menuFile"
           private JMenuItem fileSave = new JMenuItem("Save");
          * Menu item called "Exit" a sub menu item of "menuFile"
           private JMenuItem fileExit = new JMenuItem("Exit");
          * Menu item called "Search" a sub menu item of "menuEdit"
          private JMenuItem editSearch = new JMenu("Search");
          * Menu item called "Add/Remove" a sub menu item of "menuEdit"
           private JMenuItem editAddRemove = new JMenuItem("Add/Remove");
          * Menu item called "By ID #" a sub menu item of "editSearch"
          * which in turn is a sub item of "menuEdit"
           private JMenuItem editID = new JMenuItem("By ID #");
          * Menu item called "By name" a sub menu item of "editSearch"
          * which in turn is a sub item of "menuEdit"
           private JMenuItem editName = new JMenuItem("By name");
          * Menu item called "Basic Pay" a sub menu item of "menuReports"
           private JMenuItem repBasicPay = new JMenuItem("Basic Pay");
          * Menu item called "Trend" a sub menu item of "menuReports"
           private JMenuItem repTrend = new JMenuItem("Trend");
          * Menu item called "About" a sub menu item of "menuHelp"
           private JMenuItem helpAbout = new JMenuItem("About");
          * The tabbed pane that holds our table, reports and table editing capabilities
         private JTabbedPane empInfoTabPane = new JTabbedPane();
          * Main panel located in center that holds the tabbed pane "empInfoTabPane"
         private JPanel pCenterMain = new JPanel(new FlowLayout(FlowLayout.LEFT,25,30));
          * Panel that holds the table "table"
         private JPanel pTable = new JPanel(new GridLayout(2,1));
          * Main panel that holds the Basic Pay Report(s)
         private JPanel pBasicPayRep = new JPanel(new FlowLayout(FlowLayout.CENTER,10,20));
          * Main panel that holds the Trend Report(s)
         private JPanel pTrendRep = new JPanel(new FlowLayout(FlowLayout.CENTER,10,10));
          * Panel that holds all the add/remove fields, combo boxes and buttons
         private JPanel pAddRemove = new JPanel(new GridLayout(2,1));
            * Panel and Labels for Basic Pay Report
           private JPanel pBasicPayRepMain = new JPanel(new GridLayout(2,1));
          * Holds the pBasicPayGridLeft and pBasicPayGridRight
         private JPanel pBasicPayRepBot = new JPanel(new FlowLayout(FlowLayout.CENTER));
          * Holds the labels for each report
          * Recent Pay Period Worked, Cumulative Pay, Average Pay
         private JPanel pBasicPayGridLeft = new JPanel(new FlowLayout(FlowLayout.LEFT));
          * Holds all the basic pay report information for
          * Recent Pay Period Worked, Cumulative Pay, Average Pay
         private JPanel pBasicPayGridRight = new JPanel(new FlowLayout(FlowLayout.LEFT,20,0));
          * Displays the total number of employees that worked in the current pay period
         private JLabel txtTotalAllEmployees = new JLabel("0");
          * Displays the total number of Salaried employees that worked in the current pay period
         private JLabel txtTotalSalaried = new JLabel("0");
          * Displays the total number of Hourly employees that worked in the current pay period
         private JLabel txtTotalHourly = new JLabel("0");
          * Displays the total number of Temporary employees that worked in the current pay period
         private JLabel txtTotalTemporary = new JLabel("0");
          * Displays the total number of Contract employees that worked in the current pay period
         private JLabel txtTotalContract = new JLabel("0");
          * Displays the cumulative hourly rate in the current pay period
         private JLabel txtCumHourlyRate = new JLabel("0.00");
          * Displays the cumulative hours workded in the current pay period
           private JLabel txtCumHoursWorked = new JLabel("0");
          * Displays the cumulative gross pay in the current pay period
           private JLabel txtCumGrossPay = new JLabel("0.00");
          * Displays the cumulative tax paid in the current pay period
           private JLabel txtCumTax = new JLabel("0.00");
          * Displays the cumulative net pay in the current pay period
           private JLabel txtCumNetPay = new JLabel("0.00");
          * Displays the average hourly rate in the current pay period
           private JLabel txtAvgHourlyRate = new JLabel("0.00");
          * Displays the average hours workded in the current pay period
           private JLabel txtAvgHoursWorked = new JLabel("0.0");
          * Displays the average gross pay in the current pay period
           private JLabel txtAvgGrossPay = new JLabel("0.00");
          * Displays the average tax paid in the current pay period
           private JLabel txtAvgTax = new JLabel("0.00");
          * Displays the average net pay in the current pay period
           private JLabel txtAvgNetPay = new JLabel("0.00");
          * The table "table" created in the instance "quickTable"
         private JTable table = new JTable(quickTable);
          * The table "table2" created in the instance "BasicPayTable"
         private JTable table2 = new JTable(basicPayTable);
          * Turns the table "table" into a scroll pane
        private JScrollPane scrollpane = new JScrollPane(table);
          * Turns the table "table2" into a scroll pane2
        private JScrollPane scrollpane2 = new JScrollPane(table2);
          * **** Future Button to update the employee information in "table"
        private JButton updateEmplInfo = new JButton("Update");
         * Add button to add an employee
        private JButton bAdd = new JButton("Add");
         * Remove button to remove an employee
         private JButton bRemove = new JButton("Remove");
         * Search by employee ID button
         private JButton bSearchId = new JButton("Search");
         * Search by employee name button
         private     JButton bSearchName = new JButton("Search");
         * Texfield collects an employees ID number
        private JTextField fieldID = new JTextField(6);
         * Texfield collects an employees Last name
         private JTextField fieldLastName = new JTextField(22);
         * Texfield collects an employees First name
         private JTextField fieldFirstName = new JTextField(15);
         * Texfield collects an employees Middle initial
         private JTextField fieldMiddleInitial = new JTextField(1);
         * Texfield collects an employees street address
         private JTextField fieldStreetAddress = new JTextField(22);
         * Texfield collects an employees city lived in
         private JTextField fieldCity = new JTextField(18);
         * Texfield collects an employees state lived in
         private JTextField fieldState = new JTextField(2);
         * Texfield collects an employees zip code
         private JTextField fieldZip = new JTextField(6);
         * Texfield collects an employees hourly rate
         private JTextField fieldHourlyRate = new JTextField("0.00",6);
         * Texfield collects an employees year they started working
         private JTextField fieldYYYY = new JTextField("YYYY",4);
         * Texfield collects an employees ID number to perform a search with
         private JTextField fieldSearchById = new JTextField(6);
         * Texfield collects an employees last name to perform a search with
         private JTextField fieldSearchByLast = new JTextField(22);
         * Texfield collects an employees first name to perform a search with
         private     JTextField fieldSearchByFirst = new JTextField(15);
         * Texfield collects an employees middle initial to perform a search with
         private     JTextField fieldSearchByMiddle = new JTextField(1);
          * Background color designed to mimic Microsofts's default desktop color
         private Color MS = new Color(64,128,128);
         * Color used to simulate a manilla folder
         * <br>Used on the folders
         private Color manilla = new Color(252,220,140);
         * Color a complimenting color to "manilla" and "MS"
         * <br>Used as an accent in the search frames and tabs
         private Color seaFoam = new Color(156,198,172);
         * Color a complimenting color to "manilla" and "MS"
         * <br>Used as an accent in the tabs
         private Color babyBlue = new Color(170,220,238);
         * Color a complimenting color to "manilla" and "MS"
         * <br>Used as an accent in the tabs
         private Color lightPink = new Color(255,204,207);
         * Array of Strings: the 12 months of the year
         private String [] monthMM = {"MM","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
                                             "Sep","Oct","Nov","Dec"};
         * Array of Strings: the days of the month
         private String [] dayDD = {"DD","01","02","03","04","05","06","07","08","09","10","11",
                                          "12","13","14","15","16","17","18","19","20","21","22",
                                          "23","24","25","26","27","28","29","30","31"};
         * Array of Strings: employee types
         * <br>"Salaried","Hourly","Temporary","Contract"
         private String [] emplType = {"Emp Type","Salaried","Hourly","Temporary","Contract"};
         * String holds the month by using getSelectedItem()
         private String sMonth = "";
         * String holds the day by using getSelectedItem()
         private String sDay = "";
         * String holds the entire hire date
         private String sHireDate = "";
         * String holds the entire employee address
         private String sEmpAddress = "";
         * Double the horly rate paid to an employee
         private double hourlyRate = 0.0;
         * Drop down combo box displays the months of the year
        private JComboBox listMM = new JComboBox(monthMM);
         * Drop down combo box displays the days of the month
         private JComboBox listDD = new JComboBox(dayDD);
         * Drop down combo box displays the employee types
         private JComboBox listEmplType = new JComboBox(emplType);
         private JPanel pTrendReportMain = new JPanel();
         private JPanel pTrendReport = new JPanel();
         private JPanel pTrendRepMain = new JPanel(new GridLayout(2,1));
         private JPanel pTrendBot = new JPanel(new FlowLayout(FlowLayout.CENTER));
         private JPanel pTrendGridLeft = new JPanel(new FlowLayout(FlowLayout.LEFT));
         private JPanel pTrendGridRight = new JPanel(new FlowLayout(FlowLayout.LEFT,20,0));
         private JButton button, button2;
         private JLabel []JLab = new JLabel[4];
         private JTextField titletxt;
         private JTextField []Text = new JTextField[5];
         private JTextField []labeltxt = new JTextField[5];
         private JLabel txtTrendTotalEmployees = new JLabel("0");
         private JLabel txtTrendCumHourlyRate = new JLabel("0.00");
         private JLabel txtTrendAvgHourlyRate = new JLabel("0.00");
         private JLabel txtTrendTotalSalaried = new JLabel("0");
         private JLabel txtTrendCumHoursWorked = new JLabel("0");
         private JLabel txtTrendAvgHoursWorked = new JLabel("0.0");
         private JLabel txtTrendTotalHourly = new JLabel("0");
         private JLabel txtTrendCumGrossPay = new JLabel("0.00");
         private JLabel txtTrendAvgGrossPay = new JLabel("0.00");
         private JLabel txtTrendTotalTemporary = new JLabel("0");
         private JLabel txtTrendCumTax = new JLabel("0.00");
         private JLabel txtTrendAvgTax = new JLabel("0.00");
         private JLabel txtTrendTotalContract = new JLabel("0");
         private JLabel txtTrendCumNetPay = new JLabel("0.00");
         private JLabel txtTrendAvgNetPay = new JLabel("0.00");
         //Don't know if we can use these yet
         //private JLabel lPayPeriodStart = new JLabel("YYYY MM PP");
         //private JLabel lPayPeriodEnd = new JLabel("YYYY MM PP");
          * Standard constructor
          * <br>Call the main methods required to get the application to start
         public A332IWon(String title)
              super(title);
              menuDialogBar();
              setUpPanels();
              setContainerLayout();
              listenToMenuBar();
              listenToButtons();
              addWindowListener(new CloseWindow());
          * Contains all the ActionListener events associated with the menu bar
         public void listenToMenuBar()
              fileEmpTxtFile.addActionListener(quickTable);
              filePayInfoFile.addActionListener(quickTable);
              fileOpen.addActionListener(quickTable);
              fileSave.addActionListener(quickTable);
              fileExit.addActionListener(quickTable);
              editAddRemove.addActionListener(quickTable);
              editID.addActionListener(quickTable);
              editName.addActionListener(quickTable);
              repBasicPay.addActionListener(quickTable);
              repTrend.addActionListener(quickTable);
              helpAbout.addActionListener(quickTable);
          * Contains all ActionListener events associated with buttons and combo boxes
         public void listenToButtons()
              bAdd.addActionListener(quickTable);
              bRemove.addActionListener(quickTable);
              listMM.addActionListener(quickTable);
              listDD.addActionListener(quickTable);
              listEmplType.addActionListener(quickTable);
              bSearchId.addActionListener(quickTable);
              bSearchName.addActionListener(quickTable);
          * Contains the menu bar, the menus, and all the sub menu items
         public void menuDialogBar()
               JLabel menuShim = new JLabel("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
                                                 + "XXXXXXXXXXXXXXXXXXXXXXx12345");
               setJMenuBar(bar);
               bar.add(menuFile);
               bar.add(menuEdit);
               bar.add(menuReports);
               bar.add(menuHelp);
               bar.add(menuShim);
               menuShim.setVisible(false);
               menuFile.add(fileImport);
               fileImport.add(fileEmpTxtFile);
               fileImport.add(filePayInfoFile);
               menuFile.add(fileOpen);
               menuFile.add(fileSave);
               menuFile.add(fileExit);
               menuEdit.add(editAddRemove);
               menuEdit.add(editSearch);
               editSearch.add(editID);
               editSearch.add(editName);
               menuReports.add(repBasicPay);
               menuReports.add(repTrend);
               menuHelp.add(helpAbout);
          * Sets the layout for the container "c" and sets pCenterMain centered in "c"
         public void setContainerLayout()
              c.setLayout(new BorderLayout());
              c.add(pCenterMain, "Center");
          * Sets up the main panels needed at run time
         public void setUpPanels()
              centerMainPanel();
              tabbedPane();
              tabPanels();
              addRemovePanel();
              basicPayReportMain();
              trendReportMain();
          * Sets up the main panel with the tabbed pane "empInfoTabPane"
         public void centerMainPanel()
              pCenterMain.add(empInfoTabPane);
              pCenterMain.setBackground(MS);
          * Sets up the tabbed pane with the table, and eddit block,
          * basic pay report, and trend report
         public void tabbedPane()
             empInfoTabPane.addTab("Employee Information",pTable);
             empInfoTabPane.addTab("Basic Pay Report",pBasicPayRep);
             empInfoTabPane.addTab("Trend Report",pTrendRep);
             //empInfoTabPane.setBackground(manilla);
             //empInfoTabPane.setBackgroundAt(0,manilla);
             empInfoTabPane.setBackgroundAt(0,seaFoam);
             empInfoTabPane.setBackgroundAt(1,lightPink);
             empInfoTabPane.setBackgroundAt(2,babyBlue);
             //AUTO_RESIZE_OFF
             //empInfoTabPane.setEnabledAt(0,false);
          * Sets up the panels in the tabbed pane
         public void tabPanels()
              //JLabel tabTrendRep = new JLabel("This area will show a Trend report");
             JPanel pTableTop = new JPanel(new FlowLayout(FlowLayout.CENTER,20,20));
             JPanel pTableBottom = new JPanel(new FlowLayout(FlowLayout.LEFT));
              scrollpane.setPreferredSize(new Dimension(695,185));
              scrollpane2.setPreferredSize(new Dimension(695,185));
              pTableTop.add(scrollpane);
              pTableBottom.add(pAddRemove);
              pTableTop.setBackground(manilla);
              pTableBottom.setBackground(manilla);
              pTable.add(pTableTop);
              pTable.add(pTableBottom);
              pBasicPayRep.add(pBasicPayRepMain);
             pBasicPayRep.setBackground(manilla);
             pTrendRep.add(pTrendRepMain);
             pTrendRep.setBackground(manilla);
          * Sets up the basic pay report main panel that holds the table and the bottom pay report
         public void basicPayReportMain()
              pBasicPayRepMain.add(scrollpane2);
              pBasicPayRepMain.add(pBasicPayRepBot);
              basicPayRepTotalsPanel();
          * Sets up the basic pay report grid panel under the basic pay report table.
         public void basicPayRepTotalsPanel()
              JPanel pBasicPayLeftRight = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
                pBasicPayRepBot.add(pBasicPayLeftRight);
                pBasicPayRepBot.setBackground(manilla);
                pBasicPayLeftRight.add(pBasicPayGridLeft);
                pBasicPayLeftRight.add(pBasicPayGridRight);
                pBasicPayLeftRight.setBackground(manilla);
                basicPayGridLeft();
                basicPayGridRight();
          * Sets up the left grid of the basic pay report grid panel.
         public void basicPayGridLeft()
              JPanel pColumn1 = new JPanel(new GridLayout(10,1));
              JLabel lblTotalEmployees = new JLabel("Recent Pay Period Worked");
              JLabel lblCumulativePay = new JLabel("Cumulative Pay");
              JLabel lblAveragePay = new JLabel("Average Pay");
              JLabel lblShim1 = new JLabel("X");
              JLabel lblShim2 = new JLabel("X");
              JLabel lblShim3 = new JLabel("X");
              lblShim1.setForeground(manilla);
              lblShim2.setForeground(manilla);
              lblShim3.setForeground(manilla);
              pColumn1.add(lblTotalEmployees);
              pColumn1.add(lblShim1);
              pColumn1.add(new JLabel(" "));
              pColumn1.add(new JLabel(" "));
              pColumn1.add(lblCumulativePay);
              pColumn1.add(lblShim2);
              pColumn1.add(new JLabel(" "));
              pColumn1.add(new JLabel(" "));
              pColumn1.add(lblAveragePay);
              pColumn1.add(lblShim3);
              pColumn1.setBackground(manilla);
              lblTotalEmployees.setForeground(Color.black);
              lblCumulativePay.setForeground(Color.black);
              lblAveragePay.setForeground(Color.black);
              pBasicPayGridLeft.add(pColumn1);
              pBasicPayGridLeft.setBackground(manilla);
          * Sets up the right grid of the basic pay report grid panel.
          * <br>This is one narly method
         public void basicPayGridRight()
              JPanel pColumn1 = new JPanel(new GridLayout(10,1));
              JPanel pColumn2 = new JPanel(new GridLayout(10,1));
              JPanel pColumn3 = new JPanel(new GridLayout(10,1));
              JPanel pColumn4 = new JPanel(new GridLayout(10,1));
              JPanel pColumn5 = new JPanel(new GridLayout(10,1));
                JLabel lblTotalEmployees = new JLabel("Employees");
                JLabel lblTotalSalaried = new JLabel("Salaried");
                JLabel lblTotalHourly = new JLabel("Hourly");
                JLabel lblTotalTemporary = new JLabel("Temporary");
                JLabel lblTotalContract = new JLabel("Contract");
                JLabel lblCumHourlyRate = new JLabel("Pay Rate");
                JLabel lblCumHoursWorked = new JLabel("Hours Worked");
                JLabel lblCumGrossPay = new JLabel("Gross Pay");
                JLabel lblCumTax = new JLabel("Flat Tax 15%");
                JLabel lblCumNetPay = new JLabel("Net Pay");
                JLabel lblAvgHourlyRate = new JLabel("Pay Rate");
                JLabel lblAvgHoursWorked = new JLabel("Hours Worked");
                JLabel lblAvgGrossPay = new JLabel("Gross Pay");
                JLabel lblAvgTax = new JLabel("Flat Tax 15%");
                JLabel lblAvgNetPay = new JLabel("Net Pay");
              pColumn1.add(lblTotalEmployees);
              pColumn1.add(txtTotalAllEmployees);
              pColumn1.add(new JLabel(" "));
              pColumn1.add(new JLabel(" "));
              pColumn1.add(lblCumHourlyRate);
              pColumn1.add(txtCumHourlyRate);
              pColumn1.add(new JLabel(" "));
              pColumn1.add(new JLabel(" "));
              pColumn1.add(lblAvgHourlyRate);
              pColumn1.add(txtAvgHourlyRate);
              pColumn1.setBackground(manilla);
              lblTotalEmployees.setForeground(Color.black);
              txtTotalAllEmployees.setForeground(Color.black);
              lblCumHourlyRate.setForeground(Color.black);
              txtCumHourlyRate.setForeground(Color.black);
              lblAvgHourlyRate.setForeground(Color.black);
              txtAvgHourlyRate.setForeground(Color.black);
              pColumn2.add(lblTotalSalaried);
              pColumn2.add(txtTotalSalaried);
              pColumn2.add(new JLabel(" "));
              pColumn2.add(new JLabel(" "));
              pColumn2.add(lblCumHoursWorked);
              pColumn2.add(txtCumHoursWorked);
              pColumn2.add(new JLabel(" "));
              pColumn2.add(new JLabel(" "));
              pColumn2.add(lblAvgHoursWorked);
              pColumn2.add(txtAvgHoursWorked);
              pColumn2.setBackground(manilla);
              lblTotalSalaried.setForeground(Color.black);
              txtTotalSalaried.setForeground(Color.black);
              lblCumHoursWorked.setForeground(Color.black);
              txtCumHoursWorked.setForeground(Color.black);
              lblAvgHoursWorked.setForeground(Color.black);
              txtAvgHoursWorked.setForeground(Color.black);
              pColumn3.add(lblTotalHourly);
              pColumn3.add(txtTotalHourly);
              pColumn3.add(new JLabel(" "));
              pColumn3.add(new JLabel(" "));
              pColumn3.add(lblCumGrossPay);
              pColumn3.add(txtCumGrossPay);
              pColumn3.add(new JLabel(" "));
              pColumn3.add(new JLabel(" "));
              pColumn3.add(lblAvgGrossPay);
              pColumn3.add(txtAvgGrossPay);
              pColumn3.setBackground(manilla);
              lblTotalHourly.setForeground(Color.black);
              txtTotalHourly.setForeground(Color.black);
              lblCumGrossPay.setForeground(Color.black);
              txtCumGrossPay.setForeground(Color.black);
              lblAvgGrossPay.setForeground(Color.black);
              txtAvgGrossPay.setForeground(Color.black);
              pColumn4.add(lblTotalTemporary);
              pColumn4.add(txtTotalTemporary);
              pColumn4.add(new JLabel(" "));
              pColumn4.add(new JLabel(" "));
              pColumn4.add(lblCumTax);
              pColumn4.add(txtCumTax);
              pColumn4.add(new JLabel(" "));
              pColumn4.add(new JLabel(" "));
              pColumn4.add(lblAvgTax);
              pColumn4.add(txtAvgTax);
              pColumn4.setBackground(manilla);
              lblTotalTemporary.setForeground(Color.black);
              txtTotalTemporary.setForeground(Color.black);
              lblCumTax.setForeground(Color.black);
              txtCumTax.setForeground(Color.black);
              lblAvgTax.setForeground(Color.black);
              txtAvgTax.setForeground(Color.black);
              pColumn5.add(lblTotalContract);
              pColumn5.add(txtTotalContract);
              pColumn5.add(new JLabel(" "));
              pColumn5.add(new JLabel(" "));
              pColumn5.add(lblCumNetPay);
              pColumn5.add(txtCumNetPay);
              pColumn5.add(new JLabel(" "));
              pColumn5.add(new JLabel(" "));
              pColumn5.add(lblAvgNetPay);
              pColumn5.add(txtAvgNetPay);
              pColumn5.setBackground(manilla);
              lblTotalContract.setForeground(Color.black);
              txtTotalContract.setForeground(Color.black);
              lblCumNetPay.setForeground(Color.black);
              txtCumNetPay.setForeground(Color.black);
              lblAvgNetPay.setForeground(Color.black);
              txtAvgNetPay.setForeground(Color.black);
              pBasicPayGridRight.add(pColumn1);
              pBasicPayGridRight.add(pColumn2);
              pBasicPayGridRight.add(pColumn3);
              pBasicPayGridRight.add(pColumn4);
              pBasicPayGridRight.add(pColumn5);
              pBasicPayGridRight.setBackground(manilla);
          * Sets up the trend report main panel that holds the graph and the bottom trend report
         public void trendReportMain()//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
              //pTrendReportMain.add(trendReport);// changed pTrendReport to trendReport
              pTrendRepMain.add(trendReport);//changed pTrendRepMain to trendReport
              pTrendRepMain.add(pTrendBot);
              trendReportTotalsPanel();
         public void trendReportTotalsPanel()
              JPanel pTrendLeftRight = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
                pTrendBot.add(pTrendLeftRight);
                pTrendBot.setBackground(manilla);
                pTrendLeftRight.add(pTrendGridLeft);
                pTrendLeftRight.add(pTrendGridRight);
                pTrendLeftRight.setBackground(manilla);
                trendReportLeft();
                trendReportRight();
         public void trendReportLeft()
              JPanel pColumn1 = new JPanel(new GridLayout(10,1));
              JLabel lblTotalEmployees = new JLabel("Recent Pay Period Worked");
              JLabel lblCumulativePay = new JLabel("Cumulative Pay Info");
              JLabel lblAveragePay = new JLabel("Average Pay Info");
              JLabel lblShim1 = new JLabel("X");
              JLabel lblShim2 = new JLabel("X");
              JLabel lblShim3 = new JLabel("X");
              lblShim1.setForeground(manilla);
              lblShim2.setForeground(manilla);
              lblShim3.setForeground(manilla);
              pColumn1.add(lblTotalEmployees);
              pColumn1.add(lblShim1);
              pColumn1.add(new JLabel(" "));
              pColumn1.add(new JLabel(" "));
              pColumn1.add(lblCumulativePay);
              pColumn1.add(lblShim2);
              pColumn1.add(new JLabel(" "));
              pColumn1.add(new JLabel(" "));
              pColumn1.add(lblAveragePay);
              pColumn1.add(lblShim3);
              pColumn1.setBackground(manilla);
              lblTotalEmployees.setForeground(Color.black);
              lblCumulativePay.setForeground(Color.black);
              lblAveragePay.setForeground(Color.black);
              pTrendGridLeft.add(pColumn1);
              pTrendGridLeft.setBackground(manilla);
         public void trendReportRight()
              JPanel pColumn1 = new JPanel(new GridLayout(10,1));
              JPanel pColumn2 = new JPanel(new GridLayout(10,1));
              JPanel pColumn3 = new JPanel(new GridLayout(10,1));
              JPanel pColumn4 = new JPanel(new GridLayout(10,1));
              JPanel pColumn5 = new JPanel(new GridLayout(10,1));
                JLabel lblTotalEmployees = new JLabel("Employees");
                JLabel lblTotalSalaried = new JLabel("Salaried");
                JLabel lblTotalHourly = new JLabel("Hourly");
                JLabel lblTotalTemporary = new JLabel("Temporary");
                JLabel lblTotalContract = new JLabel("Contract");
                JLabel lblCumHourlyRate = new JLabel("Pay Rate");
                JLabel lblCumHoursWorked = new JLabel("Hours Worked");
                JLabel lblCumGrossPay = new JLabel("Gross Pay");
                JLabel lblCumTax = new JLabel("Flat Tax 15%");
                JLabel lblCumNetPay = new JLabel("Net Pay");
                JLabel lblAvgHourlyRate = new JLabel("Pay Rate");
                JLabel lblAvgHoursWorked = new JLabel("Hours Worked");
                JLabel lblAvgGrossPay = new JLabel("Gross Pay");
                JLabel lblAvgTax = new JLabel("Flat Tax 15%");
                JLabel lblAvgNetPay = new JLabel("Net Pay");
              pColumn1.add(lblTotalEmployees);
              pColumn1.add(txtTrendTotalEmployees);     //txtTrendTotalEmployees
              pColumn1.add(new JLabel                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            &n

    This class declaration won't do for loading into a JTabbedPane
    public class TrendReport extends JFrame implements ActionListener {Try this in it's place
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class TrendRx {
      public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        TrendReport trendReport = new TrendReport();
        f.getContentPane().add(trendReport);
        f.setSize(500,300);
        f.setLocation(100,100);
        f.setVisible(true);
    class TrendReport extends JPanel implements ActionListener {
      int width;
      int height;
      JButton button;
      int []bar = new int[4];
      float []flote = {1395,1296,1402,1522};
      String []valuesInput = {"1395","1296","1402","1522"};
      String str = "", title="Title goes here";
      String []barLabels = {
        "pp01, Oct. 2003","pp02, Oct. 2003","pp01, Nov. 2003","pp02, Nov. 2003"
      String []percent = {"","","",""};
      JLabel []JLab = new JLabel[4];
      JTextField titletxt;
      JTextField []Text = new JTextField[5];
      JTextField []labeltxt = new JTextField[5];
      boolean pieChart;
      public TrendReport() {
        setOpaque(false);
        setLayout(new FlowLayout() );
        button = new JButton("Bar TrendReport");
        button.addActionListener(this);
    //    for (int k=0; k<4; k++){
    //      str = Integer.toString(k+1);
        add(button);
      public void paintComponent(Graphics g) {
        width = getWidth();
        height = getHeight();
        Graphics2D g2 = (Graphics2D)g;                    
        g2.setColor(new Color(223,222,224));
        g2.fillRect(0,0,width,height);
        g2.setColor(Color.orange);
        if(pieChart) {
          g2.fillArc(getW(30), getH(130), getW(220), getH(220), 90, -bar[0]);
          g2.fillRect(getW(270), getH(170), getW(30), getH(20));
        else
          g2.fillRect(getW(30), getH(150), getW(bar[0]), getH(30));
        g2.setColor(Color.green);
        if(pieChart) {
          g2.fillArc(getW(30), getH(130), getW(220), getH(220), 90-bar[0], -bar[1]);
          g2.fillRect(getW(270), getH(210), getW(30), getH(20));
        else
          g2.fillRect(getW(30), getH(190), getW(bar[1]), getH(30));
        g2.setColor(Color.red);
        if(pieChart) {
          g2.fillArc(getW(30), getH(130), getW(220), getH(220),
                     90-(bar[0]+bar[1]), -bar[2]);
          g2.fillRect(getW(270), getH(250), getW(30), getH(20));
        else
          g2.fillRect(getW(30), getH(230), getW(bar[2]), getH(30));
        g2.setColor(Color.blue);
        if(pieChart) {
          g2.fillArc(getW(30), getH(130), getW(220), getH(220),
                     90-(bar[0]+bar[1]+bar[2]), -bar[3]);
          g2.fillRect(getW(270), getH(290), getW(30), getH(20));
        else
          g2.fillRect(getW(30), getH(270), getW(bar[3]), getH(30));
        g2.setColor(Color.black);
        g2.setFont(new Font("Arial", Font.BOLD, 18));
        if(pieChart)
          g2.drawString(title, getW(220), getH(142));
        else
          g2.drawString(title, getW(50), getH(132));
        g2.setFont(new Font("Arial", Font.PLAIN,16));
        int temp=0;
        if(pieChart)
          temp = 185;
        else
          temp = 172;
        for(int j=0; j <4; j++) {
          if(pieChart)
            g2.drawString("$"+valuesInput[j]+" "+barLabels[j]+percent[j],
                          getW(305), getH(temp));//XXXXXXXXXXXXXXX
          else
            g2.drawString("$"+valuesInput[j]+" "+barLabels[j]+percent[j],
                          getW(bar[j]+40), getH(temp));
          temp += 40;
        if(!pieChart){
          g2.drawLine(getW(30), getH(130), getW(30), getH(300));
          g2.drawLine(getW(30), getH(300), getW(430), getH(300));               
          g2.setFont(new Font("Arial", Font.PLAIN,12));
        super.paintComponent(g2);
      private int getW(int dx) {
        return (dx * width) / 550;
      private int getH(int dy) {
        return (dy * height) / 400;
      public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if(command.equals("Bar TrendReport")){
          button.setText("Pie Chart");
          pieChart=false;
          try {
            int temp =0;
            java.text.DecimalFormat df = new java.text.DecimalFormat("#0.#");
            for (int j=0; j<4; j++){
              //flote[j] = Float.parseFloat(Text[j].getText());//XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
              temp += (int)((flote[j]) +0.5);
            for (int k=0; k<4; k++){
              bar[k] = (int)(((flote[k]/temp) * 360)+0.5);
              //barLabels[k] = labeltxt[k].getText();XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
              flote[k] = (flote[k]/temp) *100;
              percent[k] = ": "+df.format(flote[k])+"%";
          catch(Exception message){
            title = "Oops! Complete all fields, enter numbers only";
        if(command.equals("Pie Chart")){
          button.setText("Bar TrendReport");
          pieChart=true;
        repaint();
    }

  • Mortgage Program in GUI format

    I am having trouble with writing a mortgage program. The program should allow the users to choose the format inwhich they input their mortgage information. It is to then display his mortgage payment, monthly interest, and balance over the duration of the loan. I thought I had everything right, after serveral error corrections, I get the below listed errors. I understand what they are saying is wrong with the program, but I lack the ability ot decipher how to fix it. Any informaton would be greatly appreciated.
    errors:
    H:\My Documents\Java Training\ShellyJava\Chapter.10\week4.java:333: illegal start of expression
    private static void createAndShowGUI() {
    ^
    H:\My Documents\Java Training\ShellyJava\Chapter.10\week4.java:388: ';' expected
    ^
    2 errors
    Code;
    import java.util.Set;
    import java.util.HashSet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeEvent;
    import java.text.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import java.awt.Container;
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Graphics.*;
    import java.lang.Math.*;
    import java.util.*;
    import java.text.NumberFormat;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class week4 extends JPanel {
    //Defines Labels
    private JLabel Amount_Label;
    private JLabel Rate_Label;
    private JLabel Term_Label;
    private JLabel Payments_Label;
    //Defines Strings for Labels
    private static String Amount_String = "Loan Amount: ";
    private static String Rate_String = "Percentage Rate: ";
    private static String Term_String = "Term (In Years): ";
    private static String Payments_String = "Monthly Payment: ";
    //Defines Text Fields
    private JTextField Amount_Field;
    private JTextField Rate_Field;
    private JTextField Term_Field;
    private JTextField Payments_Field;
    //Defines number Formats
    private NumberFormat Loan_Format;
    private NumberFormat Rate_Format;
    private DecimalFormat Term_Format;
    private DecimalFormat Payments_Format;
    private Verifier verifier = new Verifier();
    //Defines Buttons
    private JButton MortgageCalc = new JButton("Calculate");
         private JButton Clear = new JButton("Clear");
         private JButton Exit = new JButton("Good-bye");
         //Defines Combo Boxes
         private JComboBox Rate_Box;
         private JComboBox Term_Box;
    public week4() {
    super(new BorderLayout());
    setUpFormats();
    //Creates the labels.
    Amount_Label = new JLabel(Amount_String);
    Rate_Label = new JLabel(Rate_String);
    Term_Label = new JLabel(Term_String);
    Payments_Label = new JLabel(Payments_String);
    //Creates the text fields
    Amount_Field = new JTextField(Loan_Format.format(0), 12);
    Amount_Field.setInputVerifier(verifier);
    Rate_Field = new JTextField(Rate_Format.format(0), 12);
    Rate_Field.setInputVerifier(verifier);
    Term_Field = new JTextField(Term_Format.format(0), 12);
    Term_Field.setInputVerifier(verifier);
    Payments_Field = new JTextField(Payments_Format.format(0), 12);
    Payments_Field.setInputVerifier(verifier);
    Payments_Field.setEditable(false);
    //Creates Buttons
    MortgageCalc = new JButton("Calculate");
    Clear = new JButton("Clear");
    Exit = new JButton("Exit");
    //Creates the Combo Boxes
    Rate_Box = new JComboBox ();
         Rate_Box.addItem("5.35%");
         Rate_Box.addItem("5.50%");
         Rate_Box.addItem("5.75%");
         Rate_Box.addItem("Select One");
         add(Rate_Box);
    Term_Box = new JComboBox ();
         Term_box.addItem("7 years");
         Term_box.addItem("15 years");
         Term_box.addItem("30 years");
         Term_box.addItem("Select One");
         add(Term_Box);
    //Defines Listner
    Amount_Field.addActionListener(verifier);
    Rate_Field.addActionListener(verifier);
    Term_Field.addActionListener(verifier);
    Rate_Box.addActionListener(verifier);
    Term_box.addActionListener(verifier);
    MortgageCalc.addActionListener(verifier);
    Clear.addActionListner(verifier);
    Exit.addActionListener(verifier);
    //Sets Labels
    Amount_Label.setLabelFor(Amount_Field);
    Rate_Label.setLabelFor(Rate_Box);
    Term_Label.setLabelFor(Term_Box);
    Payments_Label.setLabelFor(Payments_Field);
    //Layout setup
    JPanel labelPane = new JPanel(new GridLayout(0,1));
    labelPane.add(Amount_Label);
    labelPane.add(Rate_Label);
    labelPane.add(Term_Label);
    labelPane.add(Payments_Label);
    JPanel fieldPane = new JPanel(new GridLayout(0,1));
    fieldPane.add(Amount_Field);
    fieldPane.add(Rate_Box);
    fieldPane.add(Term_Box);
    fieldPane.add(Payments_Field);
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
    buttonPane.add(MortgageCalc);
    buttonPane.add(Clear);
         buttonPane.add(Exit);
    setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
    add(labelPane, BorderLayout.CENTER);
    add(fieldPane, BorderLayout.LINE_END);
    add(buttonPane, BorderLayout.SOUTH);
    class Verifier extends InputVerifier
    implements ActionListener {
    double MIN_AMOUNT = 100;
    double MAX_AMOUNT = 9999999;
    double MIN_RATE = 0.0;
    int MIN_PERIOD = 1;
    int MAX_PERIOD = 30;
    public boolean shouldYieldFocus(JComponent input) {
    boolean inputOK = verify(input);
    updatePayment();
    if (inputOK) {
    return true;
    } else {
    Toolkit.getDefaultToolkit().beep();
    return false;
    protected void updatePayment() {
    double amount = 0;
    double rate = 0.0;
    int termPeriods = 0;
    double payment = 0.0;
    //Parse numbers
    try {
    amount = Loan_Format.parse(Amount_Field.getText()).
    doubleValue();
    } catch (ParseException pe) {}
    try {
    rate = Rate_Format.parse(Rate_Field.getText()).
    doubleValue();
    } catch (ParseException pe) {}
    try {
    termPeriods = Term_Format.parse(Term_Field.getText()).
    intValue();
    } catch (ParseException pe) {}
    //Calculate
    payment = computePayment(amount, rate, termPeriods);
    Payments_Field.setText(Payments_Format.format(payment));
    public boolean verify(JComponent input) {
    return checkField(input, false);
    protected boolean checkField(JComponent input, boolean changeIt) {
    if (input == Amount_Field) {
    return checkAmount_Field(changeIt);
    } else if (input == Rate_Field) {
    return checkRate_Field(changeIt);
    } else if (input == Term_Field) {
    return checkTerm_Field(changeIt);
    } else {
    return true;
    protected boolean checkAmount_Field(boolean change) {
    boolean wasValid = true;
    double amount = 0;
    try {
    amount = Loan_Format.parse(Amount_Field.getText()).
    doubleValue();
    } catch (ParseException pe) {
    wasValid = false;
    if ((amount < MIN_AMOUNT) || (amount > MAX_AMOUNT)) {
    wasValid = false;
    if (change) {
    if (amount < MIN_AMOUNT) {
    amount = MIN_AMOUNT;
    } else {
    amount = MAX_AMOUNT;
    if (change) {
    Amount_Field.setText(Loan_Format.format(amount));
    Amount_Field.selectAll();
    return wasValid;
    protected boolean checkRate_Field(boolean change) {
    boolean wasValid = true;
    double rate = 0;
    try {
    rate = Rate_Format.parse(Rate_Field.getText()).
    doubleValue();
    } catch (ParseException pe) {
    wasValid = false;
    if (rate < MIN_RATE) {
    wasValid = false;
    if (change) {
    rate = MIN_RATE;
    if (change) {
    Rate_Field.setText(Rate_Format.format(rate));
    Rate_Field.selectAll();
    return wasValid;
    protected boolean checkTerm_Field(boolean change) {
    boolean wasValid = true;
    int termPeriods = 0;
    try {
    termPeriods = Term_Format.parse(Term_Field.getText()).
    intValue();
    } catch (ParseException pe) {
    wasValid = false;
    if ((termPeriods < MIN_PERIOD) || (termPeriods > MAX_PERIOD)) {
    wasValid = false;
    if (change) {
    if (termPeriods < MIN_PERIOD) {
    termPeriods = MIN_PERIOD;
    } else {
    termPeriods = MAX_PERIOD;
    if (change) {
    Term_Field.setText(Term_Format.format(termPeriods));
    Term_Field.selectAll();
    return wasValid;
    public void actionPerformed(ActionEvent e) {
    JTextField source = (JTextField)e.getSource();
    shouldYieldFocus(source);
    source.selectAll();
    private static void createAndShowGUI() {
         JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("Week 4 Assignment - Bonnita Ludwig");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JComponent newContentPane = new week4();
    newContentPane.setOpaque(true);
    frame.setContentPane(newContentPane);
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
    double computePayment(double loanAmt, double rate, int termPeriods) {
    double I, partial1, denominator, answer;
    termPeriods *= 12;
    if (rate > 0.01) {
    I = rate / 100.0 / 12.0;
    partial1 = Math.pow((1 + I), (0.0 - termPeriods));
    denominator = (1 - partial1) / I;
    } else {
    denominator = termPeriods;
    answer = (-1 * loanAmt) / denominator;
    return answer;
    private void setUpFormats() {
    Loan_Format = (NumberFormat)NumberFormat.getNumberInstance();
    Rate_Format = NumberFormat.getNumberInstance();
    Rate_Format.setMinimumFractionDigits(3);
    Term_Format = (DecimalFormat)NumberFormat.getNumberInstance();
    Term_Format.setParseIntegerOnly(true);
    Payments_Format = (DecimalFormat)NumberFormat.getNumberInstance();
    Payments_Format.setMaximumFractionDigits(2);
    Payments_Format.setNegativePrefix("(");
    Payments_Format.setNegativeSuffix(")");
    /* References:
    *http://java.sun.com/docs/books/tutorial/uiswing/misc/example-1dot4/index.html#InputVerificationDemo
    *http://java.sun.com/docs/books/tutorial/uiswing/components/combobox.html
    */

    Thanks for the direction, but I am still getting this error:
    week4.java:377: illegal start of expression
    public actionPerformed(ActionEvent e)
    ^
    1 error
    I see that I have to work on my ability to decipher code. I am very new Java and really appreciate your assistance. I have included my code after making the several changes.
    Code:
    import java.util.Set;
    import java.util.HashSet;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.beans.PropertyChangeListener;
    import java.beans.PropertyChangeEvent;
    import java.text.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JFrame;
    import javax.swing.JButton;
    import javax.swing.JLabel;
    import java.awt.Container;
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Graphics.*;
    import java.lang.Math.*;
    import java.util.*;
    import java.text.NumberFormat;
    import java.io.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class week4 extends JPanel
    //Defines Labels
    private JLabel Amount_Label;
    private JLabel Rate_Label;
    private JLabel Term_Label;
    private JLabel Payments_Label;
    //Defines Strings for Labels
    private static String Amount_String = "Loan Amount: ";
    private static String Rate_String = "Percentage Rate: ";
    private static String Term_String = "Term (In Years): ";
    private static String Payments_String = "Monthly Payment: ";
    //Defines Text Fields
    private JTextField Amount_Field;
    private JTextField Rate_Field;
    private JTextField Term_Field;
    private JTextField Payments_Field;
    //Defines number Formats
    private NumberFormat Loan_Format;
    private NumberFormat Rate_Format;
    private DecimalFormat Term_Format;
    private DecimalFormat Payments_Format;
    private Verifier verifier = new Verifier();
    //Defines Buttons
    private JButton MortgageCalc = new JButton("Calculate");
         private JButton Clear = new JButton("Clear");
         private JButton Exit = new JButton("Good-bye");
         //Defines Combo Boxes
         private JComboBox Rate_Box;
         private JComboBox Term_Box;
    public week4()
    super(new BorderLayout());
    setUpFormats();
    //Creates the labels.
    Amount_Label = new JLabel(Amount_String);
    Rate_Label = new JLabel(Rate_String);
    Term_Label = new JLabel(Term_String);
    Payments_Label = new JLabel(Payments_String);
    //Creates the text fields
    Amount_Field = new JTextField(Loan_Format.format(0), 12);
    Amount_Field.setInputVerifier(verifier);
    Rate_Field = new JTextField(Rate_Format.format(0), 12);
    Rate_Field.setInputVerifier(verifier);
    Term_Field = new JTextField(Term_Format.format(0), 12);
    Term_Field.setInputVerifier(verifier);
    Payments_Field = new JTextField(Payments_Format.format(0), 12);
    Payments_Field.setInputVerifier(verifier);
    Payments_Field.setEditable(false);
    //Creates Buttons
    MortgageCalc = new JButton("Calculate");
    Clear = new JButton("Clear");
    Exit = new JButton("Exit");
    //Creates the Combo Boxes
    Rate_Box = new JComboBox ();
         Rate_Box.addItem("5.35%");
         Rate_Box.addItem("5.50%");
         Rate_Box.addItem("5.75%");
         Rate_Box.addItem("Select One");
         add(Rate_Box);
    Term_Box = new JComboBox ();
         Term_box.addItem("7 years");
         Term_box.addItem("15 years");
         Term_box.addItem("30 years");
         Term_box.addItem("Select One");
         add(Term_Box);
    //Defines Listner
    Amount_Field.addActionListener(verifier);
    Rate_Field.addActionListener(verifier);
    Term_Field.addActionListener(verifier);
    Rate_Box.addActionListener(verifier);
    Term_box.addActionListener(verifier);
    MortgageCalc.addActionListener(verifier);
    Clear.addActionListner(verifier);
    Exit.addActionListener(verifier);
    //Sets Labels
    Amount_Label.setLabelFor(Amount_Field);
    Rate_Label.setLabelFor(Rate_Box);
    Term_Label.setLabelFor(Term_Box);
    Payments_Label.setLabelFor(Payments_Field);
    //Layout setup
    JPanel labelPane = new JPanel(new GridLayout(0,1));
    labelPane.add(Amount_Label);
    labelPane.add(Rate_Label);
    labelPane.add(Term_Label);
    labelPane.add(Payments_Label);
    JPanel fieldPane = new JPanel(new GridLayout(0,1));
    fieldPane.add(Amount_Field);
    fieldPane.add(Rate_Box);
    fieldPane.add(Term_Box);
    fieldPane.add(Payments_Field);
    JPanel buttonPane = new JPanel();
    buttonPane.setLayout(new FlowLayout(FlowLayout.CENTER));
    buttonPane.add(MortgageCalc);
    buttonPane.add(Clear);
         buttonPane.add(Exit);
    setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
    add(labelPane, BorderLayout.CENTER);
    add(fieldPane, BorderLayout.LINE_END);
    add(buttonPane, BorderLayout.SOUTH);
         class Verifier extends InputVerifier implements ActionListener
         double MIN_AMOUNT = 100;
         double MAX_AMOUNT = 9999999;
         double MIN_RATE = 0.0;
         int MIN_PERIOD = 1;
         int MAX_PERIOD = 30;
              public boolean shouldYieldFocus(JComponent input)
         boolean inputOK = verify(input);
         updatePayment();
         if (inputOK)
         return true;
         else
         Toolkit.getDefaultToolkit().beep();
         return false;
         protected void updatePayment()
         double amount = 0;
         double rate = 0.0;
         int termPeriods = 0;
         double payment = 0.0;
         //Parse numbers
         try
         amount = Loan_Format.parse(Amount_Field.getText()).
    doubleValue();
         catch (ParseException pe)
         try
    rate = Rate_Format.parse(Rate_Field.getText()).
    doubleValue();
         catch (ParseException pe)
         try
    termPeriods = Term_Format.parse(Term_Field.getText()).
    intValue();
         catch (ParseException pe)
         //Calculate
         payment = computePayment(amount, rate, termPeriods);
         Payments_Field.setText(Payments_Format.format(payment));
    public boolean verify(JComponent input)
    return checkField(input, false);
    protected boolean checkField(JComponent input, boolean changeIt)
    if (input == Amount_Field)
    return checkAmount_Field(changeIt);
    else if (input == Rate_Field)
    return checkRate_Field(changeIt);
    else if (input == Term_Field)
    return checkTerm_Field(changeIt);
    else
    return true;
    protected boolean checkAmount_Field(boolean change)
    boolean wasValid = true;
    double amount = 0;
    try
    amount = Loan_Format.parse(Amount_Field.getText()).
    doubleValue();
    catch (ParseException pe)
    wasValid = false;
    if ((amount < MIN_AMOUNT) || (amount > MAX_AMOUNT))
    wasValid = false;
    if (change)
    if (amount < MIN_AMOUNT)
    amount = MIN_AMOUNT;
    else
    amount = MAX_AMOUNT;
    if (change)
    Amount_Field.setText(Loan_Format.format(amount));
    Amount_Field.selectAll();
    return wasValid;
    protected boolean checkRate_Field(boolean change)
    boolean wasValid = true;
    double rate = 0;
    try
    rate = Rate_Format.parse(Rate_Field.getText()).
    doubleValue();
    catch (ParseException pe)
    wasValid = false;
    if (rate < MIN_RATE)
    wasValid = false;
    if (change)
    rate = MIN_RATE;
    if (change)
    Rate_Field.setText(Rate_Format.format(rate));
    Rate_Field.selectAll();
    return wasValid;
    protected boolean checkTerm_Field(boolean change)
    boolean wasValid = true;
    int termPeriods = 0;
    try
    termPeriods = Term_Format.parse(Term_Field.getText()).
    intValue();
    catch (ParseException pe)
    wasValid = false;
    if ((termPeriods < MIN_PERIOD) || (termPeriods > MAX_PERIOD))
    wasValid = false;
    if (change)
    if (termPeriods < MIN_PERIOD)
    termPeriods = MIN_PERIOD;
    else
    termPeriods = MAX_PERIOD;
    if (change)
    Term_Field.setText(Term_Format.format(termPeriods));
    Term_Field.selectAll();
    return wasValid;
    public actionPerformed(ActionEvent e)
    JTextField source = (JTextField)e.getSource();
    shouldYieldFocus(source);
    source.selectAll();
         public createAndShowGUI()
              JFrame.setDefaultLookAndFeelDecorated(true);
         JFrame frame = new JFrame("Week 4 Assignment - Bonnita Ludwig");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         JComponent newContentPane = new week4();
         newContentPane.setOpaque(true);
         frame.setContentPane(newContentPane);
         frame.pack();
         frame.setVisible(true);
         public static void main(String[] args)
         javax.swing.SwingUtilities.invokeLater(new Runnable()
         public void run()
         createAndShowGUI();
         double computePayment(double loanAmt, double rate, int termPeriods)
         double I, partial1, denominator, answer;
         termPeriods *= 12;
         if (rate > 0.01)
         I = rate / 100.0 / 12.0;
         partial1 = Math.pow((1 + I), (0.0 - termPeriods));
         denominator = (1 - partial1) / I;
         else
         denominator = termPeriods;
         answer = (-1 * loanAmt) / denominator;
              return answer;
         private void setUpFormats()
         Loan_Format = (NumberFormat)NumberFormat.getNumberInstance();
         Rate_Format = NumberFormat.getNumberInstance();
         Rate_Format.setMinimumFractionDigits(3);
         Term_Format = (DecimalFormat)NumberFormat.getNumberInstance();
         Term_Format.setParseIntegerOnly(true);
         Payments_Format = (DecimalFormat)NumberFormat.getNumberInstance();
         Payments_Format.setMaximumFractionDigits(2);
         Payments_Format.setNegativePrefix("(");
         Payments_Format.setNegativeSuffix(")");
    }

  • ScrollBars not showing up for the JPanel [urgent]

    Hi,
    I have a frame in which i have two nested split panes i.e one horizontal splitpane and in that i am having one more split pane on the right side and a JTree on the left side.In the second split pane (which is a vertical split) ,as a top component , i am setting a JScrollPane in which i am trying to display a JPanel which is having a lot of swing components in it.I want to see the scroll bars for this panel so that i can see all the components.Do i have to implement Scrollable interface for this panel to scroll in the ScrollPane.I don't know how to implement Scrollable interface.Can some body help me in resolving this?This is some what urgent.Any help will be highly appreciated.
    Thanks in advance.
    Ashok

    Thank you all for your replies.I added the scroll bar policy.The scroll bars are showing up but the components inside the Panel are not moving.I want the components to move when i am scrolling.Here is my code.In the code SeriesDescPanel, SeriesDescMapPanel are sub classes of JPanel.I am using null layout to add the components to these panels.
    public class MainWindow extends JFrame implements TreeExpansionListener
    public MainWindow()
    throws RemoteException
    // This code is automatically generated by Visual Cafe when you add
              // components to the visual environment. It instantiates and initializes
              // the components. To modify the code, only use code syntax that matches
              // what Visual Cafe can generate, or Visual Cafe may be unable to back
              // parse your Java file into its visual environment.
              //{{INIT_CONTROLS
              setJMenuBar(menuBar);
              setTitle("Series Maintenance");
              getContentPane().setLayout(new BorderLayout(0,0));
              setSize(667,478);
              setVisible(false);
              JSplitPane1.setDividerSize(1);
              JSplitPane1.setOneTouchExpandable(true);
              getContentPane().add(BorderLayout.CENTER, JSplitPane1);
              seriesMenu.setText("Series");
              seriesMenu.setActionCommand("Series");
              menuBar.add(seriesMenu);
              newSeriesGroupMenuItem.setText("New Series Group");
              newSeriesGroupMenuItem.setActionCommand("New Series Group");
              seriesMenu.add(newSeriesGroupMenuItem);
              newSeriesMenuItem.setText("New Series");
              newSeriesMenuItem.setActionCommand("New Series");
              seriesMenu.add(newSeriesMenuItem);
              seriesMenu.add(JSeparator1);
              serachMenuItem.setText("Search");
              serachMenuItem.setActionCommand("Search");
              seriesMenu.add(serachMenuItem);
              seriesMenu.add(JSeparator2);
              saveMenuItem.setText("Save");
              saveMenuItem.setActionCommand("Save");
              seriesMenu.add(saveMenuItem);
              seriesMenu.add(JSeparator3);
              exitMenuItem.setText("Exit");
              exitMenuItem.setActionCommand("Exit");
              seriesMenu.add(exitMenuItem);
              adminMenu.setText("Administration");
              adminMenu.setActionCommand("Administration");
              menuBar.add(adminMenu);
              bulkLoadMenuItem.setText("Bulk Load");
              bulkLoadMenuItem.setActionCommand("Bulk Load");
              adminMenu.add(bulkLoadMenuItem);
              drsMenuItem.setText("DRS override");
              drsMenuItem.setActionCommand("DRS override");
              adminMenu.add(drsMenuItem);
              helpMenu.setText("Help");
              helpMenu.setActionCommand("Help");
              menuBar.add(helpMenu);
              tutorialMenuItem.setText("Tutorial");
              tutorialMenuItem.setActionCommand("Tutorial");
              helpMenu.add(tutorialMenuItem);
              bulkLoadFormatMenuItem.setText("Bulk Load Format");
              bulkLoadFormatMenuItem.setActionCommand("Bulk Load Format");
              helpMenu.add(bulkLoadFormatMenuItem);
              aboutMenuItem.setText("About");
              aboutMenuItem.setActionCommand("About");
              helpMenu.add(aboutMenuItem);
    JSplitPane2 = new javax.swing.JSplitPane();
    upperPanel = new SeriesDescPanel();
    JScrollPane2 = new javax.swing.JScrollPane(upperPanel,
    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
    ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    JScrollPane3 = new javax.swing.JScrollPane();
    JSplitPane2.setOrientation(0);
    JSplitPane2.setDividerSize(1);
    JSplitPane2.setOneTouchExpandable(true);
    JSplitPane1.setRightComponent(JSplitPane2);
    JSplitPane1.setLeftComponent(viewPane);
    viewPane.add(alphabeticPane);
    viewPane.add(searchDataPane);
    viewPane.setTitleAt(0,"All");
              viewPane.setTitleAt(1,"search");
    //JScrollPane1.setMinimumSize(new Dimension(126, 478));
    JSplitPane2.setTopComponent(JScrollPane2);
    //JScrollPane2.setMinimumSize(new Dimension(426, 409));
    JSplitPane2.setBottomComponent(JScrollPane3);
    lowerPanel = new SeriesDescMapPanel();
    seriesTreeModel = new SeriesTreeModel(SeriesMaintenanceUI.getSeriesGroupInfo());
    tickersTree.setModel(seriesTreeModel);
    alphabeticPane.getViewport().setView(tickersTree);
    //JScrollPane2.getViewport().setView(upperPanel);
    //JScrollPane2.setViewportView(upperPanel);
    //upperPanel.scrollRectToVisible(new Rectangle(upperPanel.getWidth(),
    //upperPanel.getHeight(),1,1));
    JScrollPane3.getViewport().setView(lowerPanel);
    //JSplitPane2.setPreferredSize(new Dimension(426,200));
    SeriesDescPanel upperPanel;
    SeriesDescMapPanel lowerPanel;
    SeriesTreeModel seriesTreeModel;
    SeriesTreeModel searchTreeModel;
    javax.swing.JSplitPane JSplitPane2;
    javax.swing.JScrollPane JScrollPane2;
    javax.swing.JScrollPane JScrollPane3;
    javax.swing.JTree tickersTree = new javax.swing.JTree();
    javax.swing.JTree searchTree = new javax.swing.JTree();
    javax.swing.JScrollPane alphabeticPane = new javax.swing.JScrollPane();
    javax.swing.JTabbedPane viewPane = new JTabbedPane(SwingConstants.BOTTOM);
    javax.swing.JScrollPane searchDataPane = new javax.swing.JScrollPane();
    //{{DECLARE_CONTROLS
         javax.swing.JSplitPane JSplitPane1 = new javax.swing.JSplitPane();
         javax.swing.JMenuBar menuBar = new javax.swing.JMenuBar();
         javax.swing.JMenu seriesMenu = new javax.swing.JMenu();
         javax.swing.JMenuItem newSeriesGroupMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem newSeriesMenuItem = new javax.swing.JMenuItem();
         javax.swing.JSeparator JSeparator1 = new javax.swing.JSeparator();
         javax.swing.JMenuItem serachMenuItem = new javax.swing.JMenuItem();
         javax.swing.JSeparator JSeparator2 = new javax.swing.JSeparator();
         javax.swing.JMenuItem saveMenuItem = new javax.swing.JMenuItem();
         javax.swing.JSeparator JSeparator3 = new javax.swing.JSeparator();
         javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenu adminMenu = new javax.swing.JMenu();
         javax.swing.JMenuItem bulkLoadMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem drsMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenu helpMenu = new javax.swing.JMenu();
         javax.swing.JMenuItem tutorialMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem bulkLoadFormatMenuItem = new javax.swing.JMenuItem();
         javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
    Pl. help me in resolving this.
    Ashok

  • Is it possible to print a JPanel from the application?

    Hello,
    Just a quick question: Is it possible to print a JPanel from your application? I have plotted a graph and I would like user to be able to print this with a click of a button (or similar)
    Thanks very much for your help, its appreciated as always.
    Harold Clements

    It is absolutely possible
    Check out my StandardPrint class. Basically all you need to do is
    (this is pseudocode. I don't remember the exact names of methods for all this stuff. Look it up if there's a problem)
    PrinterJob pd = PrinterJob.createNewJob();
    StandardPrint sp = new StandardPrint(yourComponent);
    pd.setPageable(sp);
    //if you want this
    //pd.pageDialog();
    pd.doPrint();You are welcome to have use and modify this class but please don't change the package or take credit for it as your own code.
    StandardPrint.java
    ===============
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
         boolean mScale = false;
         boolean mMaintainRatio = true;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
         public boolean isPrintScaled () {
              return mScale;
         public void setPrintScaled(boolean b) {
              mScale = b;
         public boolean getMaintainsAspect() {
              return mMaintainRatio;
         public void setMaintainsAspect(boolean b) {
              mMaintainRatio = b;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
            int width = im.getWidth(null);
            int height = im.getHeight(null);
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            double hratio = height / pf.getHeight();
            double wratio = width / pf.getWidth();
            //g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            Graphics2D g = (Graphics2D) gr;
              g.drawRect(0, 0, (int)format.getWidth(), (int)format.getHeight());
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
              if (!isPrintScaled()) {
                 int horizontal = getNumHorizontalPages();
                 int vertical = getNumVerticalPages();
                 int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
                 int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                 g.translate(-horizontalOffset, -verticalOffset);
                 if (sp != null) {
                     sp.printerPaint(g);
                 else {
                     c.paint(g);
                 g.translate(horizontal, vertical);
                 g.scale(ratio, ratio);
              else {
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                   double xScale = 1.0;
                   double yScale = 1.0;
                   double wid;
                   double ht;
                   if (sp != null) {
                        wid = sp.getPrintSize().width;
                        ht = sp.getPrintSize().height;
                   else {
                        wid = c.getWidth();
                        ht = c.getHeight();
                   xScale = format.getImageableWidth() / wid;
                   yScale = format.getImageableHeight() / ht;
                   if (getMaintainsAspect()) {
                        xScale = yScale = Math.min(xScale, yScale);
                   g.scale(xScale, yScale);
                   if (sp != null) {
                        sp.printerPaint(g);
                   else {
                        c.paint(g);
                   g.scale(1 / xScale, 1 / yScale);
                   g.scale(ratio, ratio);
             g.translate((int)-format.getImageableX(), (int)-format.getImageableY());     
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
              if (isPrintScaled()) return 1;
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }

Maybe you are looking for

  • IPod stuck in Disk Mode(Restart won't work)

    My iPod is stuck in disk mode, and no matter how many times I restart it, it stays in this. I've tried the 5R's and I've tried restarting it. Is there any other fixes?

  • MMS over WiFi not working after Sense 6 Update

    A week ago Monday, the Sense 6 update hit my phone.  Once loaded, I could no longer send MMS over WiFi, stream Google Play Music over WiFi, access my content on Google Play Books, or back up my pics to Google Cloud over WiFi.  After several days of e

  • Front Row, slideshow & music

    While using Front Row to play a slideshow, the same song always plays. I can't find any way to set the music to the slideshow. Can anyone help on this problem?

  • Index Not Using

    Friends, we are creating an index but its not picking the right one index during sql-execution. Please see my steps: CREATE UNIQUE INDEX RDMBKPIPRDDAT.HLS_NLSSORT_INDEX ON RDMBKPIPRDDAT.HLS_OUT (LOAD_PROC_ID, IMSI, SUBSCRIBER_TYPE, NLSSORT("IMSI",'nl

  • Extension Manager and performance

    from the JDeveloper documentation: Extensions are components that are optionally loaded when JDeveloper is launched. Many of JDeveloper's standard features are installed as extensions. Disabling unneeded components can improve launch time significant