Problem with BufferedImage & "getGraphics()" / "createGraphics()"

I try to create with a servlet a Graphics2D Object with the method "createGraphics()" from a BufferedImage Object. Therefore I use the following code:
BufferedImage bufferimage=new BufferedImage(100,100,BufferedImage. TYPE_INT_RGB);
Graphics2D g2;
g2=bufferimage.createGraphics();
With the Graphics2D Object I wanna draw into the BufferedImage Object:
g2brut.drawLine(5,5,30,30);
The servlet runs fine on a Windows-PC with Apache and Jserv. On a Linux-PC the same code doesn't work: The method createGraphics() creates a bug and the servlet doesn't run any longer.
Hope someone could help!

If there are no graphical components in your Linux system, like X-Windows or something, you don't have the capabilities to use the drawing package. AWT is system-dependent and without drawing routines on your system, you can't access drawing functions in Java. Assuming this is the problem, there's a package out there that gets around that by providing system-independent access to AWT. I've only heard of the problem, never faced it myself so I don't know exactly how to implement it, but my friend ran into the same problem and solved it this way.
Here's the link: http://www.eteks.com/pja/en/
Michael Bishop

Similar Messages

  • Problem with BufferedImage.getScaledImage()

    I have som problems with BufferedImage.getScaledImage().
    When called from a servlet on my (small) linux server (redhat 7.2 on i586)
    Here is the top of the exeption stack.
    java.lang.NoClassDefFoundError
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Class.java:130)
         at java.awt.Toolkit$2.run(Toolkit.java:712)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.awt.Toolkit.getDefaultToolkit(Toolkit.java:703)
         at java.awt.Image.getScaledInstance(Image.java:129)
         at Admin.newbegadd(Admin.java:172)
    Could this depend on missing modules in my Linux installation???
    Any ideas welcome.
    /Mattias

    It sounds as though you're running a headless system...see if this helps:
    http://www.java4less.com/faqs.htm#F14

  • GetBlue() problem with BufferedImage

    hi i have an bmp image that i want to know the blue color component for the first pixel of the pixel array i create from the image
    the problem i have is that the pixels[0]=-10718816 and i get an "IllegalArgumentException --> More than one component per pixel", i thing is because the number should be between 0 and 255. but im not really sure...
    please some one help me.
    i just need to get the blue color component from the first pixel of an pixels int array from image loaded with BufferedImage
    BufferedImage img = null;
    String pix="";
    //here i load the image into the BufferedImage
    img = ImageIO.read(new File("C:\\1sierra.bmp"));
    //here i load the intArray with the rgb pixels of my BufferedImage
    int[] pixels = img.getRGB(0,0,img.getWidth(),img.getHeight(),null,0,img.getWidth());
    //here i try to get the blue color component and i get the exception
    pix =Integer.toString(img.getColorModel().getBlue(pixels[0]));

    You want to use a bit-wise AND and not the MOD operator.
    public class TryInt
         public static void main( String[] args )
              int               i = 0xFFFFFFFF;
              System.out.println( i & 0xFF ); // output: 255
              System.out.println( i % 255  ); // output: -1
    }The most significant byte of an RGB int value often holds the Alpha value which is typically 0xFF.
    Edited by: careysb on Nov 21, 2009 9:43 PM

  • Problems with BufferedImage

    Hi, i'm very new to Java.
    What I'm trying to do is process the individual pixels of an image. So far I have the following code:
         BufferedImage inputImage;
         public void loadImage()
              try
                   File input = new File("face.jpg");
                   inputImage = ImageIO.read(input);
              catch (IOException e)
                   JFrame frame = new JFrame();
                   JOptionPane.showMessageDialog(frame,
                  "File input Error!","Error", JOptionPane.ERROR_MESSAGE);
         }This loads the Image, from a jpg.
    Next I am trying to get the color data from an individual pixel so I tried this:
         int[] pixels =
                      img.getRGB (5, 5,img.getWidth()-5,img.getHeight()-5,null, 0,img.getWidth()-5);
              JFrame frame = new JFrame();
              JOptionPane.showMessageDialog(frame,
             "" + (int)pixels[1],"PixelColor", JOptionPane.ERROR_MESSAGE);However it always gives me a Coordinates out of bound exception, I am pretty sure img.getWidth() is returning the actual width of the image
    if i put in a small values say (5 ) for width and height and scan size it does return something but it looks like gobbeldy gook -16734 does not seem like an actual pixel value!
    Also I have another question how do I println to the console? Thanks
    Salik

    Yes I have verified that getWidth and getHeight return the proper height width of the image.
    here's the actual error:
    java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
         at sun.awt.image.ByteInterleavedRaster.getDataElements(Unknown Source)
         at java.awt.image.BufferedImage.getRGB(Unknown Source)
         at pixelFlow.processImage(pixelFlow.java:31)
         at pixelFlow.run(pixelFlow.java:89)
         at acm.program.Program.runHook(Program.java)

  • Problem with a method

    I have a problem with the getRGB(int x, int y) method of the BufferedImage class :
    I've load an image in it :
    1:// b is my bufferedimage clas and myimage is an image
    2:b.getGraphics().drawImage(myimage, 0, 0, this);
    3:// g is the graphics object of my paint method
    4:g.drawImage(b, 634, 225, null);
    5:// This write -16777216 and 10, 10 is a black point
    6:System.out.println(b.getRGB(10, 10));
    I think the problem is at the second line. But i'm not sure. Can somebody help ?

    That's probably not what you meant. You can do a binary and:int r = (hex & 0x00FF0000) >> 16;
    int g = (hex & 0x0000FF00) >> 8;
    int b = (hex & 0x000000FF);

  • Problem with ImageIO.read and ImageReader GIF becomes dark

    I am having problems with certain GIF images loading completely dark. I previously had problems with certain JPGs colors being distorted http://forum.java.sun.com/thread.jspa?threadID=713164&tstart=0. This was a problem in an old JDK.
    Here is the code:
                java.awt.image.BufferedImage bufferedImage = javax.imageio.ImageIO.read( new java.io.File("javabug.gif") );
                System.out.println( bufferedImage );
                javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("badcolors.jpg") );
                javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("badcolors.png") );BufferedImage Read is:
    BufferedImage@337838: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@119cca4 transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 1536 height = 1152 #numDataElements 3 dataOff[0] = 2
    Here is the GIF
    http://www.alwaysvip.com/javabug.gif
    I am using jdk1.5.0_06
    If I use java.awt.Toolkit.getDefaultToolkit().getImage instead of ImageIO.read, the problem no longer exists.
            java.awt.Image image = java.awt.Toolkit.getDefaultToolkit().getImage( file.toURL() );
            java.awt.MediaTracker mediaTracker = new java.awt.MediaTracker( new java.awt.Container() );
            mediaTracker.addImage( image, 0 );
            mediaTracker.waitForID( 0 );
            java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage( image.getWidth( null ), image.getHeight( null ), java.awt.image.BufferedImage.TYPE_INT_RGB );
            java.awt.Graphics g = bufferedImage.createGraphics();
            g.setColor( java.awt.Color.white );
            g.fillRect( 0, 0, image.getWidth( null ), image.getHeight( null ) );
            g.drawImage( image, 0, 0, null );
            g.dispose();
            javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("goodcolors.jpg") );
            javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("goodcolors.png") );BufferedImage Read is:
    BufferedImage@1bf216a: type = 1 DirectColorModel: rmask=ff0000 gmask=ff00 bmask=ff amask=0 IntegerInterleavedRaster: width = 1536 height = 1152 #Bands = 3 xOff = 0 yOff = 0 dataOffset[0] 0
    Is this another bug in the JDK? Is there a possible workaround where I can still use ImageIO.read?

    I figured out the problem. It was an actual BUG in the JDK!
    The code failed with the following JDKs:
    java version "1.5.0_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)
    Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)
    java version "1.5.0_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
    Java HotSpot(TM) Client VM (build 1.5.0_03-b07, mixed mode)
    The code ran sucessful with this JDK:
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
    If you are using the ImageIO classes, I highly suggest you upgrade to the latest JDK.
    Best,
    Scott

  • Problem with ImageIO.read and ImageReader JPG colors are distorted/wrong

    (Using JDK 1.5)
    ImageIO incorrectly reads some jpg images.
    I have a jpg image that, when read by the ImageIO api, all the colors become reddish.
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                javax.imageio.ImageIO.write( bi, "jpg", new java.io.File("badcolors.jpg") );
                javax.imageio.ImageIO.write( bi, "png", new java.io.File("badcolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }Why is this happening??? My guess is there is a problem with the ImageIO.read ?
    the jpg can be downloaded at http://www.alwaysvip.com/javabug.jpg
    <BufferedImage@11faace: type = 5 ColorModel: #pixelBits = 24 numComponents = 3 color space = java.awt.color.ICC_ColorSpace@1ebbfde transparency = 1 has alpha = false isAlphaPre = false ByteInterleavedRaster: width = 1691 height = 1269 #numDataElements 3 dataOff[0] = 2>
    I have even tried creating a new buffered image but still have the same problem:
    (suggested by http://forum.java.sun.com/thread.jspa?forumID=20&threadID=665585) "Java Forums - ImageIO: scaling and then saving to JPEG yields wrong colors"
            try
                java.awt.image.BufferedImage bi = javax.imageio.ImageIO.read( new java.io.File("javabug.jpg") );
                java.awt.image.BufferedImage out = new java.awt.image.BufferedImage( bi.getWidth(), bi.getHeight(), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics2D g = out.createGraphics();
                g.drawRenderedImage(bi, null);
                g.dispose();
                javax.imageio.ImageIO.write( out, "jpg", new java.io.File("badcolors.jpg") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }I have used the following which works but does not use the ImageIO api. However, I tried using the ImageIO to write and it worked for writing which leads me to believe there is a problem with the reader.
    (suggested by http://developers.sun.com/solaris/tech_topics/java/articles/awt.html "Server-Side AWT")
            try
                java.awt.Image image = new javax.swing.ImageIcon(java.awt.Toolkit.getDefaultToolkit().getImage("javabug.jpg")).getImage();
                java.awt.image.BufferedImage bufferedImage = new java.awt.image.BufferedImage( image.getWidth( null ), image.getHeight( null ), java.awt.image.BufferedImage.TYPE_INT_RGB );
                java.awt.Graphics g = bufferedImage.createGraphics();
                g.setColor( java.awt.Color.white );
                g.fillRect( 0, 0, image.getWidth( null ), image.getHeight( null ) );
                g.drawImage( image, 0, 0, null );
                g.dispose();
                com.sun.image.codec.jpeg.JPEGImageEncoder encoder = com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder( new java.io.FileOutputStream( "goodcolors.jpg" ) );
                encoder.encode( bufferedImage );
                javax.imageio.ImageIO.write( bufferedImage, "jpg", new java.io.File("goodiocolors.jpg") );
                javax.imageio.ImageIO.write( bufferedImage, "png", new java.io.File("goodiocolors.png") );
            catch ( java.io.IOException ioe )
                ioe.printStackTrace();
            }BTW, the following does not work either:
                java.util.Iterator readers = javax.imageio.ImageIO.getImageReadersByFormatName( "jpg" );
                javax.imageio.ImageReader reader = ( javax.imageio.ImageReader ) readers.next();
                javax.imageio.stream.ImageInputStream iis = javax.imageio.ImageIO.createImageInputStream( new java.io.File("javabug.jpg") );
                reader.setInput( iis, true );
                java.awt.image.BufferedImage bufferedImage = reader.read( 0 );

    I figured out the problem. It was an actual BUG in the JDK!
    The code failed with the following JDKs:
    java version "1.5.0_01"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)
    Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)
    java version "1.5.0_03"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_03-b07)
    Java HotSpot(TM) Client VM (build 1.5.0_03-b07, mixed mode)
    The code ran sucessful with this JDK:
    java version "1.5.0_06"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05)
    Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)
    If you are using the ImageIO classes, I highly suggest you upgrade to the latest JDK.
    Best,
    Scott

  • Problem with Background image and JFrame

    Hi there!
    I've the following problem:
    I created a JFrame with an integrated JPanel. In this JFrame I display a background image. Therefore I've used my own contentPane:
    public class MContentPane extends JComponent{
    private Image backgroundImage = null;
    public MContentPane() {
    super();
    * Returns the background image
    * @return Background image
    public Image getBackgroundImage() {
    return backgroundImage;
    * Sets the background image
    * @param backgroundImage Background image
    public void setBackgroundImage(Image backgroundImage) {
    this.backgroundImage = backgroundImage;
    * Overrides the painting to display a background image
    protected void paintComponent(Graphics g) {
    if (isOpaque()) {
    g.setColor(getBackground());
    g.fillRect(0, 0, getWidth(), getHeight());
    if (backgroundImage != null) {
    g.drawImage(backgroundImage,0,0,this);
    super.paintComponent(g);
    Now the background image displays correct. But as soon as I click on some combobox that is placed within the integrated JPanel I see fractals of the opened combobox on the background. When I minimize
    the Frame they disappear. Sometimes though I get also some fractals when resizing the JFrame.
    It seems there is some problem with the redrawing of the background e.g. it doesn't get redrawn as often as it should be!?
    Could anyone give me some hint, on how to achieve a clear background after clicking some combobox?
    Thx in advance

    I still prefer using a border to draw a background image:
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class CentredBackgroundBorder implements Border {
        private final BufferedImage image;
        public CentredBackgroundBorder(BufferedImage image) {
            this.image = image;
        public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
            int x0 = x + (width-image.getWidth())/2;
            int y0 = y + (height-image.getHeight())/2;
            g. drawImage(image, x0, y0, null);
        public Insets getBorderInsets(Component c) {
            return new Insets(0,0,0,0);
        public boolean isBorderOpaque() {
            return true;
    }And here is a demo where I load the background image asynchronously, so that I can launch the GUI before the image is done loading. Warning: you may find the image disturbing...
    import java.awt.*;
    import java.io.*;
    import java.net.URL;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class BackgroundBorderExample {
        public static void main(String[] args) throws IOException {
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame f = new JFrame("BackgroundBorderExample");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JTextArea area = new JTextArea(24,80);
            area.setForeground(Color.WHITE);
            area.setOpaque(false);
            area.read(new FileReader(new File("BackgroundBorderExample.java")), null);
            final JScrollPane sp = new JScrollPane(area);
            sp.setBackground(Color.BLACK);
            sp.getViewport().setOpaque(false);
            f.getContentPane().add(sp);
            f.setSize(600,400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
            String url = "http://today.java.net/jag/bio/JagHeadshot.jpg";
            final Border bkgrnd = new CentredBackgroundBorder(ImageIO.read(new URL(url)));
            Runnable r = new Runnable() {
                public void run() {
                    sp.setViewportBorder(bkgrnd);
                    sp.repaint();
            SwingUtilities.invokeLater(r);
    }

  • Printing problem with WindowsXP

    I've written a Java application using SDK v1.4.0 and this class works with all printers and Windows versions (95, 98, ME) on the several PCs I've tested it on except the machine running WindowsXP. Using WindowsXP, the page prints out the border around the textArea, but not the text. This problem occurs with both HPDeskJet and HPLaserJet printers connected to that PC.
    Has anyone seen a similar problem with WindowsXP? What should I change in this class, or change in the PC/printer properties, to get this print class to work with WindowsXP? All PCs tested are running Java v1.4.0.
    Russ Carroll
    (class code follows below)
    class ButtonHandlerPrint extends Frame implements ActionListener{
         public void actionPerformed(ActionEvent e){
              PageAttributes pageAttributes = new PageAttributes();
              pageAttributes.setPrintQuality(3);
              PrintJob pjob = Toolkit.getDefaultToolkit().getPrintJob(this,null,null,pageAttributes);
              if(pjob!=null){
                   Graphics pg = pjob.getGraphics();
                   if(pg!=null){
                        pg.translate(50,50);
                        textAreawinBCP.printAll(pg);
                        pg.dispose();
                   pjob.end();

    Did you find a fix for this problem? I have a similar problem with Win 2000 and JRE 1.4.0.01. My print works with Java 1.2 methods and prints fine in JRE 1.3.1 in Win 98,Me,2000, and prints fine in JRE 1.4.0.01 in Win 98 and Me but not in 2000. The problem sounds similar, but my text in a table doesn't print. I do get text printed that is in a text field.

  • GUI - Problem with GridBag

    Hi everyone,
    I have been trying to get this GUI built from the ground up and I have encountered a problem with the GridBag(exception error that the fields being added can not be done. Also, my method main seems to be off track, I have a working program which the display fields have been modified to display object and everything else is the same except that I can not get the GUI to run.
    The following is the code and any suggestions as to what I can do to get this going will be appreciated. Thank you.
    import javax.swing.JLabel; /* displays text and images*/
    import javax.swing.SwingConstants; /* common constants used with Swing*/
    import javax.swing.Icon; /* interface used to manipulate images*/
    import javax.swing.ImageIcon; /* loads images*/
    import javax.swing.JOptionPane;
    import java.util.*;
    import java.io.PrintStream;
    import java.text.DecimalFormat;
    import java.text.NumberFormat;
    import java.text.*;     
    import javax.swing.JFrame;/* provides basic window features*/     
    import java.util.Arrays;
    import javax.swing.ImageIcon.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.awt.*;
    public class FinalInventoryGUI extends JFrame
    {//Private variables.
    private GridBagLayout layout = new GridBagLayout();
    private GridBagConstraints constraints = new GridBagConstraints();
    //Private data from main program
    private String productName;
    private String itmeNumber;
    private double unitPrice;
    private int unitStock;
    private double productValue;
    private double inventoryValue;
    private double reStkfee;
    //Declaration of the JLabels.
    private JLabel logoLabel;
    private JLabel productNameLabel;
    private JLabel itemNumberLabel;
    private JLabel unitPriceLabel;
    private JLabel unitStockLabel;
    private JLabel productValueLabel;
    private JLabel InventoryValueLabel;
    private JLabel reStkfeeLabel;
    //Declaration of the text Fields for data Entry.     
    private JTextField productNameText;
    private JTextField itemNumberText;
    private JTextField unitPriceText;
    private JTextField unitStockText;
    private JTextField productValueText;
    private JTextField inventoryValueText;
    private JTextField reStkfeeText;
    private JTextField titleText;
    //Declaration of the JButtons for user interface.
    private JButton first;//To move to first element in the array.
    private JButton next;//To move to next element in the array.
    private JButton previous;//To move to next element in the array.
    private JButton lastButton;//To move to the first element in the array.
    private JButton addButton;//To add a product to the array.
    private JButton modifyButton;//To modify an element in the array.
    private JButton deleteButton;//To remove a product from the array.
    private JButton saveButton;//To save the array elements to C:\.
    private JButton searchButton;//To search for an element in the array.
    private Product products[];//Declaration of array product[] for storing entries.
    private int NumOfProducts;//Declaration of the variable defining the number of products.
    private int Index=0;//Setting the counter index to initiate at "0".
    //Constants
    private final static int LOGO_WIDTH  = 4;
    private final static int LOGO_HEIGHT = 4;
    private final static int LABEL_WIDTH  = 1;
    private final static int LABEL_HEIGHT = 1;
    private final static int TEXT_WIDTH  = LOGO_WIDTH-LABEL_WIDTH;
    private final static int TEXT_HEIGHT = 1;
    private final static int BUTTON_WIDTH  = 1;
    private final static int BUTTON_HEIGHT = 1;
    private final static int LABEL_START_ROW = LABEL_HEIGHT+LABEL_WIDTH+1;
    private final static int LABEL_COLUMN = 0;
    private final static int TEXT_START_ROW = LABEL_START_ROW;
    private final static int TEXT_COLUMN = LABEL_WIDTH+1;
    private final static int BUTTON_START_ROW = LABEL_START_ROW+9*LABEL_HEIGHT;
    private final static int BUTTON_COLUMN = LABEL_COLUMN;
    private final static int SEARCH_START_ROW = BUTTON_START_ROW+3;
    final static String EMPTY_ARRAY_MESSAGE = "Hit ADD to add a new PRODUCT";
    //Constructor-New instance of the JLabelTextFieldView.
    public FinalInventoryGUI( Product productsIn)
        {//Passing the frame title to JFrame, set the IconImage.
             super("Welcome To The Inventory Program");
             setLayout(layout);
             //Copy the input array(products).
             setProduct(productsIn);//maybe the title?????
             //Start the display with the first element of the array.
             index = 0;
             //Build the GUI
             buildGUI();
             //Values
             updateAllTextFields();
             }//End of the constructor for building the GUI.
             //Methods for copying the input of Product array to the GUIs private array
             //variable
             private void setInventoryArray(Product productsIn[])
                  products = new Product[productIn.length];
                  for (int i = 0; i<products.length; i++)
                  {//Creates A Product array element from the input array.
                       prodcuts[i] = new Product(productIn);
                   products[i] = new Product(productIn[i].productName(), productIn[i].itemNumber(),
                                                      productIn[i].unitStock(), productIn[i].unitPrice());
              //System prints out a ineof the productsIn array to a string.
         }//End of the for statment.
         }//End for copying the array.
         //A method for updating each of the GUIs fields.
         private void updateAllTextFields()
              if(products.length > 0)//Then update the JTextField display.
              {// Update the product name text field.
              productNameText.setText(products[index].productName());
              //Update the Update the itemNumber text field.
              itemNumberText.set(String.format("%d", products[index].itemNumber()));
              //Update the title text field.
              titleText.setText(dvd[index].title());
              //Update the unitStock text field.
              unitStockText.setText(String.format("%d",products[index].unitStock()));
              //Update the unit price textField.
              unitPriceText.setText(String.format("$%.2f",products[index].unitPrice()));
              //Update the productValue textField.
              productValueText.setText(String.format("$%.2f", products[index].productValue()));
              //Update the restocking fee text field.
              reStkfeeText.setText(String.format("$%.2f",reStkfee()));
              //Update the total value of the inventory text field.
              inventoryValueText.setText(String.formtat("$%.2f",Product.productValue(products)));
              }//End of the if statement.
              else//Put a special message in the fields.
              {//Update the productName textField.
              productNameText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the itemNumber textField
              itemNumberText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the title textField.
              titleText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the units in stock textField.
              unitStockText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the unitPrice textFied.
              unitPriceText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the productValue textField.
              productValueText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the restocking fee textField.
              reStkfeeText.setText(EMPTY_ARRAY_MESSAGE);
              //Update the totatl inventoryValue textField.
              inventoryValueText.setText(EMPTY_ARRAY_MESSAGE);
              }//End else
         }//Set the appropriate fields editable or uneditable.
         private void setModifiableTextFieldsEnabled(Boolean state)
         {//The fields of the product name, item number, unit price,
         // and stock can be editable or non editable.
         itemNumber.setEditable(state);
         productName.setEditable(state);
         unitPrice.setEditable(state);
         unitStock.setEditable(state);
         }//End setting of the modifiable textFields.
         //Methods for the JButton methods.
         private class ButtonHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
              {//This is the first button being pressed by the user.
                   if(event.getSource()==firstButton)
                        handleFirstButton();
                   }//End if
                   else if(event.getSource()==previousButton)//Button previous is pressed by user.
                        handlePreviousButton();
                   }//End else if
                   else if (event.getSource()==nextButton)//Button next is pressed by user.
                        handleNextButton();
                   }//End else if.
                   else if (event.getSource()==lastButton)//Button last is pressed by the user.
                        handleLastButton();
                   }//End else if.
                   else if(event.getSource()==firstButton)
                        handleFirstButton();
                   }//End else if.
         }//End metod of actionPeformed.
         }//End class ButtonHandler
         //Displaying the first element of the Product array
         private void handlerFirstButton()
         {//Setting the index to the first element in the array.
              index = 0;
         //Update and disable modification
         updateAllFields();
         setModifiableTextFieldsEnabled(false);
         }//End method for handling the first button.
         //Displaying the next element of the products array or wrap to the first.
         private void handleNextButton()
         {//Incrementation of the index.
         index++;
         //If the index exceeds the last valid array element, wrap around to the first
         //element of the array.
         if(index > products.length-1)
              index = 0;
         }//End if statment.
         //Update and disable the modification.
         updateAllFields();
         setModifiableTextFieldsEnabled(false);
         }//End method of handleNextButton.     
         private void handlePreviousButton()
              index--;
              if(index < 0)
                   index = products.length -1;
              }//End if statment.
              //Update and disabe modification.
              updateAllTextFields();
              setModifiableTextFieldsEnabled(false);
         }//End method of handlePreviousButton.
         private void handleLastButton()
              index--;
              if(index < products.length -1)
                   index = 2;
              }//End if statment.
              updateAllTextFields();
              setMdifiableTextFieldsEnabled(false);
              }//End method for handleLatButton
         //The textFieldHandler class - handling the events of the buttonsmethods
         private class TextFieldHandler implements ActionListener
              public void actionPerformed(ActionEvent event)
              {//The user pressed "ENTER" in the JTextField "title" text.
              if(event.getSource() == itemNumber)
                   //HandleItemNumberTextField()is fired.
              }//End the if statement.
              //The user pressed "ENTER" in the JTextField "title" text.
              else if (event.getSource() == titleText)
                   //HandleTitleTextField() is fired.
              }//End the if statement.
         //The user pressed "ENTER" in the JTextField "unitStoc" text.
              else if(event.getSource() == unitStockText)
                   //HandleUnitStockTextField() is fired.
              }//End the if statment
              //The user pressed "ENTER" in the JtextField "unitPrice" text.
              else if (event.getSource() == unitPriceText)
                   //HandleUnitPriceTextField() is fired.
              }//End the if statment.
         //The user pressed "ENTER" in the JTextField "Search" text.
         else if(event.getSource() == searchText)
              //HandleSearchTextField() is fired.
         }//End the if statment.
              }//End the method actionPerformed.
         }//End the inner class TextFieldhandler.
              //The GUI methods.
              //Building the GUI.
              private void BuildGUI()
              {//Mthod for adding the LOGO.
              buildLogo();
              //Add the text fields and their labels.
              buildLabels();
              buildTextFields();
              //Add the navigation and other buttons.
              buildMainButtons();
              //Provide value to the Fields.
              updateAllTextFields();
              //provide some setup to the frame.
                        setSize(FRAME_LENGTH, FRAME_WIDTH);
                        setLocation(FRAME-XLOC, FRAME_YLOC);
                        setResizable(false);
                        //PACK(); IS THIS NOT PART OF THE GUI ADDED AT THE END OR IS WHAT
                        //FOLLOWS THE SAME AS SAYING ".PACK()".
                        setDefaultCloseOperation(EXIT_ON_CLOSE);//DOES IT MATTER WHERE THIS LINE FALLS?
                        //WHEN I TRIED TO USE IT IN THE MAIN I RECEIVED AN ERROR AND THE SAME WHEN I
                        //PLACED IT IN THE CONSTRUCTOR--WHY?.
                        setVisible(true);
              }//End of building the GUI.
              //Addin the LOGO to the Frame.
              private void buildLogo()
                   constraints.weightx = 2;
                   constraints.weigthy = 1;
                   logoLabel = new JLabel(new ImageIcon("O2K.jpg"));
                   logoLabel.setText("Products Inventory");
                   constraints.fill = GridBagConstraints.BOTH;
                   addToGridbag(logoLabel,2,2,LOGO_WIDTH, LOGO_HEIGHT);
                   //Creating a vertical space.
                   addToGridBag(new JLabel(""),LOGO_HEIGHT+1,0, LOGO_WIDTH, LABEL_WIDTH);
              }//End the method with building the LOGO.
                   //Build the panel just containing the text.
                   private void buildLabels()
                   {//Set up if for readability).
                   int rows = 0;
                   int column = 0;
                   int width = 0;
                   int height = 0;
              column = LABEL_COLUMN;
              width = LABEL_WIDTH;
              height = LABEL_HEIGHT;
                   constraints.weightx = 1;
                   constraints.weighty = 0;
                        constraints.fill = GridbagConstraints.Both;
                        //Create the name labes and name the TextFields.
                        productNameLabel = new JLabel("Product Name:");
                        productnamelabel.setLabelfor(productNameField);
                        productNameLabel.setLabelFor(productNameText);
                        productNameLabel.setToolTipText("Enter The Product Name Here");
                        row = Label_START_ROW;          
                        addToGridBag(productNameLabel, row, column, width, height);
                        //Create the itemNumberLabel and TextField.
                        itemNumberLabel = new JLabel("Product Id:");
                        itemNumberLabel.setLabelFor(itemNumberText);
                        row += LABEL_HEIGHT;
                        addToGridBag(itemNumber, row, column, width, height);
                        //Create the title label for the Product and the title text field.
                        titleLabel = new JLabel("Inventory Of Products:");
                        titleLabel.setLabelFor(titleText);
                        row += LABEL_HEIGHT;
                        addToGridBag(titleLabel,row,column,width,height);
                        //Create the unitStock label and textField.
                        unitStockLabel = new JLabel("Units In Stock:");
                        unitStockLabel.setLabelFor(unitStockLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(unitStocklabel, row, column, height);
                        //Creat the unitPrice label and textField.
                        unitPriceLabel = new JLabel("Unit Price");
                        unitPriceLabel.setLabelFor(unitPriceLabel);
                        unitPriceLabel.setToolTipText("The Cost Of The Product");
                        row += LABEL_HEIGHT;
                        addToGridBag(unitPriceLabel, row, column, height);
                        //Create the productValue label and textField.
                        productValueLabel = new JLabel("Total Product Value:");          
                        productValueLabel.setLabelFor(productValueLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(productValue, row, column, height);
                        //Create the restocking fee of 1.05% Label and textField.
                        reStkfeeLabel = new JLabel("Product Restock Fee:");
                        reStkfeeLabel.setLabelFor(reStkfeeLabel);
                        row+= LABEL_HEIGHT;
                        addToGridBag(reStkfee, row, column, height);
                        //Create a vertical space.
                        row += LABEL_HEIGHT;
                        //Create the Total Inventory Value label and textField.
                        inventoryValueLabel = new JLabel("Total Inventory Value:");
                        inventoryValueLabel.setLabelFor(inventoryValueLabel);
                        row += LABEL_HEIGHT;
                        addToGridBag(inventoryValue, row, column, height);
              }//End the method for building the labels
                        //Build the methods for the TextFields.
                        private void buildTextFields()
                             {//Defining the variables
                             int row = 0;
                             int column = 0;
                             int width = 0;
                             int height = 0;
                             column = TEXT_COLUMN;
                             width = TEXT_WIDTH;
                             height = TEXT_HEIGHT;
                             constraints.fill = GridBagConstraints.BOTH;
                             constraints.weightx = 1;                    
                             TextFieldHandler handler = new TextFieldHandler();
                             productNameText = new JTextField("Product Name");
                             productNameText.setEditable(false);
                             row = TEXT_START_ROW;
                             addToGridBag(productNameText, row, column, height);
                        itemNumberText = new JTextField("Product Id");
                        itemNumberText.setEditable(false);
                        row = TEXT_START_ROW;
                        addToGridBag(itemNumberText, row, column, height);
                        titleText = new JTextField("Title");
                        titleText.addActionListener(handler);
                        titleText.setEditable(false);
                        row += TEXT_HEIGHT;
                        addToGridBag(titleText, row, column, height);
                        unitPriceText = new JTextField("Unit Price");
                        unitPriceText.addActionListener(handler);
                        unitPrice.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(unitPriceText, row, column, height);
                        unitStockText = new JTextField("Units In Stock");
                        unitStockText.addActionListener(handler);
                        unitStockText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(unitStockText, row, column, height);
                        productValueText =new TextField("Product Value");
                        productValueText.addActionListener(handler);
                        productValueText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(productValueText, row, cloumn, height);
                             reStkfeeText =new JTextField("Restock Fee");
                        reStkfeeText.addActionListener(handler);
                        reStkfeeText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(reStkfeeText, row, cloumn, height);
                        //Creat vertical space.
                        row += TEXT_HEIGHT;
                        addToGridBag(new JLabel(""),row, column, height);
                        inventoryValueText =new TextField("Inventory Value");
                        inventoryValueText.addActionListener(handler);
                        inventoryValueText.setEditable(false);
                        row += TEXT_START_ROW;
                        addToGridBag(inventoryValueText, row, cloumn, height);
                        }//End the methods for building the TextFields.
                             //Add the main buttons to the frame.
                   private void buildMainButtons()
                             {//Declaraing the variables.
                             int row = 0;
                             int column = 0;
                             int width = 0;
                             int height = 0;                         
                             row =BUTTON_START_ROW;
                             column = BUTTON_COLUMN;
                             width = BUTTON_WIDTH;
                             height = BUTTON_HEIGHT;
                             constraints.weightx = 1;
                             constraints.weighty = 0;                         
                             //The constraints.fill = GridBagConstraints.HORIZONTAL;
                             ButtonHandler handler = new ButtonHandler();
                             //Creat a veritical space.
                             addToGridbag(new JLabel(""), row, column, width, height);
                             firstButton = new JButton("First");
                             firstButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(firstButton, row, column, width, height);                         
                             previousButton = new JButton("Previous");
                             previousButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(previousButton, row, column, width, height);     
                             nextButton = new JButton("Next");
                             nextButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(nextButton, row, column, width, height);     
                             lastButton = new JButton("Last");
                             lastButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(lastButton, row, column, width, height);     
                             addButton = new JButton("Add");
                             addButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(addButton, row, column, width, height);                         
                             deleteButton = new JButton("Delete");
                             deleteButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(deleteButton, row, column, width, height);
                             saveButton = new JButton("Save");
                             saveButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(saveButton, row, column, width, height);     
                             searchButton = new JButton("Search");
                             searchButton.addActionListener(handler);
                             row += LABEL_HEIGHT;
                             addToGridBage(searchButton, row, column, width, height);                         
                        //End methods for building the main butt0ns.
         private void addToGridBag(Component component, int row, int column, int width, int height)
         {               //Set up the upper-left corner of the component gridx and gridy.
                             constraints.gridx = column;
                             constraints.gridy = row;
                             //Set the numbers of rows and columns the components occupies.
                             constraints.gridwidth = width;
                             constraints.gridheight = height;
                             //set the constraints
                             Layout.setConstraints(component, constraints);
                             //Add the component to the JFrame.
                             add(component);                    
                        }//End method for addGridBag.                     
              //End class JLabelTextFieldViewGui.
    class Invetnory4
              public static void main(String args[])
                        {   //An array variable.
                             Product[]inventory;
                             inventory = new Product[10];
                             //Create and pass control to the GUI
                             FinalInventory gui = new FinaInventoryGUI(inventory);           
                        }//End method main
                   }//End class Inventory4     
    /*Inventory.java*/
    /*Means for importing program packages*/
    /*Beginning of the class type Inventory*/

    Hi Bryan,
    I took your advice and decided to take a different approach to the problem I am having, I decided to stay somewhat with the basics with little knowledge I have about coding. I am new to this and I am trying to learn through the fire but it's getting hot so if you don't mind, can you tell me what I need to do to fix the error messages I am getting.
    1. "else" without "if',
    2. can't load my icon-a JPG
    3. exception in thread amin
    process complete.
    4.Text area for displaying an iteration of the input
    the code is not as long as the other one! any help will be appreciated. Also I am attaching the code to the GUI that does work but I can not seem to get the actionListener aspect to work. Thanks again.
      //this one works and it serves as a model for what I am //trying to do in the fields. as well as designate a text area                                                              //where a each entry per iteration of input is displayed
    * @(#)InventoryGUIFrame.java
    * @author
    * @version 1.00 2008/2/2
    package components;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    * FormattedTextFieldDemo.java requires no other files.
    * It implements a mortgage calculator that uses four
    * JFormattedTextFields.
    public class InventoryGUIFrame extends JFrame
              String productName;
              String itemNumber;
              double unitPrice;
              double unitStock;
              //Labels to identify the fields
              private JLabel productNamelabel;
              private JLabel itemNumberlabel;
              private JLabel unitPricelabel;
              private JLabel unitStocklabel;
              //Fields for data Entry     
              private JTextField productNameField;
              private JTextField itemNumberField;
              private JTextField unitPriceField;
              private     JTextField unitStockField;
                   //Adding the JButtons
              JButton firstButton;
              JButton nextButton;
              JButton previousButton;
              JButton searchButton;
              JButton addButton;
              JButton deleteButton;
              JButton saveButton;
              //Constructor          
    public InventoryGUIFrame()
             super("Welcome To The Inventory Program");
             setLayout(new FlowLayout());
             setDefaultCloseOperation(EXIT_ON_CLOSE);
             JFrame Frame = new JFrame();
             Frame JPanel = new Frame();
             JPanel  JLabel= new JPanel();
             TextArea area = new TextArea();
         productNamelabel = new JLabel("PRODUCT  NAME");
         productNamelabel.setToolTipText("Name of the item you wish to calculate");
        add(productNamelabel);
         productNameField= new JTextField(8);
         add(productNameField);
         itemNumberlabel = new JLabel("PRODUCT  NUMBER");
         itemNumberlabel.setToolTipText("Number identifying the product");
         add(itemNumberlabel);
         itemNumberField =new JTextField(5);
         add(itemNumberField);
         unitPricelabel=new JLabel("PRODUCT  PRICE");
         unitPricelabel.setToolTipText("What is the cost of the product?:");
         add(unitPricelabel);
         unitPriceField = new JTextField(5);
         add(unitPriceField);          
         unitStocklabel = new JLabel("UNITS  IN  STOCK");
         unitStocklabel.setToolTipText("How many products in inventory?:");
         add(unitStocklabel);
         unitStockField = new JTextField(5);
         add(unitStockField);
         firstButton =new JButton("First");
         add(firstButton);
         nextButton = new JButton("Next");
         add(nextButton);
         previousButton = new JButton("Previous");
         add(previousButton);
         addButton = new JButton("Add");
         add(addButton);
         deleteButton = new JButton("Delete");
         add(deleteButton);
         saveButton = new JButton("Save");
         add(saveButton);
         searchButton = new JButton("Search");
         add(searchButton);
         public static void main(String args[])
         InventoryGUIFrame frame  = new InventoryGUIFrame();
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.setSize(740,150);
         frame.setVisible(true);
      class InventorySystem6
    {     /*Declaration of products[] and the maximum storing capacity*/
       private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
       /*Prompts user to make another selection or exit program*/
       private static final String STOP_COMMAND = "stop";
            /*parameters defining maximun numbers of products available for storing in */
    private static final int MAX_NUM_OF_PRODUCTS = 100;
    /*Declaration of the variables */
    String name;
    String item;
    double stock;
    double price;
    double reStkfee=1.05;
    double pValue;
    double iValue;
    public InventorySystem6()
         /*Empty Constructor*/
    }/*Beginning of product input by the user*/
    public void inputProductInfo()
    {     /*Declaration of currency format*/     
                   DecimalFormat Currency = new DecimalFormat();
                   Scanner input = new Scanner(System.in);
                   /*Beginning of the Loop*/
                   JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
                   JOptionPane.PLAIN_MESSAGE);               
                   for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
                   name = JOptionPane.showInputDialog( "What is the Product Name? ");
                   if(name.equalsIgnoreCase("stop"))
                   break;
         String item = JOptionPane.showInputDialog("Enter the products ID");
         String priceStr =JOptionPane.showInputDialog("Enter the products price");
         double price=Double.parseDouble(priceStr);
                   String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
                   double stock = Double.parseDouble(stockStr);          
                   double sum=price*stock;
              JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
              JOptionPane.PLAIN_MESSAGE);
                   /* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
                   ,"\n","The Product Id is "+productId,"Product ID"
                        ,"\n","The Unit Price is"+unitPrice,"Unit Price"
                             ,"\n","The Units In Stock is"+unitStock,"UnitStock"
                                  ,"\n","The Product Value is"+productValue, "productValue"
                                       ,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
                                            ,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
                                                 ,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
                                                      ,"\n",JOptionPane.PLAIN_MESSAGE);*/
              //Product products[] = new Product[100];
                   products[i] = new Product();
                   products[i].setitem(item);
                   products[i].setname(name);
                   products[i].setprice(price);
                   products[i].setstock(stock);
                   products[i].setpValue(sum);
                   products[i].setreStkfee(reStkfee);
                   iValue += sum + products[i].getreStkfee();
    public void displayProductInfo()
    { /*Initialization of the variable total inventory value*/
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
              Product product = products[i];
              if(product==null)
              System.out.println(products[i]);
                   break;
         System.out.printf("product name: %s\n ", product.getname());
         System.out.printf("product ID: %s \n", product.getitem());
         System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getprice()));
         System.out.printf("units in Stock: %s \n", product.getstock());
         System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getpValue()));
         System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
         System.out.printf("Inventory Value: %s \n", iValue);
    }/*Beginning of method main*/
    public static void main(String[] args)
    {/*Message*/
         /*Means for retrieving and storing new data input into inventory program*/
    InventorySystem6 JTableImageCreator = new InventorySystem6();
    JTableImageCreator.displayProductInfo();
    JTableImageCreator.inputProductInfo();
    class Product
    /*Declaration of and default value of specified variables*/
    //private Product products[] = new Product[100];
    private String item;
    String name;
    private double stock;
    private double price;
    private double pValue;
    private double reStkfee;
    //private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
    private double iValue;
    /*method defining the get and set values of each individual variable*/
    public String getname()
    {/*Mean for storing and retrieving input of name*/
    return name;
    }/*Means for setting the product name*/
    public void setname(String name)
    {/*null pointer argument exception defining metod for obtainng product name*/
    this.name = name;
    }/*Means for getting the units identifcation number inputted by the user*/
    public String getitem()
    {/*Means for returning the user input*/
    return item;
    }/*Means for setting the units identifcation */
    public void setitem(String item)
    {/*null pointer argument exception for setting the product identification number*/
    this.item = item;
    }/*Means for getting the units value input*/
    public double getstock()
    {/*Means for returning the variable of the units*/
    return stock;
    }/*Means for setting the units value*/
    public void setstock(double stock)
    this.stock = stock;
    public double getprice()
    {/*Means for returning the dollar value of the price of the unit(s)*/
    return price;
    }/*Means for setting and requesting user to input + dollar amt*/
    public void setprice(double price)
    this.price = price ;
    }/*Means for setting the value of the total product value*/
    public void setpValue(double pValue)
    this.pValue = pValue+(price*stock);
    }/*Means for getting the value of the product*/
    public double getpValue()
    {/*Means for returning the value*/
         return pValue;
    }/*Means for getting the TtlInventoryValue of products entered*/
    public void setiValue(double iValue)
    {/*Condition Statement*/
              this.iValue=iValue;
    public double getiValue()
              return iValue;
    public void setreStkfee(double reStkfee)
         this.reStkfee=stock*price*1.05;
    /*Means for setting restockin fee of the total products*/
    public double getreStkfee()
    {/*Means for calculating the restocking fee of each products units nStock*/
                   return reStkfee;
    }/*Method for string the elements in [i] for display*/
    public String toString()
         {/*Means for returning defined string of elements in [i]*/
              return "Product{" +
    "item="+ item +
    ", name="+ name +
    ", stock="+ stock +
    ", price="+price +
    ", pValue="+pValue +
    ", reStkfee="+ reStkfee +
    ", iValue="+iValue+     
    }/*End set and get method*/
    }/*End of class Product*/
    /*Delcaration of the class type sortproductNames*/                    
    class sortproductNames extends Product
    {/*Declaration of the variable productName*/
    protected String name;
    /*Means for setting and getting values of the variable productName*/
    public void setname(String name)
    this.name = name;
    public String getname()
    return name;
    public int compareTo(Object object)
    { // for sorting by product name
    Product anotherProduct = (Product) object;
    return name.compareTo( anotherProduct.name);
                   g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
              else;
                   g.drawString("O2K", 10,10);
    * @(#)InventoryGUIFrame.java
    * @author
    * @version 1.00 2008/2/2
    package components;
    import java.io.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.imagio.*;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import javax.swing.ImageIcon;
    import javax.swing.event.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.text.*;
    import java.awt.*;
    * FormattedTextFieldDemo.java requires no other files.
    * It implements a mortgage calculator that uses four
    * JFormattedTextFields.
    public class InventoryGUIPanelFrameTextArea extends JFrame
    String productName;
    String itemNumber;
    double unitPrice;
    double unitStock;
    //Labels to identify the fields
    private JLabel productNamelabel;
    private JLabel itemNumberlabel;
    private JLabel unitPricelabel;
    private JLabel unitStocklabel;
    //Fields for data Entry     
    private JTextField productNameField;
    private JTextField itemNumberField;
    private JTextField unitPriceField;
    private     JTextField unitStockField;
    private Product[] products;
    private int unitStock;
    private int currentIndex=0;
    //Adding the JButtons
    JButton firstButton;
    JButton nextButton;
    JButton previousButton;
    JButton searchButton;
    JButton addButton;
    JButton deleteButton;
    JButton saveButton;
    //Constructor          
    public InventoryGUIPanelFrameTextArea()
    super("Welcome To The Inventory Program");
    this.products = products;
    this.numOfProducts = products;
    JFrame JPanel = new JFrame();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setLayout(new GridLayout());
    showLogo();
    showLabels();
    showInputFields();
    showButtons();
    public void showLogo()
    O2K myLogo = new O2K();
    this.add(myLogo);
    public void showLabels()
    JPanel panel = new JPanel();
    panel.add(new JLabel("PRODUCT NAME"));
    panel.add(new JLabel("ITEM NUMBER"));
    panel.add(new JLabel("UNIT PRICE"));
    panel.add(new JLabel("UNITS IN STOCK"));
    this.add(panel);
    public void showInputFields()
    itemNumber =new JTextField(5);
    itemNumber.setEditable(false);
    productName= new JTextField(10);
    productName.setEditable(false);
    unitPrice= new JTextField(5);
    unitPrice.setEditable(false);
    unitStock = new JTextField(10);
    unitStock.setEditable(false);
    panel.setEditable(false);
    panel.add(itemNumber);
    panel.add(productName);
    panel.add(unitPrice);
    panel.add(unitStock);
    this.add(panel);
    public void showButtons()
    JPanel panel = new JPanel();
    first = new JButton("First");
    next = new JButton("Next");
    previous = new JButton("Previous");
    add = new JButton ("Add");
    delete = new JButton ("Delete");
    search = new JButton ("Search");
    save = new JButton ("Save");
    panel.add(first);
    panel.add(next);
    panel.add(previous);
    panel.add(add);
    panel.add(delete);
    panel.add(search);
    panel.add(save);
    panel.add(this);
    ButtonActionHandler handler = new ButtonActionHandler();
    first.addActionListener(handler);
    next.addActionListener(handler);
    previous.addActionListener(handler);
    add.addActionListener(handler);
    delete.addActionListener(handler);
    search.addActionListener(handler);
    save.addActinListener(handler);
    this.add(panel);
    setFields(0);
    protected void paintComponent (Graphics g)
    public void setFields(int i)
    setItemNumber(i);
    setProductName(i);
    setUnitPrice(i);
    setUnitStock(i);
    public void setItemNumber( int i)
    itemNumber.setText(products[i].getItemNumber());
    public void setProductName(int i)
    productname.setText(products[i].getProductName());
    public void setUnitPrice( int i)
    unitPrice.setText(String.valueOf(products[i].getunitPrice()));
    public void setUnitStock(int i)
    unitStock.setText(String.valueOf(products[i].getunitStock()));
    private class ButtonActionHandler implements ActionListener
    public void actionPerformed(ActionEvent event)
    if(event.getSource()==first)
    currentIndex=0;
    setFields(currentIndex);
    else if(event.getSource()==next)
    currentIndex++;
    if(currentIndex==unitStock);
    currentIndex--;
    setFields(currentIndex);
    else if (event.getSource()==previous)
    currentIndex--;
    if(curentIndex < 0)
    currentIndex=0;
    setFields(currentIndex);
    else if(event.getSource()==last)
    currentIndex = unitStock -1;
    setFields(currentIndex);
    else if(event.getSource()==add)
    currentIndex = productName ++;
    setFields(currentIndex);
    else if(event.getSource()==delete)
    currentIndex= productName -1;
    setFields(currentIndex);
    else if (event.getSource()==search)
    currentIndex=productName ++;
    setFields(currentIndex);
    else if (event.getSource()==save)
    currentIndex=productName ++;
    setFields(currentIndex);
    public static void main(String args[])
    JFrame mainFrame = new JFrame();
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(400,300);
    mainFrame.setVisible(true);
    class InventorySystem6
    {     /*Declaration of products[] and the maximum storing capacity*/
    private Product products[] = new Product[MAX_NUM_OF_PRODUCTS];
    /*Prompts user to make another selection or exit program*/
    private static final String STOP_COMMAND = "stop";
         /*parameters defining maximun numbers of products available for storing in [i]*/
    private static final int MAX_NUM_OF_PRODUCTS = 100;
    /*Declaration of the variables */
    String name;
    String item;
    double stock;
    double price;
    double reStkfee=1.05;
    double pValue;
    double iValue;
    public InventorySystem6()
         /*Empty Constructor*/
    }/*Beginning of product input by the user*/
    public void inputProductInfo()
    {     /*Declaration of currency format*/     
                   DecimalFormat Currency = new DecimalFormat();
                   Scanner input = new Scanner(System.in);
                   /*Beginning of the Loop*/
                   JOptionPane.showMessageDialog(null,"Welcome to the Inventory Program\n","Welcome to the Inventory Program\n",
                   JOptionPane.PLAIN_MESSAGE);               
                   for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
                   name = JOptionPane.showInputDialog( "What is the Product Name? ");
                   if(name.equalsIgnoreCase("stop"))
                   break;
         String item = JOptionPane.showInputDialog("Enter the products ID");
         String priceStr =JOptionPane.showInputDialog("Enter the products price");
         double price=Double.parseDouble(priceStr);
                   String stockStr=JOptionPane.showInputDialog("Enter the units in stock " );
                   double stock = Double.parseDouble(stockStr);          
                   double sum=price*stock;
              JOptionPane.showMessageDialog(null,"The product value is:"+sum, "pValue",
              JOptionPane.PLAIN_MESSAGE);
                   /* JOptionPane.showMessageDialog(null,"The Product Name is:"+productName, "productName"
                   ,"\n","The Product Id is "+productId,"Product ID"
                        ,"\n","The Unit Price is"+unitPrice,"Unit Price"
                             ,"\n","The Units In Stock is"+unitStock,"UnitStock"
                                  ,"\n","The Product Value is"+productValue, "productValue"
                                       ,"\n","The Restocking Fee is "+reStockfee,"Restock Fee"
                                            ,"\n","The Inventory Value is"+inventoryValue,"Inventory Value"
                                                 ,"\n","The Inventory Restock Fee is"+reStockfee,"Restock Fee"
                                                      ,"\n",JOptionPane.PLAIN_MESSAGE);*/
              //Product products[] = new Product[100];
                   products[i] = new Product();
                   products[i].setItemNumber(itemNumber);
                   products[i].setPrdocutName(productName);
                   products[i].setUnitPrice(unitPrice);
                   products[i].setUnitStock(unitStock);
                   products[i].setProductValue(sum);
                   products[i].setReStkfee(reStkfee);
                   inventoryValue += sum + products[i].getreStkfee();
    public void displayProductInfo()
    { /*Initialization of the variable total inventory value*/
    NumberFormat moneyFormat = NumberFormat.getCurrencyInstance();
    for(int i = 0; i<MAX_NUM_OF_PRODUCTS ; i++)
              Product product = products[i];
              if(product==null)
              System.out.println(products[i]);
                   break;
         System.out.printf("product name: %s\n ", product.getproductName());
         System.out.printf("product ID: %s \n", product.getitemNumber());
         System.out.printf("Unit Price: %s \n", moneyFormat.format(product.getunitPrice()));
         System.out.printf("units in Stock: %s \n", product.getunitStock());
         System.out.printf("Total product Value: %s \n", moneyFormat.format(product.getproductValue()));
         System.out.printf("Restocking fee: %s \n", moneyFormat.format(product.getreStkfee()));
         System.out.printf("Inventory Value: %s \n", inventoryValue);
    }/*Beginning of method main*/
    public static void main(String[] args)
    {/*Message*/
         /*Means for retrieving and storing new data input into inventory program*/
    InventorySystem6 JTableImageCreator = new InventorySystem6();
    JTableImageCreator.displayProductInfo();
    JTableImageCreator.inputProductInfo();
    class Product
    /*Declaration of and default value of specified variables*/
    //private Product products[] = new Product[100];
    protected String itemNumber;
    protected String prodcutname;
    protected double unitStock;
    protected double unitPrice;
    protected double productValue;
    protected double reStkfee;
    protected double inventoryValue;
    //private String productNames[] = new String[1000]; //declaration of array "productNames" to store Product Names
    /*method defining the get and set values of each individual variable*/
    public String getproductName()
    {/*Mean for storing and retrieving input of name*/
    return productName;
    }/*Means for setting the product name*/
    public void setProductName(String productName)
    {/*null pointer argument exception defining metod for obtainng product name*/
    this.productName = ProductName;
    }/*Means for getting the units identifcation number inputted by the user*/
    public String getitemNumber()
    {/*Means for returning the user input*/
    return itemNumber;
    }/*Means for setting the units identifcation */
    public void setItemNumber(String itemNumber)
    {/*null pointer argument exception for setting the product identification number*/
    this.itemNumber = itemNumber;
    }/*Means for getting the units value input*/
    public double getunitStock()
    {/*Means for returning the variable of the units*/
    return unitStock;
    }/*Means for setting the units value*/
    public void setUnitStock(double unitStock)
    this.unitStock = unitStock;
    public double getunitPrice()
    {/*Means for returning the dollar value of the price of the unit(s)*/
    return unitPrice;
    }/*Means for setting and requesting user to input + dollar amt*/
    public void setUnitPrice(double unitPrice)
    this.unitPrice = unitPrice ;
    }/*Means for setting the value of the total product value*/
    public void setProductValue(double prodcutValue)
    this.prodcutValue = unitPrice*unitStock;
    }/*Means for getting the value of the product*/
    public double getproductValue()
    {/*Means for returning the value*/
         return productValue;
    }/*Means for getting the TtlInventoryValue of products entered*/
    public void setInvetnoryValue(double invetnoryValue)
    {/*Condition Statement*/
              this.inventoryValue=inventoryValue;
    public double getinvetotyValue()
              return productValue;
    public void setReStkfee(double reStkfee)
         this.reStkfee=stock*price*1.05;
    /*Means for setting restockin fee of the total products*/
    public double getreStkfee()
    {/*Means for calculating the restocking fee of each products units nStock*/
                   return reStkfee;
    }/*Method for string the elements in [i] for display*/
    public String toString()
         {/*Means for returning defined string of elements in [i]*/
              return "Product{" +
    "itemNumber="+ itemNumber +
    ", productName="+ productName +
    ", unitStock="+ unitStock +
    ", unitPrice="+unitPrice +
    ", productValue="+prodcutValue +
    ", reStkfee="+ reStkfee +
    ", inventoryValue="+inventoryValue+     
    }/*End set and get method*/
    }/*End of class Product*/
    /*Delcaration of the class type sortproductNames*/                    
    class sortproductNames extends Product
    {/*Declaration of the variable productName*/
    protected String name;
    /*Means for setting and getting values of the variable productName*/
    public void setProdcutName(String productName)
    this.productName = productName;
    public String getproductName()
    return productName;
    public int compareTo(Object object)
    { // for sorting by product name
    Product anotherProduct = (Product) object;
    return productName.compareTo( anotherProduct.productName);
         class myGraphics extends component          
              private BufferedImage image;
              private boolean imageFound = true;
              public myGraphics()
                   super();
                   try
                        image=ImageIO.read(new File("Logo.jpg"));
                   catch(IOException x)
                        x.printStackTrace();
                        imageFound = false;
              public void paint(Graphics g)
                   g.drawImage(image,0,0,200,50,0,0,image.getWidth(null), image.getHeight(null),null);
              else;
                   g.drawString("O2K", 10,10);

  • Problem with affinetransformOp method...

    I have a serious problem with filter method
    I Want to make a image flipping or some other filtering by using
    AffineTransformOp
    but it printouts an erro like this
    cannot resolve symbol
    op.filter (img, flipped)
    (the error pointer shows ".after the op")
    a code from my one of the filters
    BufferedImage flipped = new BufferedImage(img.getHeight(), img.getWidth(),BufferedImage.TYPE_INT_RGB);
    AffineTransform trans = new AffineTransform(0, 1, 1, 0, 0, 0);
    AffineTransformOp op = new AffineTransformOp(trans, AffineTransformOp.TYPE_NEAREST_NEIGHBOR);
    op.filter(img, flipped); //img is my buffered image source
    I used some other ways like (img, null) but always give out error.
    thanks..

    Did you declare "img" as BufferedImage or something else?
    What is the full error message?

  • Problem With BufferImage.

    Hi!
    I have a problem with creating a bufferimage. It compiles just fine but when I run it I get a NullPointerException... Can anyone tell my why and what I shall do to make it work?
    public class Meadow extends JFrame{
         private MediaTracker tracker;
         private Toolkit toolkit;
         private Dimension screenSize;
         private Image bufferImage;
         private Graphics bufferGraphics;
         private ImageIcon meadowIcon;
         private Image meadowImage;
         private ImageIcon sentinelIcon;
         private Image sentinelImage;
              private Container contentPane;
              private Graphics graphics;
    public Meadow(){
         tracker = new MediaTracker(this);
         toolkit = getToolkit();
         screenSize = toolkit.getScreenSize();
         bufferImage = createImage(screenSize.width, screenSize.height);
         tracker.addImage(bufferImage, 0);
              try{
                   tracker.waitForID(0);
              }//end try
              catch (InterruptedException e){
                   return;
              }//end catch
              if(tracker.statusID(0, false) == MediaTracker.COMPLETE){
    nullpointer--->          bufferGraphics = bufferImage.getGraphics();
              }//end if
         meadowIcon = new ImageIcon("meadow.gif");
         meadowImage = meadowIcon.getImage();
    sentinelIcon = new ImageIcon("Grapghic/Sentinel/sentinel_0.gif");
    sentinelImage = sentinelIcon.getImage();
         setBounds(0, 0, screenSize.width, screenSize.height);
         getContentPane().setLayout(null);
         setUndecorated(true);
         setResizable(false);
         setVisible(true);
         graphics = getContentPane().getGraphics();
         drawScreen();
    }//end constructor Meadow
    }//end class Meadow
    Gratefull for any answers I can get!
    //John

    ok... Im getting closer to the root of the problem... But I could still use some help...
    bufferImage = createImage(screenSize.width, screenSize.height);
    if (bufferImage == null){
    System.out.println("crap");
    bufferGraphics = bufferImage.getGraphics(); <---This gives a nullpointer
    Ok... The above lines givs a nullpointer but just before it does, "crap" is printed... I,we read that createImage returns null if graphicEnviroment.isHeadless returns true... And if I get everything right that meens that the graphic eniroment doesn't support the image I'm trying to create...
    Am I way off here or have I got it right? And if it is that way, how can I make the graphicEnviroment support my image?
    I appreciate all help I can get!
    //John
    ps Thanx Nelo! Your replie helped me with another problem I've been struggling with! ds

  • Problem with Transparency using PixelGrabbar.

    Well, im having a problem.
    Im creating a basic 2d game and using images, since im using alot of images and they are being drawn alot i use a class i call "GameSprite", basically it retrieves the file needed and then keeps it in a pixel array, but transparency dosn't seem to work with it. The reason im using this is because say i have 100 images to draw, it dosn't need to keep using the drawImage method because it draws all at once using a set drawing area on which the pixel arrays are possitioned, for example this is the drawing;
    public void drawGraphics(int xOffset, Graphics g, int yOffset)
            setImageConsumer();
            g.drawImage(drawingAreaImage, xOffset, yOffset, this);
    .private synchronized void setImageConsumer()
            if(imageConsumer != null)
                imageConsumer.setPixels(0, 0, drawingAreaHeight, drawingAreaWidth, colorModel, drawingAreaSize, 0, drawingAreaHeight);
                imageConsumer.imageComplete(2);
        }Here is the basic's of what it does, note i used URL just for a test if you wanted to test (image still is uploaded there);
    Image image = Toolkit.getDefaultToolkit().createImage(new URL("http://i166.photobucket.com/albums/u116/the_owner2007/testtrans.png"));
              image = setTransparency(image, new Color(255, 89, 255));
              ImageIcon icon = new ImageIcon(image);
              imageWidth = icon.getIconWidth();
              imageHeight = icon.getIconHeight();
              imagePixels = new int[imageWidth * imageHeight];
              PixelGrabber pixelgrabber = new PixelGrabber(image, 0, 0, imageWidth, imageHeight, imagePixels, 0, imageWidth);
                 pixelgrabber.grabPixels();If i use for example a JLabel and set an ImageIcon as the image the transparency works, otherwise i can't figure it out.
    Here is the setTransparency method;
    public static Image setTransparency(Image im, Color color) {
            //the color to make transparent
            final int markerRGB = color.getRGB() & 0x00FFFFFF;
            ImageFilter filter = new RGBImageFilter() {
                public int filterRGB(int x, int y, int rgb) {
                    if ((rgb & 0x00FFFFFF) == markerRGB) {
                        return markerRGB;
                    } else {
                        return rgb;
            ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
            return java.awt.Toolkit.getDefaultToolkit().createImage(ip);
    If you can think of an alternative solution which would work better and possibly more efficiant please feel free to post that.
    Thanks.

    drawingAreaImage = component.createImage(this);Note that images created through this method are often times immutable. They will not respond to changes in the underlying ImageProducer. So "drawingAreaImage" is essentially a snapshot of whatever pixels "this" gave it.
    An exception to this rule is if you use MemoryImageSource and set the animated flag,
    int[] pixels = ....
    MemoryImageSource imageProducer = ....
    imageProducer.setAnimated(true);
    drawingAreaImage = component.createImage(imageProducer);This time, whenever pixels is modified you can call imageProducer.newPixels() and the image will be updated.
    On a side note, you are using a very old method of dealing with images (over a decade old since java 1.0 and 1.1). Are you doing this for compatability purposes? I would recommend you drop the ImageProducer/Consumer model entirely and stick with BufferedImages (which as been around since 1.2 and was the "upgrade" from the ImageProducer/Consumer model).

  • Problem with loading image to Applet.

    Hello. Im preety new to Java, and currently ive got problems with adding an image to my applet. I tried to make game, similar to Mario - a platform based one. I found a source code of something close to that, and wanted to test but i couldnt get images loading. Here's the code :
    Main class :
    package pl.wat.edu;
    import java.applet.*;
    import java.awt.*;
    public class Main extends Applet implements Runnable{
         Thread th;
         private final int speed = 15;
         private Level obecny_poziom;
         private Image dbImage;
         private Graphics dbg;
         MediaTracker mt = new MediaTracker(this);
         private Image ziemia1;
         @Override
         public void destroy() {
              // TODO Auto-generated method stub
              super.destroy();
         @Override
         public void init() {
              // TODO Auto-generated method stub
              super.init();
              setSize(stale.wielkosc_apletu_szerokosc, stale.wielkosc_apletu_wysokosc);
              //setBackground(Color.blue);
              //ziemia1 = getImage(getCodeBase(), "g1.GIF");
              obecny_poziom = new Pierwszy(this, this);
         @Override
         public void start() {
              // TODO Auto-generated method stub
              super.start();
              // create new thread
              th = new Thread (this);
              // start thread
              th.start ();
         @Override
         public void stop() {
              // TODO Auto-generated method stub
              super.stop();
              // Thread stop
              th.stop();
              th = null;
         public void run() {
              // TODO Auto-generated method stub
              while (true){
                   repaint();
                   try
                        Thread.sleep(speed);
                   catch (InterruptedException ex)
                   // do nothing
         @Override
         public void paint(Graphics arg0) {
              // TODO Auto-generated method stub
              super.paint(arg0);
              //arg0.drawImage(ziemia1,10,10,this);
              obecny_poziom.paintLevel(arg0);
         public void update (Graphics g)
              if (dbImage == null)
                   dbImage = createImage (this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics ();
              dbg.setColor (getBackground ());
              dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
              dbg.setColor (getForeground());
              paint(dbg);
              g.drawImage (dbImage, 0, 0, this);
    }and Level class that have draw levels from String rows :
    package pl.wat.edu;
    import java.applet.Applet;
    import java.awt.*;
    public abstract class Level {
         //private LevelElement [] elements;
         private WorldTile [] tiles;
         private WorldTile[][] tablica_kolizji;
         private Color [] colors;
         private Component parent;
         private int lewa_granica;
         private int prawa_granica;
         private int dlugosclevelu;
         private Image ziemia = null;
         private Image titi;
         private Applet applet;
         public abstract void resetLevel();
         public Level(Component parent, Applet applet) {
              super();
              this.parent = parent;
              this.applet = applet;
              ziemia = applet.getImage(applet.getCodeBase(), "g1.GIF");
         public void initializeLevel(String [] definitions){
              tablica_kolizji = new WorldTile [stale.dlugosclevela] [definitions[0].length()];
              lewa_granica = 0;
              prawa_granica = stale.wielkosc_apletu_szerokosc;
              int licznik_kratek = 0;
              for(int i=0; i<definitions.length; i++){
                   char [] definition_line = definitions.toCharArray();
                   for(int j=0; j<definition_line.length; j++){
                        if (definition_line[j] == ':')
                             tablica_kolizji[i][j] = null;
                        else if (definition_line[j]== 'g'){
                             Ziemia tile = new Ziemia(j*stale.szerokoscTile, i*stale.wysokoscTile, stale.ziemia_id, ziemia, parent);
                             tablica_kolizji[i][j] = tile;
                             licznik_kratek = 0;
              tiles = new WorldTile [licznik_kratek];
              int licznik = 0;
              for (int i = 0; i<tablica_kolizji.length; i++){
                   for(int j=0; j>tablica_kolizji[i].length; j++){
                        if (tablica_kolizji[i][j] != null){
                             tiles[licznik] = tablica_kolizji[i][j];
                             licznik++;
         public void paintLevel(Graphics g)
              try
                   // draw background
                   // draw all elements in elements array
                   for(int i=0; i<tiles.length; i++)
                        tiles[i].rysujTile(g);
              catch(Exception ex)
                   // do nothing
    Any ideas why this Image doesnt show up ?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    michali7x4s1 wrote:
    Thats a code i found somewhere, tried to check how some things work.Have you used exceptions before? If not, please read the sun tutorial on them as they are very very important. Also, whether this is your code or someone else's doesn't matter as it's yours now, and you would be best served by never throwing out exceptions as is done in this code. It's like driving with a blindfold on and then wondering why you struck the tree. It's always best to go through the tutorials to understand code before using it. If it were my project, I'd do it in Swing, not AWT. Fortunately Sun has a great tutorial on how to code in Swing, and I suggest you head there as well. Best of luck.

  • Problem with session while sending a multipart-form (a file via post)

    I have a problem with the communication between my applet and my server. I use a method to post an xml to my server with the Content-Type "application/x-www-form-urlencoded" and with it I'm not having any problem to preserve the session.
    However I use another method I found in the forums to post files and try to adapt it, but I'm being send from the server to the login page because it's not recognizing my session
    Can anybody help me? This is my method
    public String uploadFile(String adr, BufferedImage img) {
            String res = "";
            String CONTENT_BOUNDARY = "--abvx98734732";
            String s;
            File f = null;
            URL url;
            URLConnection conn;
            try {
                url = new URL(adr);
                conn = url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data; boundary=" + CONTENT_BOUNDARY);
                conn.setRequestProperty("file-Name", "process_image.jpg");
                DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
                wr
                        .write(("--"
                                + CONTENT_BOUNDARY
                                + "\r\n"
                                + "Content-Disposition: form-data; name=\"fileData\"; filename=\""
                                + "process_image.jpg" + "\"\r\nContent-Type: image/jpg\r\n\r\n")
                                .getBytes());
                ImageIO.write(img, "jpg", wr);
                wr.write(("\r\n--" + CONTENT_BOUNDARY + "--\r\n").getBytes());
                wr.flush();
                BufferedReader in = new BufferedReader(new InputStreamReader(conn
                        .getInputStream()));
                while ((s = in.readLine()) != null) {
                    res += s;
                in.close();
            catch (MalformedURLException muo) {
                muo.printStackTrace();
            catch (IOException io) {
                io.printStackTrace();
            return res;
        }This is how I preserve session in my other method:
    private static final String SESSION_KEY = "_session_id";
    URLEncoder.encode(SESSION_KEY, "UTF-8") + "=" +
    URLEncoder.encode(sessionId, "UTF-8");
    wr.writeBytes(content);
    ....

    Yes, the only way is to pass the value u want in the query string. But make sure that the value is not too large.
    In case you have too much info i guess the only way is to circumvent multipart and handle the process in your own custom class, which wont be worth the effort if u need pass only 2-3 small parameters.
    Always,
    Leo.
    Hi,
    Before I upload a file, I want to get a few parameter
    values (getParameter) on the form first. I've tried
    using com.oreilly.servlet MultipartRequest and a few
    other free servlets but they require that the file
    must to be uploaded first. For example:
    MultipartRequest multi = new
    MultipartRequest(request,filepath, 10*1024*1024);
    //this will instantiate the object and upload the
    file
    String command = multi.getParameter("command"); //get
    the form parameter
    Is there any way I can get the parameter first before
    uploading the file? I truly appreciate any helps you
    can provide me.
    Regards,
    Lily

Maybe you are looking for

  • Is there a way to import music from my windows media player, if so how?

    Is there a way to import music from my windows media player, if so how?

  • GP: How to wait a specific number of days?

    Hello everybody, I am searching for an idea how to create a step in my Guided Procedures process which waits until a specific day (or a number of days from it's start). I have thought about implementing a Java Callable Object which waits until comple

  • Time Machine will not start (code -43)

    After getting a new 1TB external usb drive and changing format for use with time machine the program no longer launches producing unexpected error (code -43) instead. I had hoped to have three of four partitions on this drive for use with old windows

  • Trading Scenario in SAP

    Hi all, I am working for a project where there is total trading scenarios. No manufacturing at all. But the scenario is like when the PO is received from the customer then only all the procurement process begins: 1. Sales order Created & requirements

  • How to stop the message - "You have not signed up for a data plan..."?

    Just purchase iPad2 3G I keep receiving the "nag" to sign up for a data plan. How can I stop this from apppearig without signing up? Just not ready to sign up - I know that might seem strange but I have reasons... Thx