Writing to JPanels

I have a method which writes a button and 4 labels to separate JPanels in an order form format. Whenever I add a component to a panel, I immediately validate that panel. There are 4 basic products presented in this application, and 3 of the 4 display on the order form without problem. The 4th product displays nothing, not even the button. All of the products are sent to the order form using the exact same code.
Logically, one would think that the problem is with the product, not the panels. But the data is passed to the method successfully, it just isn't appearing on the screen.
Thanks in advance!

Please post a Short,Self Contained, Compilable and Executable Example Program.

Similar Messages

  • Sizing a jlist within a jpanel

    Hi,
    I'm writing a jpanel tjhat contains a jlist object at its center. Now, when I place the jpanel within a JFrame the panel grows to eat all the available space (I can see this thanks to the border of the panel), while the JList remains at a very small size regarding the jpanel. I'd like to have the jlist to resize itself to occupy all the
    jpanel size. The following is the code that shows it. Any idea about how to achieve this?
    Thanks,
    Luca
    public class ListPanel extends JPanel{
        protected JList myList;
    public AgletListPanel(){
            super();
            this.setLayout(new FlowLayout(FlowLayout.CENTER));
            this.listModel = new DefaultListModel();
            this.myList = new JList(this.listModel);
            this.myList.setBackground(Color.WHITE);
            this.myist.setForeground(Color.BLUE);
            this.myList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            this.myList.setPreferredSize(getPreferredSize());
            this.add(new JScrollPane(this.myList));
            TitledBorder border = new TitledBorder("List"));
            border.setTitleColor(Color.BLUE);
            border.setTitleJustification(TitledBorder.CENTER);
            this.setBorder(border);
            this.setVisible(true);
        }

    Thanks, using the borderlayout the panel now shows fine to me. However I removed the setPreferredSize line in order not ot have the jlist to use scrollbars even if empty.
    By the way, can you explain why the FlowLayout did not work and the border layout did it?
    Thanks.

  • Out of Memory Error when writing from mySQL to JPanel

    Hi,
    I have a JPanel with BoxLayout to which I am adding JCheckBoxes, which are the result of an Select query to mySQL.
    My select query is giving me 15000 lines of result, in which case my program is screwed up, and I am getting OutofMemory Error.
    Does somebody know how to fix this problem?
    This is my code for the JPanel :
    srchRP = new JPanel();
         BoxLayout bl = new BoxLayout(srchRP, BoxLayout.Y_AXIS);
         srchRP.setLayout(bl);
         srchSP = new JScrollPane(srchRP);
         srchSP.setPreferredSize(new Dimension(300,470));

    If I understand correctly, your JVM simply cannot deal with 15,000 objects (the result set generated by your query). You can either make more memory available to the JVM as described above, or you can consider redesigning your application.
    It seems what you are trying to do is get every record in the database table, and display those records in a JPanel, allowing the end user to select which records he wants to perform an action on (such as delete).
    Instead of using a "select * from table" query, you could do a "select id, title from table" type of query, in which case, your data object will be a lot smaller and still give the user enough information to decide whether to delete the record or not.
    Alternatively, you could write a utility program to get the information you need from a text file generated as a result of a database dump and load that information upon startup, i.e., cache the master list of records.
    But, it seems to me, if I were your customer, I would not want to scroll through a list of 15,000 entries and deciding which ones I wanted to check off. If you figure out an easier way to manage 15,000+ records, such as allowing the user to narrow down his criteria, then you go a long way towards optimizing your code to reduce memory requirements.

  • Writing jpg from jpanel

    Hi.
    I want to write a jpg-file showing the contents of a JPanel. Is there any way to do this?
    Greetings,
    Feanor's Curse

    Im using your method to save a JPG image from a JPanel too
    It isn't working for me.
    I am running a command line version of my program, but still need to save the JPanel.
    I am just getting a blank image saved.
    Obviously, I think, the problem is that it never gets inserted into a Frame (as I don't have one!) so is never visible. The 'paint(Graphics g)' is obviously too clever and not drawing it, when not in view?

  • How to make a JPanel transparent? Not able to do it with setOpaque(false)

    Hi all,
    I am writing a code to play a video and then draw some lines on the video. For that first I am playing the video on a visual component and I am trying to overlap a JPanel for drawing the lines. I am able to overlap the JPanel but I am not able to make it transparent. So I am able to draw lines but not able to see the video. So, I want to make the JPanel transparent so that I can see the video also... I am posting my code below
    import javax.media.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.*;
    import java.lang.Math;
    import javax.media.control.FramePositioningControl;
    import javax.media.protocol.*;
    import javax.swing.*;
    class MPEGPlayer2 extends JFrame implements ActionListener,ControllerListener,ItemListener
         Player player;
         Component vc, cc;
         boolean first = true, loop = false;
         String currentDirectory;
         int mediatime;
         BufferedWriter out;
         FileWriter fos;
         String filename = "";
         Object waitSync = new Object();
         boolean stateTransitionOK = true;
         JButton bn = new JButton("DrawLine");
         MPEGPlayer2 (String title)
              super (title);
              addWindowListener(new WindowAdapter ()
                   public void windowClosing (WindowEvent e)
                            dispose ();
                            public void windowClosed (WindowEvent e)
                         if (player != null)
                         player.close ();
                         System.exit (0);
              Menu m = new Menu ("File");
              MenuItem mi = new MenuItem ("Open...");
              mi.addActionListener (this);
              m.add (mi);
              m.addSeparator ();
              CheckboxMenuItem cbmi = new CheckboxMenuItem ("Loop", false);
              cbmi.addItemListener (this);
              m.add (cbmi);
              m.addSeparator ();
              mi = new MenuItem ("Exit");
              mi.addActionListener (this);
              m.add (mi);
              MenuBar mb = new MenuBar ();
              mb.add (m);
              setMenuBar (mb);
              setSize (500, 500);
              setVisible (true);
         public void actionPerformed (ActionEvent ae)
                        FileDialog fd = new FileDialog (this, "Open File",FileDialog.LOAD);
                        fd.setDirectory (currentDirectory);
                        fd.show ();
                        if (fd.getFile () == null)
                        return;
                        currentDirectory = fd.getDirectory ();
                        try
                             player = Manager.createPlayer (new MediaLocator("file:" +fd.getDirectory () +fd.getFile ()));
                             filename = fd.getFile();
                        catch (Exception exe)
                             System.out.println(exe);
                        if (player == null)
                             System.out.println ("Trouble creating a player.");
                             return;
                        setTitle (fd.getFile ());
                        player.addControllerListener (this);
                        player.prefetch ();
         }// end of action performed
         public void controllerUpdate (ControllerEvent e)
              if (e instanceof EndOfMediaEvent)
                   if (loop)
                        player.setMediaTime (new Time (0));
                        player.start ();
                   return;
              if (e instanceof PrefetchCompleteEvent)
                   player.start ();
                   return;
              if (e instanceof RealizeCompleteEvent)
                   vc = player.getVisualComponent ();
                   if (vc != null)
                        add (vc);
                   cc = player.getControlPanelComponent ();
                   if (cc != null)
                        add (cc, BorderLayout.SOUTH);
                   add(new MyPanel());
                   pack ();
         public void itemStateChanged(ItemEvent ee)
         public static void main (String [] args)
              MPEGPlayer2 mp = new MPEGPlayer2 ("Media Player 2.0");
              System.out.println("111111");
    class MyPanel extends JPanel
         int i=0,j;
         public int xc[]= new int[100];
         public int yc[]= new int[100];
         int a,b,c,d;
         public MyPanel()
              setOpaque(false);
              setBorder(BorderFactory.createLineBorder(Color.black));
              JButton bn = new JButton("DrawLine");
              this.add(bn);
              bn.addActionListener(actionListener);
              setBackground(Color.CYAN);
              addMouseListener(new MouseAdapter()
                             public void mouseClicked(MouseEvent e)
                   saveCoordinates(e.getX(),e.getY());
         ActionListener actionListener = new ActionListener()
              public void actionPerformed(ActionEvent aae)
                        repaint();
         public void saveCoordinates(int x, int y)
                    System.out.println("x-coordinate="+x);
                    System.out.println("y-coordinate="+y);
                    xc=x;
              yc[i]=y;
              System.out.println("i="+i);
              i=i+1;
         public Dimension getPreferredSize()
    return new Dimension(500,500);
         public void paintComponent(Graphics g)
    super.paintComponent(g);
              Graphics2D g2D = (Graphics2D)g;
              //g2D.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0.0f));
              g2D.setColor(Color.GREEN);
              for (j=0;j<i;j=j+2)
                   g2D.drawLine(xc[j],yc[j],xc[j+1],yc[j+1]);

    camickr wrote:
    "How to Use Layered Panes"
    http://java.sun.com/docs/books/tutorial/uiswing/components/layeredpane.html
    Add your video component to one layer and your non-opaque panel to another layer.Did you try that with JMF? It does not work for me. As I said, the movie seems to draw itself always on top!

  • Problem with writing and reading using serialization

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

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

  • Problem with ArrayLists and writing and reading from a .dat file (I think)

    I'm brand new to this forum, but I'm sure hoping someone can help me with a problem I'm having with ArrayLists. This program was originally created with an array of objects that were displayed on a GUI with jtextFields, then cycling thru them via jButtons: First, Next, Previous, Last. Now I need to add the ability to modify, delete and add records. Both iterations of this program needed to write to and read from a .dat file.
    It worked just like it was suppose to when I used just the array, but now I need to use a "dynamic array" that will grow or shrink as needed: i.e. an ArrayList.
    When I aded the ArrayList I had the ArrayList use toArray() to fill my original array so I could continue to use all the methods I'd created for using with my array. Now I'm getting a nullPointerException every time I try to run my program, which means somewhere I'm NOT filling my array ???? But, I'm writing just fine to my .dat file, which is confusing me to no end!
    It's a long program, and I apologize for the length, but here it is. There are also 2 class files, a parent and 1 child below Inventory6. This was written in NetBeans IDE 5.5.1.
    Thank you in advance for any help anyone can give me!
    LabyBC
    package my.Inventory6;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.io.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.text.NumberFormat;
    // Class Inventory6
    public class Inventory6 extends javax.swing.JFrame {
    private static InventoryPlusColor[] inventory;
    private static ArrayList inList;
    // create a tool that insure the specified format for a double number, when displayed
    private DecimalFormat doubleFormat = new DecimalFormat( "0.00" );
    private DecimalFormat singleFormat = new DecimalFormat( "0");
    // the index within the array of products of the current displayed product
    private int currentProductIndex;
    /** Creates new form Inventory6 */
    public Inventory6() {
    initComponents();
    currentProductIndex = 0;
    } // end Inventory6()
    private static InventoryPlusColor[] getInventory() {
    ArrayList<InventoryPlusColor> inList = new ArrayList<InventoryPlusColor>();
    inList.add(new InventoryPlusColor(1, "Couch", 3, 1250.00, "Blue"));
    inList.add(new InventoryPlusColor(2, "Recliner", 10, 525.00, "Green"));
    inList.add(new InventoryPlusColor(3, "Chair", 6, 125.00, "Mahogany"));
    inList.add(new InventoryPlusColor(4, "Pedestal Table", 2, 4598.00, "Oak"));
    inList.add(new InventoryPlusColor(5, "Sleeper Sofa", 4, 850.00, "Yellow"));
    inList.add(new InventoryPlusColor(6, "Rocking Chair", 2, 459.00, "Tweed"));
    inList.add(new InventoryPlusColor(7, "Couch", 4, 990.00, "Red"));
    inList.add(new InventoryPlusColor(8, "Chair", 12, 54.00, "Pine"));
    inList.add(new InventoryPlusColor(9, "Ottoman", 3, 110.00, "Black"));
    inList.add(new InventoryPlusColor(10, "Chest of Drawers", 5, 598.00, "White"));
    for (int j = 0; j < inList.size(); j++)
    System.out.println(inList);
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    return inventory;
    } // end getInventory() method
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    IDNumberLbl = new javax.swing.JLabel();
    IDNumberField = new javax.swing.JTextField();
    prodNameLbl = new javax.swing.JLabel();
    prodNameField = new javax.swing.JTextField();
    colorLbl = new javax.swing.JLabel();
    colorField = new javax.swing.JTextField();
    unitsInStockLbl = new javax.swing.JLabel();
    unitsInStockField = new javax.swing.JTextField();
    unitPriceLbl = new javax.swing.JLabel();
    unitPriceField = new javax.swing.JTextField();
    invenValueLbl = new javax.swing.JLabel();
    invenValueField = new javax.swing.JTextField();
    restockingFeeLbl = new javax.swing.JLabel();
    restockingFeeField = new javax.swing.JTextField();
    jbtFirst = new javax.swing.JButton();
    jbtNext = new javax.swing.JButton();
    jbtPrevious = new javax.swing.JButton();
    jbtLast = new javax.swing.JButton();
    jbtAdd = new javax.swing.JButton();
    jbtDelete = new javax.swing.JButton();
    jbtModify = new javax.swing.JButton();
    jbtSave = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    searchIDNumLbl = new javax.swing.JLabel();
    searchIDNumbField = new javax.swing.JTextField();
    jbtSearch = new javax.swing.JButton();
    searchResults = new javax.swing.JLabel();
    jbtExit = new javax.swing.JButton();
    jbtExitwoSave = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Inventory Program"));
    IDNumberLbl.setText("ID Number");
    IDNumberField.setEditable(false);
    prodNameLbl.setText("Product Name");
    prodNameField.setEditable(false);
    colorLbl.setText("Product Color");
    colorField.setEditable(false);
    colorField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    colorFieldActionPerformed(evt);
    unitsInStockLbl.setText("Units In Stock");
    unitsInStockField.setEditable(false);
    unitPriceLbl.setText("Unit Price $");
    unitPriceField.setEditable(false);
    invenValueLbl.setText("Inventory Value $");
    invenValueField.setEditable(false);
    restockingFeeLbl.setText("5% Restocking Fee $");
    restockingFeeField.setEditable(false);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(unitPriceLbl)
    .addComponent(unitsInStockLbl)
    .addComponent(colorLbl)
    .addComponent(prodNameLbl)
    .addComponent(IDNumberLbl)
    .addComponent(restockingFeeLbl)
    .addComponent(invenValueLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(IDNumberField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(prodNameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(invenValueField, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
    .addContainerGap())
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(IDNumberLbl)
    .addComponent(IDNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(prodNameLbl)
    .addComponent(prodNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(colorLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitsInStockLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitPriceLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(restockingFeeLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(invenValueField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(invenValueLbl))
    .addContainerGap())
    jbtFirst.setText("First");
    jbtFirst.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtFirstActionPerformed(evt);
    jbtNext.setText("Next");
    jbtNext.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtNextActionPerformed(evt);
    jbtPrevious.setText("Previous");
    jbtPrevious.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtPreviousActionPerformed(evt);
    jbtLast.setText("Last");
    jbtLast.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtLastActionPerformed(evt);
    jbtAdd.setText("Add");
    jbtAdd.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtAddActionPerformed(evt);
    jbtDelete.setText("Delete");
    jbtModify.setText("Modify");
    jbtModify.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtModifyActionPerformed(evt);
    jbtSave.setText("Save");
    jbtSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtSaveActionPerformed(evt);
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Search by:"));
    searchIDNumLbl.setText("Item Number:");
    jbtSearch.setText("Search");
    searchResults.setFont(new java.awt.Font("Tahoma", 1, 12));
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(searchIDNumLbl)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(259, 259, 259)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(searchIDNumLbl)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtSearch)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jbtExit.setText("Save and Exit");
    jbtExit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitActionPerformed(evt);
    jbtExitwoSave.setText("Exit");
    jbtExitwoSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitwoSaveActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jbtExitwoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jbtExit)))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtFirst)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtNext)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtPrevious)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtLast))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(12, 12, 12)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtAdd)
    .addComponent(jbtDelete)
    .addComponent(jbtModify)
    .addComponent(jbtSave))))
    .addContainerGap())
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtFirst, jbtLast, jbtNext, jbtPrevious});
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAdd, jbtDelete, jbtModify, jbtSave});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(21, 21, 21)
    .addComponent(jbtAdd)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtDelete)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtModify)
    .addGap(39, 39, 39)
    .addComponent(jbtSave))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jbtFirst)
    .addComponent(jbtNext)
    .addComponent(jbtPrevious)
    .addComponent(jbtLast))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtExit)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtExitwoSave)))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void jbtExitwoSaveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String prodNameMod, colorMod;
    double unitsInStockMod, unitPriceMod;
    int idNumMod;
    idNumMod = Integer.parseInt(IDNumberField.getText());
    prodNameMod = prodNameField.getText();
    unitsInStockMod = Double.parseDouble(unitsInStockField.getText());
    unitPriceMod = Double.parseDouble(unitPriceField.getText());
    colorMod = colorField.getText();
    if(currentProductIndex == inventory.length) {
    inList.add(new InventoryPlusColor(idNumMod, prodNameMod,
    unitsInStockMod, unitPriceMod, colorMod));
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    } else {
    inventory[currentProductIndex].setIDNumber(idNumMod);
    inventory[currentProductIndex].setProdName(prodNameMod);
    inventory[currentProductIndex].setUnitsInStock(unitsInStockMod);
    inventory[currentProductIndex].setUnitPrice(unitPriceMod);
    inventory[currentProductIndex].setColor(colorMod);
    displayProduct(inventory[currentProductIndex]);
    private static void writeInventory(InventoryPlusColor i,
    DataOutputStream out) {
    try {
    out.writeInt(i.getIDNumber());
    out.writeUTF(i.getProdName());
    out.writeDouble(i.getUnitsInStock());
    out.writeDouble(i.getUnitPrice());
    out.writeUTF(i.getColor());
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception writing data",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } //end writeInventory()
    private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
    File file = new File(name);
    out =
    new DataOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(file)));
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error", "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return out;
    } // end openOutputStream()
    private static void closeFile(DataOutputStream out) {
    try {
    out.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeFile()
    private static DataInputStream getStream(String name) {
    DataInputStream in = null;
    try {
    File file = new File(name);
    in = new DataInputStream(
    new BufferedInputStream(
    new FileInputStream(file)));
    } catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "The file doesn't exist",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error creating file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return in;
    private static void closeInputFile(DataInputStream in) {
    try {
    in.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeInputFile()
    private double entireInventory() {
    // a temporary double variable that the method will return ...
    // after each product's inventory is added to it
    double entireInventory = 0;
    // loop to control number of products
    for (int index = 0; index < inventory.length; index++) {
    // add each inventory to the entire inventory
    entireInventory += inventory[index].setInventoryValue();
    } // end loop to control number of products
    return entireInventory;
    } // end method entireInventory
    private void jbtLastActionPerformed(java.awt.event.ActionEvent evt) {                                       
    currentProductIndex = inventory.length-1; // move to the last product
    // display the information for the last product
    displayProduct(inventory[currentProductIndex]);
    private void jbtPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (currentProductIndex != 0) // it's not the first product displayed
    currentProductIndex -- ; // move to the previous product (decrement the current index)
    } else // the first product is displayed
    currentProductIndex = inventory.length-1; // move to the last product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (currentProductIndex != inventory.length-1) // it's not the last product displayed
    currentProductIndex ++ ; // move to the next product (increment the current index)
    } else // the last product is displayed
    currentProductIndex = 0; // move to the first product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtFirstActionPerformed(java.awt.event.ActionEvent evt) {                                        
    currentProductIndex = 0;
    // display the information for the first product
    displayProduct(inventory[currentProductIndex]);
    private void colorFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    private void jbtModifyActionPerformed(java.awt.event.ActionEvent evt) {                                         
    prodNameField.setEditable(true);
    prodNameField.setFocusable(true);
    unitsInStockField.setEditable(true);
    unitPriceField.setEditable(true);
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    IDNumberField.setText("");
    IDNumberField.setEditable(true);
    prodNameField.setText("");
    prodNameField.setEditable(true);
    colorField.setText("");
    colorField.setEditable(true);
    unitsInStockField.setText("");
    unitsInStockField.setEditable(true);
    unitPriceField.setText("");
    unitPriceField.setEditable(true);
    restockingFeeField.setText("");
    invenValueField.setText("");
    currentProductIndex = inventory.length;
    private void jbtExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
    DataOutputStream out = openOutputStream("inventory.dat");
    for (InventoryPlusColor i : inventory)
    writeInventory(i, out);
    closeFile(out);
    System.exit(0);
    private static InventoryPlusColor readProduct(DataInputStream in) {
    int idNum = 0;
    String prodName = "";
    double inStock = 0.0;
    double pric

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • How can i  add more than 500 jPanels in a jScrollPane

    Hello to all ,
    I am facing a problem related to adding jPanels in jScrollPane. My application needs more than 500 jpanels in the jscrollpane.where in each jPanel 4 jtextboxes, 1 comboboxes, 1 check box is there.when the check box will be clicked then the total row( ie row means the panel containing the 4 jtextboxes, 1 comboboxes, 1 check box ).and when the user will click on move up or move down button then the selected jpanel will move up or down.
    The tool(sun java studio enterprise 8.1) is not allowing more Jpanels to add manually. so i have to add the jpanels by writing the code in to a loop. and the problem is that when i am trying to add the code in the code generated by the tool the code written out side the code by me is not integratable into the tool generated code.
    If u watch the code here am sending u ll get what am facing the problem. The idea of creating jpanels through loop is ok but when trying to impleent in tool facing difficulties.
    A example code am sending here. please tell me how i can add more panels to the scrollpane(it is the tool generated code)
    Thanks in advance , plz help me for the above
    package looptest;
    public class loopframe extends javax.swing.JFrame {
    /** Creates new form loopframe */
    public loopframe() {
    initComponents();
    private void initComponents() {
    jScrollPane1 = new javax.swing.JScrollPane();
    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    jTextField1 = new javax.swing.JTextField();
    jComboBox1 = new javax.swing.JComboBox();
    jPanel3 = new javax.swing.JPanel();
    jTextField2 = new javax.swing.JTextField();
    jComboBox2 = new javax.swing.JComboBox();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jTextField1.setText("jTextField1");
    jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2Layout.createSequentialGroup()
    .add(28, 28, 28)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 109, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(54, 54, 54)
    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 156, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(35, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(21, Short.MAX_VALUE))
    jTextField2.setText("jTextField2");
    jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
    org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    jPanel3.setLayout(jPanel3Layout);
    jPanel3Layout.setHorizontalGroup(
    jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel3Layout.createSequentialGroup()
    .add(20, 20, 20)
    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 111, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(33, 33, 33)
    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 168, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(40, Short.MAX_VALUE))
    jPanel3Layout.setVerticalGroup(
    jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel3Layout.createSequentialGroup()
    .add(21, 21, 21)
    .add(jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
    .add(jComboBox2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jTextField2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(21, Short.MAX_VALUE))
    org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
    .addContainerGap(58, Short.MAX_VALUE))
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(jPanel1Layout.createSequentialGroup()
    .add(21, 21, 21)
    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .add(49, 49, 49)
    .add(jPanel3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(66, Short.MAX_VALUE))
    jScrollPane1.setViewportView(jPanel1);
    org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(31, 31, 31)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 439, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(74, Short.MAX_VALUE))
    layout.setVerticalGroup(
    layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    .add(layout.createSequentialGroup()
    .add(30, 30, 30)
    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 254, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(55, Short.MAX_VALUE))
    pack();
    }// </editor-fold>
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new loopframe().setVisible(true);
    // Variables declaration - do not modify
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration
    and
    package looptest;
    public class Main {
    public Main() {
    public static void main(String[] args) {
    new loopframe().setVisible(true);
    }

    Thanks for here kind attention to solve my problem.
    I am thinking to create the classes separately for the components (i.e the jpanel, combobox,textbox etc)and call their instaces from the for loop .But the problem is the jpanel will contain the other components and that jpanels (unlimited jpanels will be added later)will be later added to the jscrollpane.
    By writing code, the problem is to place components( the comboboxes,textboxes etc placed on the jpanel ) in appropriate coordinates . So i am doing it through tool .
    I am sending here the sample code related to my actual need . In this i have taken a jScrollPane, on that i have added jPanel1 and on jPanel1 i have added jPanel2.On jPanel2 jTextField1, jComboBox1,jCheckBox are added. If the u ll see the code u can understand what problem i am facing.
    If i am still not clearly explained ,please ask me. plz help me if u can as u have already handled a problem similar to this.
    package addpanels;
    public class Main {
    /** Creates a new instance of Main */
        public Main() {
        public static void main(String[] args) {
            new addpanels().setVisible(true);
    } and
    package addpanels;
    public class addpanels extends javax.swing.JFrame {
        /** Creates new form addpanels */
        public addpanels() {
            initComponents();
        private void initComponents() {
            jScrollPane1 = new javax.swing.JScrollPane();
            jPanel1 = new javax.swing.JPanel();
            jPanel2 = new javax.swing.JPanel();
            jTextField1 = new javax.swing.JTextField();
            jComboBox1 = new javax.swing.JComboBox();
            jCheckBox1 = new javax.swing.JCheckBox();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jTextField1.setText("jTextField1");
            jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
            jCheckBox1.setText("jCheckBox1");
            jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
            jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
            org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
            jPanel2.setLayout(jPanel2Layout);
            jPanel2Layout.setHorizontalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel2Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 131, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 144, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                    .add(jCheckBox1)
                    .addContainerGap(39, Short.MAX_VALUE))
            jPanel2Layout.setVerticalGroup(
                jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addContainerGap(17, Short.MAX_VALUE)
                    .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                        .add(jTextField1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jComboBox1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(jCheckBox1))
                    .addContainerGap())
            org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(34, Short.MAX_VALUE))
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel1Layout.createSequentialGroup()
                    .add(26, 26, 26)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(152, Short.MAX_VALUE))
            jScrollPane1.setViewportView(jPanel1);
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(36, Short.MAX_VALUE)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 449, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(18, 18, 18))
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(32, 32, 32)
                    .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 230, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(38, Short.MAX_VALUE))
            pack();
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new addpanels().setVisible(true);
        // Variables declaration - do not modify//GEN-BEGIN:variables
        private javax.swing.JCheckBox jCheckBox1;
        private javax.swing.JComboBox jComboBox1;
        private javax.swing.JPanel jPanel1;
        private javax.swing.JPanel jPanel2;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTextField jTextField1;
        // End of variables declaration//GEN-END:variables
    }

  • Repaint() in JPanel doesn't align correctly

    Hey all,
    I'm running into this problem with a program I'm writing for work. It's basically a dispatch board which connects to our SQL server via ODBC. When the user presses a "Next" or "Prev" button, the dates will change and show the dispatching for the next or previous week respectively. However, the refreshed components go where they are supposed to, but the old screen is underneath, and shifted slightly so that nothing aligns. In turn, you can make heads or tails as to what's happening. However, if you select File -> Refresh from my menubar (calls repaint() the same way) everything is repainted correctly. Any ideas?
    package dispatchBoard.DispatchBoard;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseMotionListener;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import java.sql.*;
    import javax.swing.JPanel;
    import sun.misc.Queue;
    public class DB_MainWindow extends JPanel implements MouseListener{
         private static final long serialVersionUID = 1L;
         private int _xRes, _yRes;
         private int _techs;
         private String _dayOption, _monday, _tuesday, _wednesday, _thursday, _friday, _odbcName, _databaseName, _currYear;
         private String[] _months;
         private Tech _myTechList;
         private Font _defaultFont;
         DB_Frame _mainFrame;
         private Calendar cal = new GregorianCalendar();
         public DB_MainWindow(String _resolution, String optionString, String ofTechs, DB_Frame frame, String _odbc, String _database, String _year)
              _xRes = Integer.valueOf(_resolution.substring(0, findCharPosition(_resolution, 'x'))).intValue() - 5;
              _yRes = Integer.valueOf(_resolution.substring(findCharPosition(_resolution, 'x')+1)).intValue() - 30;
              _techs = Integer.valueOf(ofTechs).intValue();
              _dayOption = optionString;
              _mainFrame = frame;
              _odbcName = _odbc;
              _databaseName = _database;
              _currYear = _year;
              setDaysFiveStraight();
              System.out.println(_xRes + " " + _yRes);
              this.setBackground(Color.GRAY);
              this.setPreferredSize(new Dimension(_xRes,_yRes));
              this.addMouseListener(this);
         public void paint(Graphics g)
              _myTechList = null;
              int _spacing = 0;
              int _spacing2 = 0;
              g.setColor(Color.BLACK);
              g.drawLine(60,0,60,_yRes);
              _defaultFont =g.getFont();
              //draw tech barriers
              for (int i = 1; i < _techs+1; i ++)
                   _spacing = _yRes / (_techs+1);
                   g.drawLine(0, _spacing*i, 1366, _spacing*i);
              //draw day barriers
              for (int j = 1; j < 5; j++)
                   _spacing2 = (_xRes-60) / 5;
                   g.drawLine(_spacing2*j + 60, 0, _spacing2*j + 60, 768);
              int _curPos = 60, _timePos = 0;
              int _time[] = {8,9,10,11,12,1,2,3,4,5};
              for (int k = 0; k < 5; k++)
                   _curPos = 60+(k*_spacing2);
                   for (int l = 0; l < 9; l++)
                        g.drawLine( _curPos + (l*(_spacing2/9)), 0+_spacing, _curPos + (l*(_spacing2/9)), _yRes);
                        String _tempString = ""+_time[_timePos];
                        g.drawString(_tempString, _curPos + (l*(_spacing2/9)), _spacing);
                        _timePos++;
                   _timePos = 0;
              //draw graph labels
              System.out.println(_dayOption);
              g.drawString("TECHS", 10, _spacing);
              g.drawString("Monday "+_monday, 60+(_spacing2/2) - 23, _spacing/2);
              g.drawString("Tuesday "+_tuesday, 60+_spacing2+(_spacing2/2) - 26, _spacing/2);
              g.drawString("Wednesday "+_wednesday, 60+2*_spacing2+(_spacing2/2) - 33, _spacing/2);
              g.drawString("Thursday "+_thursday, 60+3*_spacing2+(_spacing2/2) - 28, _spacing/2);
              g.drawString("Friday "+_friday, 60+4*_spacing2+(_spacing2/2) - 25, _spacing/2);
               * At this point the default grid, including all labels, have been drawn on
               * the dispatch board.  Now, we have to fetch the data from the SQL server,
               * place it into some sort of form (possibly 2d array?!) and then print it out
               * on the board....
               * Here goes!
    //          this.addMouseMotionListener(this);
    //          g.drawRect(_mousePosition.x, _mousePosition.y, 10, 10);
              fillInTimes(g, _spacing, _spacing2);
         public void setDaysFiveStraight()
              if (_dayOption.equals(new String("work_week")))
                   _monday = new String("");
                   _tuesday = new String("");
                   _wednesday = new String("");
                   _thursday = new String("");
                   _friday = new String("");
                   String[] _months2 = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
                   _months = _months2;
                    * Sunday = 1
                    * Monday = 2
                   System.out.println("DAY OF THE WEEK = "+cal.get(Calendar.DAY_OF_WEEK));
                   if (cal.get(Calendar.DAY_OF_WEEK) == 2)
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 3)
                   {     //tuesday
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        System.out.println("TUESDAY = "+_tuesday);
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 4)
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        //System.out.println("TUESDAY = "+_tuesday);
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 5)
                   {     //thursday
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                   else if (cal.get(Calendar.DAY_OF_WEEK) == 6)
                   {     //friday
                        _friday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-4);
                        _monday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _tuesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _wednesday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
                        cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+1);
                        _thursday = new String(_months[cal.get(Calendar.MONTH)] + "/"+cal.get(Calendar.DAY_OF_MONTH)+"/"+cal.get(Calendar.YEAR));
         private void fillInTimes(Graphics g, int _spacing, int _spacing2) {
              // need to get the data first, building pre-defined array for test data...
              //****START REAL DATA LOAD****\\
    //          Calendar cal = new GregorianCalendar();
             try {
                 // Load the JDBC-ODBC bridge
                 Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
                 // specify the ODBC data source's URL
                 String url = "jdbc:odbc:"+_odbcName;
                 // connect
                 Connection con = DriverManager.getConnection(url,"sa",_currYear);
                 // create and execute a SELECT
                 Statement stmt = con.createStatement();
                 Statement stmt2 = con.createStatement();
                 ResultSet techList = stmt2.executeQuery("USE "+_databaseName+" SELECT Distinct(SV00301.Technician) from SV00301 join SV00115 on SV00301.Technician = SV00115.Technician where SV00115.SV_Inactive<>1");
                 // traverse through results
                 Tech temp;
                 int counter = 0;
                 while(techList.next())
                      if (_myTechList == null)
                           _myTechList = new Tech(techList.getString(1).trim());
                           System.out.println(_myTechList.getName());
                           counter++;
                      else if (!_myTechList.hasNext())
                           _myTechList.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(_myTechList.getNext().getName());
                           counter++;
                      else
                           temp = _myTechList.getNext();
                           while(temp.hasNext())
                                temp = temp.getNext();
                           temp.setNext(new Tech(techList.getString(1).trim()));
                           System.out.println(temp.getNext().getName());
                           counter++;
    //             printTechList();
                 String nextMonth, prevMonth;
                 if(cal.get(Calendar.MONTH)==11)
                      nextMonth=_months[0];
                 else
                      nextMonth = _months[cal.get(Calendar.MONTH)+1];
                 if(cal.get(Calendar.MONTH) == 0)
                      prevMonth = _months[11];
                 else
                      prevMonth = _months[cal.get(Calendar.MONTH)-1];
                 ResultSet rs = stmt.executeQuery
                 ("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00301.Task_Date)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00301.Task_Date)="+prevMonth+" or Month(SV00301.Task_Date)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                 System.out.println("USE "+_databaseName+" SELECT * from SV00301 JOIN SV00300 on SV00300.Service_Call_ID = SV00301.Service_Call_ID JOIN SV00115 on SV00300.Technician = SV00115.Technician JOIN SV000805 on SV000805.Service_Call_ID = SV00301.Service_Call_ID and SV000805.Note_Service_Index='Description' where (Month(SV00300.Date_of_Service_Call)="+_months[cal.get(Calendar.MONTH)]+" or Month(SV00300.Date_of_Service_Call)="+prevMonth+" or Month(SV00300.Date_of_Service_Call)="+nextMonth+") and SV00300.Status_of_Call='OPEN' and SV00115.SV_Inactive<>1");
                  while (rs.next()) {
                      // get current row values
                       String servicecallid = rs.getString(1).trim(),
                               tech = rs.getString(4).trim(),
                               rawDate = rs.getString(6).trim(),
                               startTime = rs.getString(7).trim(),
                               _length = rs.getString(9).trim(),
                               description = rs.getString(33).trim(),
                               customernumber = rs.getString(35).trim(),
                               custname = rs.getString(45).trim(),
                               location = rs.getString(46).trim(),
                               calltype = rs.getString(54).trim(),
                               notes = rs.getString(268).trim();   
    //                  String formattedDate = month+"/"+day+"/"+year;
    //                  System.out.println(formattedDate);
    //                  String tech = rs.getString(142).trim();
    //                  String rawDate = rs.getString(144);
                      System.out.println(rawDate);
                      String day = rawDate.substring(8,10);
                      String month = rawDate.substring(5,7);
                      String year = rawDate.substring(0,4);
                      formatNumber(day);
                      formatNumber(month);
    //                  startTime = rs.getString(145);
    //                  String _length = rs.getString(147);
                      int hour = Integer.valueOf(startTime.substring(11,13)).intValue();
                      String minute = startTime.substring(14,16);
                      int minutes = Integer.valueOf(minute).intValue();
                      minutes = minutes / 60;
                      double length = (Integer.valueOf(_length).intValue())/100;
                      // print values
                      //System.out.println ("Service_Call_ID = " + Surname);
                      if (hour!=0)
                           sortJob(new Job(servicecallid, custname, new MyDate(month,day,year), hour+minutes,length, description, customernumber, location, calltype, notes), _myTechList, tech);
                  // close statement and connection
                  stmt.close();
                  con.close();
                  catch (java.lang.Exception ex) {
                      ex.printStackTrace();
              //draw techs and blocks of jobs!!!!!
              //***TECHS***\\
             Tech _tempTech = new Tech("DOOKIE");
              int multiplier = 2;
              if (_myTechList.hasNext())
                   g.setColor(Color.BLACK);
                   _tempTech = _myTechList.getNext();
                   g.drawString(_myTechList.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_myTechList.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_myTechList,multiplier, _spacing,_spacing2);
                   multiplier++;
              while(_tempTech.hasNext())
                   g.setColor(Color.BLACK);
                   g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
                   System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
                   printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
                   multiplier++;
                   _tempTech = _tempTech.getNext();
              g.setColor(Color.BLACK);
              g.drawString(_tempTech.getName(),5,(_spacing)*multiplier);
              System.out.println("printJobs(g, "+_tempTech.getName()+","+multiplier+","+_spacing+","+_spacing2+")");
              printJobs(g,_tempTech,multiplier, _spacing,_spacing2);
              //***TIME BLOCKS***\\\
         private void printTechList() {
              // TODO Auto-generated method stub
              boolean temp = !_myTechList.hasNext();
              Tech tempTech = _myTechList;
              System.out.println("BEGINNING TECH LIST PRINTOUT!!!!");
              while (tempTech.hasNext() || temp)
                   System.out.println(tempTech.getName());
                   if (temp)
                        temp = !temp;
                   else
                        tempTech = tempTech.getNext();
              System.out.println(tempTech.getName());
              System.out.println("END TECH LIST PRINTOUT!!!");
         private void formatNumber(String month) {
              // TODO Auto-generated method stub
              if (month.equals(new String("01")))
                   month = new String("1");
              else if (month.equals(new String("02")))
                   month = new String("2");
              else if (month.equals(new String("03")))
                   month = new String("3");
              else if (month.equals(new String("04")))
                   month = new String("4");
              else if (month.equals(new String("05")))
                   month = new String("5");
              else if (month.equals(new String("06")))
                   month = new String("6");
              else if (month.equals(new String("07")))
                   month = new String("7");
              else if (month.equals(new String("08")))
                   month = new String("8");
              else if (month.equals(new String("09")))
                   month = new String("9");
         private void printJobs(Graphics g, Tech techList, int multiplier, int _spacing, int _spacing2) {
              Job tempJob = techList.getJobs();
              boolean temp = false;
              if (tempJob != null)
              {     temp = !tempJob.hasNext();
              while (tempJob.hasNext() || temp)
                   g.setColor(Color.RED);
                   String _tempDate = new String(tempJob.getDate().toString());
    //               System.out.println("This job has date of: "+_tempDate);
                   int horizontalMultiplier = 0;
                   if (_tempDate.equals(_monday))
                        horizontalMultiplier = 0;
                   else if (_tempDate.equals(_tuesday))
                        horizontalMultiplier = 1;
                   else if (_tempDate.equals(_wednesday))
                        horizontalMultiplier = 2;
                   else if (_tempDate.equals(_thursday))
                        horizontalMultiplier = 3;
                   else if (_tempDate.equals(_friday))
                        horizontalMultiplier = 4;
                   else
                        horizontalMultiplier = 5;
    //               System.out.println("HorizontalMultiplier = "+horizontalMultiplier);
                   if (horizontalMultiplier !=5)
                        if (tempJob.getJobCallType().equals(new String("TM"))) g.setColor(new Color(0,255,0));
                        else if (tempJob.getJobCallType().equals(new String("SU"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("SPD"))) g.setColor(new Color(44,148,67));
                        else if (tempJob.getJobCallType().equals(new String("QUO"))) g.setColor(new Color(0,255,255));
                        else if (tempJob.getJobCallType().equals(new String("MCC"))) g.setColor(new Color(255,0,255));
                        else if (tempJob.getJobCallType().equals(new String("MC"))) g.setColor(new Color(128,0,255));
                        else if (tempJob.getJobCallType().equals(new String("CBS"))) g.setColor(new Color(0,0,255));
                        else if (tempJob.getJobCallType().equals(new String("AS"))) g.setColor(new Color(255,255,255));
                        else g.setColor(Color.red);
                        g.fillRect(/*START X*/(int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1),/*START Y*/_spacing*(multiplier-1)+1,/*LENGTH*/(int)(tempJob.getJobLength()*(_spacing2/9)-1),/*WIDTH*/_spacing-1);
                        System.out.println("g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        g.setColor(Color.BLACK);
                        g.setFont(new Font("Monofonto", Font.PLAIN, 22));
                        if ((int)(tempJob.getJobLength()*(_spacing2/9)-1) >0)
                             g.drawString(formatStringLength(tempJob.getJobName().toUpperCase(), tempJob.getJobLength()), (int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1), (_spacing*(multiplier)+1)-_spacing/2+5);
                        g.setFont(_defaultFont);
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
                   else
                        System.out.println("*g.fillRect("+((int)(60+(horizontalMultiplier*_spacing2)+(tempJob.getStarTime()-8)*(_spacing2/9)+1))+","+(_spacing*(multiplier-1)+1)+","+((int)(tempJob.getJobLength()*(_spacing2/9)-1))+","+(_spacing-1)+") :: Multiplier = "+multiplier+" :: JOB NAME = "+tempJob.getJobName()+" :: JOB NUMBER = "+tempJob.getJobNumber());
                        if (!temp)
                             tempJob = tempJob.getNext();
                             if (tempJob.hasNext() == false)
                                  temp = true;
                        else
                             temp = !temp;
         //     g.fillRect((int)(60+(tempJob.getStarTime()-8)*(_spacing2/9)+1),_spacing*(multiplier-1)+1,(int)(tempJob.getJobLength()*(_spacing2/9)-1),_spacing-1);
         private String formatStringLength(String string, double jobLength) {
              // TODO Auto-generated method stub
              if (jobLength*3>string.length())
                   return string;
              return string.substring(0, new Double(jobLength*3).intValue());
         private void sortJob(Job job, Tech techList, String techName) {
              Tech _tempTech2;
              if (techName.equals(techList.getName()))
                   techList.insertJob(job);
                   System.out.println("ADDED " + job.getJobName() +" TO " + techName);
              else
                   _tempTech2 = techList.getNext();
                   while (!_tempTech2.getName().equals(techName) && _tempTech2.hasNext())
                        _tempTech2 = _tempTech2.getNext();
    //                    System.out.println(_tempTech2.getName()+" vs. " + techName);
                   if (_tempTech2.getName().equals(techName))
                        _tempTech2.insertJob(job);
                        System.out.println("ADDED " + job.getJobName() +" TO " + techName);
                   else
                        System.out.println("TECH NAME: "+_tempTech2.getName()+" NOT FOUND :: COULD NOT INSERT JOB");
         private int findCharPosition(String _resolution2, char c) {
              // TODO Auto-generated method stub
              for (int i = 0; i < _resolution2.length(); i++)
                   if (_resolution2.charAt(i) == c)
                        return i;
              return 0;
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
              System.out.println("Mouse clicked at coordinates: "+arg0.getX()+", "+arg0.getY()+"\nAttempting to intelligently find the job number");
               * Find the tech
              int techNum = arg0.getY()/(_yRes / (_techs+1));
              String techName= new String("");
              int counter = 0;
              Tech temp = _myTechList;
              boolean found = true;
              while(temp.hasNext() && found)
                   counter++;
                   if (counter == techNum)
                        techName = temp.getName();
                        found = false;
                   else
                        temp = temp.getNext();
              System.out.println("The "+techNum+"th tech was selected... which means you clicked "+techName);
               * Find the day
              int day = (arg0.getX()-60)/(0 + ((_xRes-60)/5));
              String days[] = {_monday, _tuesday, _wednesday, _thursday, _friday};
              System.out.println("The day you chose was "+days[day]);
               * Find the time
              int blocksIn = ((arg0.getX()-60)/(((_xRes-60)/5)/9))%9;
              System.out.println(blocksIn+" blocks inward!!!!");
               * Find the job
               *           - temp is already initialized to the current tech!!
              System.out.println(temp.getName()+" has "+temp.getNumberOfJobs()+" jobs");
              Job current = temp.getJobs();
              Queue jobQueue = new Queue();
              boolean first = true;
              while(current.hasNext() || first)
                   if(current.getDate().toString().equals(days[day]))
                        jobQueue.enqueue(current);
                        System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
                   else
                        System.out.println("Did not queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
                        if (first)
                             first = false;
                             current = current.getNext();
                        else
                             current = current.getNext();
              if(current.getDate().toString().equals(days[day]))
                   jobQueue.enqueue(current);
                   System.out.println("Queued the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              else
                   System.out.println("Did not queue the job on "+current.getDate().toString()+"::"+current.getJobNumber());
              blocksIn+=8;
              while(!jobQueue.isEmpty())
                   try {
                         * Get a job off the queue... now check the times
                        Job dqJob = (Job)jobQueue.dequeue();
                        System.out.println(dqJob.getStarTime()+"<="+blocksIn +" && "+(dqJob.getStarTime()+dqJob.getJobLength()-1)+">="+blocksIn+" :: "+dqJob.getJobName());
                        if (dqJob.getStarTime()<=blocksIn && dqJob.getStarTime()+dqJob.getJobLength()-1>=blocksIn)
                             System.out.println("MONEY!!!! Found job: "+dqJob.getJobName());
                             new JobDisplayer(dqJob, _xRes, _yRes);
                   } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void mouseClicked(MouseEvent arg0) {
              // TODO Auto-generated method stub
         public void nextDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)+7);
                   setDaysFiveStraight();
              this.repaint();
         public void prevDay() {
              // TODO Auto-generated method stub
              if (_dayOption.equals(new String("work_week")))
                   cal.set(Calendar.DAY_OF_YEAR, cal.get(Calendar.DAY_OF_YEAR)-7);
                   setDaysFiveStraight();
                   this.repaint();
              this.repaint();
    }Sorry for the huge chunk of code.
    Thanks in advance,
    Jeff

    Sorry for the huge chunk of code.
    Mm, yes, I'm far too lazy to read all that.
    But you should be overriding paintComponent(), not paint().
    http://www.google.co.uk/search?hl=en&q=java+swing+painting&btnG=Google+Search&meta=
    I've not bothered to work out from that pile of magic numbers exactly what you're tring to draw but is it not something that JTable would happily do?

  • Randomaccessfile, writing an update to the file?

    Hi,
    I'm working on an app that uses a randomaccessfile (student.dat) and I have it so it will write info to the dat file & I can search thru what I entered..... now I need to add the ability to update a record in the dat. The student info is just basic name & address. So I need to be able to update an address change for a given record.
    I looked at the documentation online but I'm not understanding how you capture the reference point in the file and modify it.... does anyone have a good example or does anyone out there know how to explain how to do it to me??
    My file is here below that I need to add the update functionality to (and the 2 accompaning files)...... I already inserted my Update button on the second panel where it needs to reside. Now I need to add the update functionality to the button.
    Anyone have any suggestions/explanations on how to add this fnctionality or know a working example I can reference?? Any help would be great appreciated.... thanks.
    // StudentRecords.java: Store and read data
    // using RandomAccessFile
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class StudentRecords extends JFrame {
      // Create a tabbed pane to hold two panels
      private JTabbedPane jtpStudent = new JTabbedPane();
      // Random access file for access the student.dat file
      private RandomAccessFile raf;
      /** Main method */
      public static void main(String[] args) {
        StudentRecords frame = new StudentRecords();
        frame.pack();
        frame.setTitle("Test RandomAccessFile");
        frame.setVisible(true);
      /** Default constructor */
      public StudentRecords() {
        // Open or create a random access file
        try {
          raf = new RandomAccessFile("student.dat", "rw");
        catch(IOException ex) {
          System.out.print("Error: " + ex);
          System.exit(0);
        // Place buttons in the tabbed pane
        jtpStudent.add(new RegisterStudent(raf), "Register Student");
        jtpStudent.add(new ViewStudent(raf), "View Student");
        // Add the tabbed pane to the frame
        getContentPane().add(jtpStudent);
    // Register student panel
    class RegisterStudent extends JPanel implements ActionListener {
      // Button for registering a student
      private JButton jbtRegister;
      // Student information panel
      private StudentPanel studentPanel;
      // Random access file
      private RandomAccessFile raf;
      public RegisterStudent(RandomAccessFile raf) {
        // Pass raf to RegisterStudent Panel
        this.raf = raf;
        // Add studentPanel and jbtRegister in the panel
        setLayout(new BorderLayout());
        add(studentPanel = new StudentPanel(),
          BorderLayout.CENTER);
        add(jbtRegister = new JButton("Register"),
          BorderLayout.SOUTH);
        // Register listener
        jbtRegister.addActionListener(this);
      /** Handle button actions */
    //   JFileChooser fc;
      public void actionPerformed(ActionEvent e) {
        if (e.getSource() == jbtRegister) {
          Student student = studentPanel.getStudent();
          try {
            raf.seek(raf.length());
            student.writeStudent(raf);
          catch(IOException ex) {
            System.out.print("Error: " + ex);
    // View student panel
    class ViewStudent extends JPanel implements ActionListener {
      // Buttons for viewing student information
      private JButton jbtFirst, jbtNext, jbtPrevious, jbtLast, jbtUpdate;
      // Random access file
      private RandomAccessFile raf = null;
      // Current student record
      private Student student = new Student();
      // Create a student panel
      private StudentPanel studentPanel = new StudentPanel();
      // File pointer in the random access file
      private long lastPos;
      private long currentPos;
      public ViewStudent(RandomAccessFile raf) {
        // Pass raf to ViewStudent
        this.raf = raf;
        // Panel p to hold four navigator buttons
        JPanel p = new JPanel();
        p.setLayout(new FlowLayout(FlowLayout.LEFT));
        p.add(jbtFirst = new JButton("First"));
        p.add(jbtNext = new JButton("Next"));
        p.add(jbtPrevious = new JButton("Previous"));
        p.add(jbtLast = new JButton("Last"));
        p.add(jbtUpdate = new JButton("Update"));
        // Add panel p and studentPanel to ViewPanel
        setLayout(new BorderLayout());
        add(studentPanel, BorderLayout.CENTER);
        add(p, BorderLayout.SOUTH);
        // Register listeners
        jbtFirst.addActionListener(this);
        jbtNext.addActionListener(this);
        jbtPrevious.addActionListener(this);
        jbtLast.addActionListener(this);
        jbtUpdate.addActionListener(this);
      /** Handle navigation button actions */
      public void actionPerformed(ActionEvent e) {
        String actionCommand = e.getActionCommand();
        if (e.getSource() instanceof JButton) {
          try {
            if ("First".equals(actionCommand)) {
              if (raf.length() > 0)
                retrieve(0);
            else if ("Next".equals(actionCommand)) {
              currentPos = raf.getFilePointer();
              if (currentPos < raf.length())
                retrieve(currentPos);
            else if ("Previous".equals(actionCommand)) {
              currentPos = raf.getFilePointer();
              if (currentPos > 0)
                retrieve(currentPos - 2*2*Student.RECORD_SIZE);
            else if ("Last".equals(actionCommand)) {
              lastPos = raf.length();
              if (lastPos > 0)
                retrieve(lastPos - 2*Student.RECORD_SIZE);
            else if ("Update".equals(actionCommand)) {
         //     raf.writeChars(student.dat);     //HOW DO I UPDATE THE FILE????????????????
          catch(IOException ex) {
            System.out.print("Error: " + ex);
      /** Retrieve a record at specified position */
      public void retrieve(long pos) {
        try {
          raf.seek(pos);
          student.readStudent(raf);
          studentPanel.setStudent(student);
        catch(IOException ex) {
          System.out.print("Error: " + ex);
    // This class contains static methods for reading and writing
    // fixed length records
    class FixedLengthStringIO {
      // Read fixed number of characters from a DataInput stream
      public static String readFixedLengthString(int size,
        DataInput in) throws IOException {
        char c[] = new char[size];
        for (int i=0; i<size; i++)
          c[i] = in.readChar();
        return new String(c);
      // Write fixed number of characters (string s with padded spaces)
      // to a DataOutput stream
      public static void writeFixedLengthString(String s, int size,
        DataOutput out) throws IOException {
        char cBuffer[] = new char[size];
        s.getChars(0, s.length(), cBuffer, 0);
        for (int i = s.length(); i < cBuffer.length; i++)
          cBuffer[i] = ' ';
        String newS = new String(cBuffer);
        out.writeChars(newS);
    }Student Panel....................
    // StudentPanel.java: Panel for displaying student information
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    public class StudentPanel extends JPanel {
      JTextField jtfName = new JTextField(32);
      JTextField jtfStreet = new JTextField(32);
      JTextField jtfCity = new JTextField(20);
      JTextField jtfState = new JTextField(2);
      JTextField jtfZip = new JTextField(5);
      /** Construct a student panel */
      public StudentPanel() {
        // Set the panel with line border
        setBorder(new BevelBorder(BevelBorder.RAISED));
        // Panel p1 for holding labels Name, Street, and City
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(3, 1));
        p1.add(new JLabel("Name"));
        p1.add(new JLabel("Street"));
        p1.add(new JLabel("City"));
        // Panel jpState for holding state
        JPanel jpState = new JPanel();
        jpState.setLayout(new BorderLayout());
        jpState.add(new JLabel("State"), BorderLayout.WEST);
        jpState.add(jtfState, BorderLayout.CENTER);
        // Panel jpZip for holding zip
        JPanel jpZip = new JPanel();
        jpZip.setLayout(new BorderLayout());
        jpZip.add(new JLabel("Zip"), BorderLayout.WEST);
        jpZip.add(jtfZip, BorderLayout.CENTER);
        // Panel p2 for holding jpState and jpZip
        JPanel p2 = new JPanel();
        p2.setLayout(new BorderLayout());
        p2.add(jpState, BorderLayout.WEST);
        p2.add(jpZip, BorderLayout.CENTER);
        // Panel p3 for holding jtfCity and p2
        JPanel p3 = new JPanel();
        p3.setLayout(new BorderLayout());
        p3.add(jtfCity, BorderLayout.CENTER);
        p3.add(p2, BorderLayout.EAST);
        // Panel p4 for holding jtfName, jtfStreet, and p3
        JPanel p4 = new JPanel();
        p4.setLayout(new GridLayout(3, 1));
        p4.add(jtfName);
        p4.add(jtfStreet);
        p4.add(p3);
        // Place p1 and p4 into StudentPanel
        setLayout(new BorderLayout());
        add(p1, BorderLayout.WEST);
        add(p4, BorderLayout.CENTER);
      /** Get student information from the text fields */
      public Student getStudent() {
        return new Student(jtfName.getText().trim(),
                           jtfStreet.getText().trim(),
                           jtfCity.getText().trim(),
                           jtfState.getText().trim(),
                           jtfZip.getText().trim());
      /** Set student information on the text fields */
      public void setStudent(Student s) {
        jtfName.setText(s.getName());
        jtfStreet.setText(s.getStreet());
        jtfCity.setText(s.getCity());
        jtfState.setText(s.getState());
        jtfZip.setText(s.getZip());
    }Student file............
    // Student.java: Student class encapsulates student information
    import java.io.*;
    public class Student implements Serializable {
      private String name;
      private String street;
      private String city;
      private String state;
      private String zip;
      // Specify the size of five string fields in the record
      final static int NAME_SIZE = 32;
      final static int STREET_SIZE = 32;
      final static int CITY_SIZE = 20;
      final static int STATE_SIZE = 2;
      final static int ZIP_SIZE = 5;
      // the total size of the record in bytes, a Unicode
      // character is 2 bytes size
      final static int RECORD_SIZE =
        (NAME_SIZE + STREET_SIZE + CITY_SIZE + STATE_SIZE + ZIP_SIZE);
      /** Default constructor */
      public Student() {
      /** Construct a Student with specified name, street, city, state,
         and zip
      public Student(String name, String street, String city,
        String state, String zip) {
        this.name = name;
        this.street = street;
        this.city = city;
        this.state = state;
        this.zip = zip;
      /** Return name */
      public String getName() {
        return name;
      /** Return street */
      public String getStreet() {
        return street;
      /** Return city */
      public String getCity() {
        return city;
      /** Return state */
      public String getState() {
        return state;
      /** Return zip */
      public String getZip() {
        return zip;
      /** Write a student to a data output stream */
      public void writeStudent(DataOutput out) throws IOException {
        FixedLengthStringIO.writeFixedLengthString(
          name, NAME_SIZE, out);
        FixedLengthStringIO.writeFixedLengthString(
          street, STREET_SIZE, out);
        FixedLengthStringIO.writeFixedLengthString(
          city, CITY_SIZE, out);
        FixedLengthStringIO.writeFixedLengthString(
          state, STATE_SIZE, out);
        FixedLengthStringIO.writeFixedLengthString(
          zip, ZIP_SIZE, out);
      /** Read a student from data input stream */
      public void readStudent(DataInput in) throws IOException {
        name = FixedLengthStringIO.readFixedLengthString(
          NAME_SIZE, in);
        street = FixedLengthStringIO.readFixedLengthString(
          STREET_SIZE, in);
        city = FixedLengthStringIO.readFixedLengthString(
          CITY_SIZE, in);
        state = FixedLengthStringIO.readFixedLengthString(
          STATE_SIZE, in);
        zip = FixedLengthStringIO.readFixedLengthString(
          ZIP_SIZE, in);

    Advise sounds strikingly similar to what I mentioned
    page b4. Look, can you post the entire class in code
    tags ... and the entire file as well?@Bill,
    Yes, I read yours but (sorry, its hard to answer multiple replies in these forums) but I could not understand some of what you suggested. If you look at the //???? lines I commented on your code below you'll see where I'm lost on what you are doing there. You also mentioned a "marker"... is that the currentPos thing in the code of mine, to get the current position?
    Both you and Andrew suggested classes to some extent but I'm not sure how to it or what goes in it. If you look at my code paste above the buttons seem to have everything in the action, not a class, other than the register button on the other pane (which has a write method in studentpanel.java).
    I'm trying to follow/implement what u guys have been suggesting... but my brain just is not wrapping around the what I should type & where..... :-( Got any further explanation/demonstration of what I should be doing?? Sorry, I'm not that skilled of a programmer yet...
    int curr_ptr = 0,
    prev_ptr = 0;
    String marker = "ADDRS=",
    address="My new address",
    record = null;
    while ( ( record = raf.readLine() ) != null ) {   //????
    curr_ptr = raf.getFilePointer();
    if ( ( idx = record.indexOf("marker") ) != -1 ) {   //????
    record = record.substring( 0, 6 ) + address;  //????
    raf.seek( prev_ptr );
    raf.writeBytes( record );
    curr_ptr = raf.getFilePointer();
    raf.seek(curr_ptr);
    }

  • Event handling in JMenu in JPanel

    Hi,
    I'm writing a small register program GUI. I have a problem with ActionListener in JMenu. I wrote a JPanel which creates a JMenu and that works just fine. The problem is that id doesn't give any event signals. I have another class which impelemets ActionListener and it works fine with JButton (another panel for buttons), but not with JMenu.
    Below is the JPanel for JMenu and Application which implements the ActionListener. Do you see anything wrong? I really can't imagine why I cannot get the action signals. JPanel is defined in JFrame as it should be. Have you got any ideas?
    Regards,
    Marko
    class MenuPanel extends JPanel {
         protected JMenuBar menuBar;
         protected JMenu menu;
         protected JMenuItem loadRegister;
         protected JMenuItem saveRegister;
         protected JMenuItem information;
         protected JMenuItem quit;
         public MenuPanel(Application application) {
              menuBar = new JMenuBar();          
              menu = new JMenu("Tiedosto");     
              loadRegister = new JMenuItem("Lataa");
              loadRegister.addActionListener(application);
              saveRegister = new JMenuItem("Talleta");
              saveRegister.addActionListener(application);
              information = new JMenuItem("Tietoja");
              information.addActionListener(application);
              quit = new JMenuItem("Lopeta");                    quit.addActionListener(application);
              menu.add(loadRegister);
              menu.add(saveRegister);
              menu.addSeparator();
              menu.add(information);
              menu.add(quit);          
              menuBar.add(menu);
    class Application implements ActionListener {     
         // Define CardPanel
         private CardPanel cardPanel;
         // Define linked list for cards
         private CardList cardList = null;
         // Constructor. Initializes cardPanel and cardList
         public Application(CardPanel cardPanelRefrence) {
              cardPanel = cardPanelRefrence;
              cardList = new CardList();
         public void actionPerformed(ActionEvent action) {
              String actionPerformed = action.getActionCommand();
              if (actionPerformed.equals("Lataa")) {
                   load();          
              if (actionPerformed.equals("Talleta")) {
                   save();          
              if (actionPerformed.equals("Tietoja")) {
                   info();          
              if (actionPerformed.equals("Lopeta")) {
                   System.exit(0);
    // Continues with the methods...

    Well, I found the answer. Heh, quite easy one but it took a while before I found it..
    Just if you ever have similar problem. The problem was that in my JFrame I didn't create an object of class (Application) which implement s the ActionListener before using it as a reference in creating JPanel object. Quite confusing explanation, but here the code. This code was in my JFrame which was not included in this question.
    private Application application;
    private MenuPanel menuPanel;
    application = new Application(cardPanel, rightInfoPanel);
    menuPanel = new MenuPanel(application);
    These two were introduced other way round, so that variable "application" was null. What a problem in fact.. :)
    - Marko

  • Writing to .txt file

    Hi
    Thanks for any help and advice i got with my last problem, an other small problem i have. I'm tring to use a gui to write information to a file, its compling with no errors, creates the file but won't write any thing to it. I have it inside the try and catch no luck i've tried it out side the try and catch also. The same problem
    Any help would be great i know its only something small just can't see it
    Cheers
    Ambrose
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.io.*;
    public class Create_Mail extends JPanel implements ActionListener
    private JButton b1;
    private JButton b4;
    private JButton b2;
    private JButton b3;
    private JLabel l4;
    private JLabel l5;
    private JTextArea ta6;
    private JComboBox comb7;
    private JTextField t8;
    private JTextField t9;
    private JButton b10;
    private FileOutputStream fos;
         private PrintWriter out;
    public Create_Mail() {
    //construct preComponents
    String[] jcomp7Items = {"Ireland", "IP 1", "IP 2", "IP 3", "IP 4", "IP 5", "America", "IP1", "IP2", "IP3"};
    //construct components
    b1 = new JButton ("Save E-Mail");
    b4 = new JButton ("a");
    b2 = new JButton ("Exit System");
    b3 = new JButton ("Main Menu");
    l4 = new JLabel (" To :");
    l5 = new JLabel (" Subject :");
    ta6 = new JTextArea (5, 5);
    comb7 = new JComboBox (jcomp7Items);
    t8 = new JTextField (5);
    t9 = new JTextField (5);
    b10 = new JButton ("Calculate Size of E-Mail");
    //adjust size and set layout
    setPreferredSize (new Dimension (482, 488));
    setLayout (null);
    //add components
    add (b4);
    add (b1);
    add (b2);
    add (b3);
    add (l4);
    add (l5);
    add (ta6);
    add (comb7);
    add (t8);
    add (t9);
    add (b10);
    //set component bounds
    b1.setBounds (35, 360, 100, 20);
    b2.setBounds (160, 395, 105, 20);
    b3.setBounds (160, 360, 100, 20);
    b4.setBounds (100, 460, 95, 20);
    b10.setBounds (285, 360, 180, 20);
    l4.setBounds (25, 30, 100, 25);
    l5.setBounds (25, 80, 100, 25);
    ta6.setBounds (30, 150, 435, 165);
    comb7.setBounds (365, 35, 95, 20);
    t8.setBounds (135, 85, 210, 20);
    t9.setBounds (135, 35, 210, 20);
              b1.addActionListener(this);
              b2.addActionListener(this);
              b3.addActionListener(this);
              b4.addActionListener(this);
              b10.addActionListener(this);
    public void actionPerformed( ActionEvent e )
    //When the user hits the below button a comparsion is made
    //If it's true then its executes
    //The process is continued depending on the button the user hits
    System.out.println("button => "+ e.getActionCommand());
    if(( new String("a")).compareTo(e.getActionCommand()) == 0 )
    System.exit(0);
    if(( new String("Save E-Mail")).compareTo(e.getActionCommand()) == 0 )
    try
              fos = new FileOutputStream("E-mail.txt", true );
    out = new PrintWriter(new OutputStreamWriter(fos));
         String s1 = ta6.getText();
                   String s2 = t8.getText();
                   String s3 = t9.getText();
                   s1.trim();
                   s2.trim();
                   s3.trim();
                   System.out.println("Test in dos prompt");
                   out.println(s1 +"," s2 "," +s3);
                   ta6.setText("");
                   t8.setText("");
                   t9.setText("");     
              catch (Exception ex){}
    public static void main (String[] args)
    JFrame frame = new JFrame ("Create_Mail");
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    System.out.println("fgfd");
    frame.getContentPane().add (new Create_Mail());
    frame.pack();
    frame.setVisible (true);
    }

    Hello Ambrose,
    for writing text into a file use a Writer, e.g.
    BufferedWriter outfile = new BufferedWriter(new FileWriter("E-mail.txt"));
    String s= s1 +"," +s2 +"," +s3;
    outfile.write(s,0,s.length());
    outfile.newLine();hth
    J�rg

  • Problem with file writing

    Hello, I have a problem with writing a file. My code is very simple..it takes a line from one file, a line from a second file, combines them, and writes them into the third file. However, the program never gets past the point where it creates the output file. Any help is appreciated.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MergeFiles extends JApplet implements ActionListener
        private final String filename = "mergedfiles.txt";
        BufferedReader f1in, f2in;
        FileOutputStream outputstream;
        JTextField f1f = new JTextField("file1.txt", 20);
        JTextField f2f = new JTextField("file2.txt", 20);
        String F1text, F2text, F3text;
        JLabel title = new JLabel("Merge files program! Press enter to merge!");
        JButton merge = new JButton("MERGE! MERGE! MERGE!");
        JLabel labelone = new JLabel("File one");
        JLabel labeltwo = new JLabel("File two");
        Container con = getContentPane();
        JPanel pane = new JPanel();
        GridBagConstraints c = new GridBagConstraints();
        public void makedisplay()
            Insets i = new Insets(10, 10, 10, 10);
            pane.setLayout(new GridBagLayout());
            pane.setBackground(Color.green);
            con.setBackground(Color.green);
            con.add(pane, BorderLayout.CENTER);
            con.add(title, BorderLayout.NORTH);
            c.weightx = 0;
            c.insets = i;
            c.gridy = 0;
            c.gridx = 0;
            pane.add(labelone, c);
            c.gridx = 1;
            pane.add(labeltwo, c);
            c.gridx = 0;
            c.gridy = 1;
            c.ipadx = 50;
            pane.add(f1f, c);
            c.gridx = 1;
            pane.add(f2f, c);
            c.gridx = 0;
            c.gridy = 2;
            c.gridwidth = 3;
            c.ipadx = 0;
            pane.add(merge, c);
        public void init()
            makedisplay();
            merge.addActionListener(this);
        public void actionPerformed(ActionEvent e)
            openfiles();
            File f = new File("H://mergefiles//mergedfile.txt");
            try {
                title.setText("AAA");
                BufferedWriter out = new BufferedWriter(new FileWriter(f));
                F1text = f1in.readLine();
                F2text = f2in.readLine();
                title.setText("BBB");
                F3text = "" + F1text + F2text;
                out.write("" + F3text);
                f1in.close();
                f2in.close();
                out.close();
             catch (IOException ex)
        public void openfiles()
            try
                BufferedReader f1in = new BufferedReader(new FileReader(f1f.getText()));
                title.setText("file one opened");
            catch (FileNotFoundException e)
                title.setText("File one not found!");
            try
                BufferedReader f2in = new BufferedReader(new FileReader(f2f.getText()));
                title.setText("File two opened");
            catch (FileNotFoundException e)
                title.setText("File two not found!");
    }

    Nevermind, I've fixed the problem...for some reason you can't use the writer with an applet. I've written some new code that works:
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class MergeFiles2
        static String F1L = "", F2L = "";
        static File file1 = new File("H://mergefiles//file1.txt");
        static File file2 = new File("H://mergefiles//file2.txt");
        public static void main(String[] args) throws IOException
            PrintWriter out = new PrintWriter(new FileWriter("file3.txt"));
            BufferedReader f1in = new BufferedReader(new FileReader(file1));
            BufferedReader f2in = new BufferedReader(new FileReader(file2));
            while (F1L != null)
                F1L = f1in.readLine();
                if (F1L != null)
                    out.println(F1L);
            while (F2L != null)
                F2L = f2in.readLine();
                if (F2L != null)
                    out.println(F2L);
            out.close();
    }

  • How do I draw on a Jpanel

    I've spent around 15 hours trying to work out how to draw something as simple as a line onto a JPanel!
    I kind of understand about using paint, set color etc. if I was writing code in notepad I'm sure that it wouldn't be a problem but as I'm using the JDK SE form editor I'm very confused as to what should be done.
    Basically i have a frame with 2 panels in gridLayout position and filled top to bottom left to right equally spaced.
    I've added a button to the left panel. When this button is clicked I want to draw a line on the right panel. It's that simple! If I can do that then I can move on.
    All the examples i've read don't show what to do when using the JDK SE form editor. Please can someone tell me exactly what to do...thanks

    see if you can follow this
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    class Testing extends JFrame
      public Testing()
        setSize(400,300);
        setLocation(200,100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        getContentPane().add(new DrawPanel());
        pack();
      public static void main(String[] args){new Testing().setVisible(true);}
    class DrawPanel extends JPanel
      java.util.List points = new java.util.ArrayList();
      public DrawPanel()
        setPreferredSize(new Dimension(400,300));
        setBackground(Color.WHITE);
        addMouseListener(new MouseAdapter(){
          public void mousePressed(MouseEvent me){
            points = new java.util.ArrayList();
            points.add(me.getPoint());}});
        addMouseMotionListener(new MouseMotionListener(){
          public void mouseMoved(MouseEvent me){}
          public void mouseDragged(MouseEvent me){
            points.add(me.getPoint());
            DrawPanel.this.repaint();}});
      public void paintComponent(Graphics g)
        super.paintComponent(g);
        if(points.size() > 0)
          Point sPt = (Point)points.get(0);
          for(int x = 1, y = points.size(); x < y; x++)
            Point ePt = (Point)points.get(x);
            g.drawLine(sPt.x,sPt.y,ePt.x,ePt.y);
            sPt = ePt;
    }if you want a bit of advice - dump the gui builder

  • JPanel with many children doesn't display them all in a narrow window

    I'm writing an application that has a JPanel at the top containing many
    JToolBars. However, the height of the JPanel stays constant when I narrow
    the application window so that many of the JToolBars are not displayed.
    I would like to have the JPanel increase in height as the window narrows
    so that all the JToolBars remain visible. How can you do this? Thanks.
    Try widening/narrowing the window in this example:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Sample extends JFrame {
        public Sample(String name) {
            super(name);
            JPanel tp = new JPanel(new FlowLayout());
            for (int i = 0; i < 10; i++) {
                JToolBar tb = new JToolBar("toolbar" + i);
                for (int j = 0; j < 10; j++) {
                    tb.add(new AbstractAction(("Action" + i) + j) {
                        public void actionPerformed(ActionEvent event) {
                tp.add(tb);
            JPanel cp = new JPanel();
            cp.setSize(400, 400);
            cp.setBackground(Color.red);
            add(tp, BorderLayout.PAGE_START);
            add(cp, BorderLayout.CENTER);
        public static void main(String[] args) {
            Sample s = new Sample("Sample");
            s.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            s.setSize(500, 500);
            s.setVisible(true);
    }

    There are some neat tricks in this thread.
    http://forum.java.sun.com/thread.jspa?threadID=716580&messageID=4190052

Maybe you are looking for

  • XML Namespace Question

    Hi folks, I'm new to XML, and have been trying to validate an XML document against a schema using an online validator. I have given ultra-simple examples of my schema and document below: Schema <?xml version="1.0"?> <xs:schema xmlns:xs="http://www.w3

  • Connect two G5 with 1000BASE-T (Gigabit) - how?

    what i need to connect two G5 dual 1.8 with 1000BASE-T (Gigabit)? just a cable or some cards and routers and ....?

  • Converting digits from display to tactile vibrations

    I would like to get a pulse or pulses for the some output.. i.e. i need to convert digital output (i.e. clock display to tactile display (vibrations)) if the clock or any display, displays 345, then i would have three switches on my module, i switch

  • Cannot seem to Extend ???

    Hie there , people ! I have 2 Beans to use, from which I use the 'extends' keyword to link empQBean.java to sqlBean.java. However, I get the following error message. Can someone please help ? ERROR MESSAGE empQBean.java:6: cannot resolve symbol symbo

  • Can't transfer my ebooks to my nook get error msg E_ACT_TOO_MANY_ACTIVATIONS - Activation limit exceeded  worked fine  2 weeks ago.

    Can't get my ebooks to transfer over to my Nook.  reoccurring problem worked 2 weeks ago  Got this error msg E_ACT_TOO_MANY_ACTIVATIONS - Activation limit exceeded  Previously I have gotten it fixed with a remote chat from Adobe today no help from th