AWT equivalent of image JLabels

I'm trying to rewrite some Swing code in AWT. It displays some images by using JLabels constructed with ImageIcons, and then uses the setVisible method to turn them on and off during the running of the program.
Can anyone point me towards the easiest way of doing this in AWT?

I'm trying to rewrite some Swing code in AWT. It
displays some images by using JLabels constructed with
ImageIcons, and then uses the setVisible method toFirst problem: ImageIcon is swing
You need to use plain java.awt.Image
Create a new component that extends component, override it's paint method, and in there paint the label and the image to the Graphics object

Similar Messages

  • Converting awt to JAI image - please help!

    My application needs to be able to create a JAI image and apply dither to it.
    I got this working by using the fileload operator in JAI to load the image and convert it to a planar image but when I try to use the awtImage operator to convert the images to planar images it doesn't work.
    I really don't understand why this is. The two methods are pratically identical.
    This is the method that works and the error diffusion method
    public void setDitherOp(String op, String picName,KernelJAI typeDither)
                          //operation name, parameter block
        srcImg = JAI.create("fileload", "Pics/"+picName);
        dataType = srcImg.getSampleModel().getDataType();
                  //contains parameters to be used in dither operation
        pb = new ParameterBlock();
        pb.addSource(srcImg);
        layout = new ImageLayout();
        if(op=="ordered")
          orderedDither();
        else if(op=="error")
          errorDiffDither(typeDither);
    public void errorDiffDither(KernelJAI typeDither)
          if(srcImg.getNumBands()==1)   //source image has one color band
            LookupTableJAI lut =new LookupTableJAI(new byte[] {(byte)0x00, (byte)0xff});
            pb.add(lut);
            pb.add(typeDither);
            byte[] map = new byte[] {(byte)0x00, (byte)0xff};
            ColorModel cm = new IndexColorModel(1, 2, map, map, map);
            layout.setColorModel(cm);
          else if(srcImg.getNumBands()==3)  //source image has three color bands
            pb.add(ColorCube.BYTE_496);  //add color cube to parameter block
            pb.add(typeDither);          //add error filter kernel
            System.out.println("error diffusion num bands is: "+srcImg.getNumBands());
          RenderingHints rhints = new RenderingHints(JAI.KEY_IMAGE_LAYOUT, layout);
          ditheredImage = JAI.create("errordiffusion", pb, rhints);
          if(ditheredImage==null)System.out.println("Dithered image is NULL");
    This is the one that doesn't!
    public void setDitherOp(String op, Image frameImage,KernelJAI typeDither)
        srcImg = JAI.create("AWTImage", frameImage);
        dataType = srcImg.getSampleModel().getDataType();
                  //contains parameters to be used in dither operation
        pb = new ParameterBlock();
        pb.addSource(srcImg);
        if(srcImg==null)System.out.println("src image null in set dither op");
        /*if(srcImg!=null)
            ditheredImage = JAI.create("Invert", pb);
        layout = new ImageLayout();
        if(op=="ordered")
          orderedDither();
        else if(op=="error")
          errorDiffDither(typeDither);
    public PlanarImage getDitheredImage()
        return ditheredImage;
      }The other really odd thing in the method that uses the awtImage operator is this:
    if the code to invert the colours is executed it works fine. This must mean that it is creating the planar image from the awt image? I really don't see what the problem could be in that case because it uses the same error diffusion method after that.
    Please help me with this - its part of a project thats due up in a few days and I really need to get this part working as soon as possible.
    CurtinR

    Hi morgair,
    Thank you so much for answering!!
    You're right - the FileLoad and awtImage operators return different types of objects.
    FileLoad returns a RenderedImage
    JAI.create("fileload", "Pics/"+picName);awtImage returns a PlanarImage. The sample model and color model are set according to the AWT image data.
    srcImg = (PlanarImage)JAI.create("AWTImage", pbAwtOp);Also the error diffusion operation takes a renderedImage as a parameter. It says in the programming guide that the source image and the color map must have the same data type and number of bands. (That would explain why the method using fileLoad worked!)
    How do I change the Planar image to a rendered imaage or specify the sample model and colour model of srcImg. I've been trying to do this but am going round in circles - there are descrepancies between the programmers guide and the API and I'm lost..
    Any suggestions really really appreciated..

  • CC equivalent to Image adjustments variations

    Is there an Photoshop CC equivalent to the Image > Adjustments > Variations tool available in earlier versions?

    Variations Plug-in is in Photoshop CC Adobe seems to have removed it from CC 2014.  However when I copied then cc variations plug-in into my Photoshop Plugin tree which  I link into all versions of Photoshop plug-in tree.  When I use CC 2014 the variation plun-in seems to work so I don't know why Adobe removed it from CC 2014 the support needed seems to still be there.  Right click on image and click view the link in a new tab or window.  You can scale it and read it then.

  • Saveing contents of awt panel to image file in headless enviroment

    Hi im trying create a program that will generate a graph in the form of a PNG file however it must be run in a headless enviroment as its going to be run on a server as part of a larger chain of applications
    for graph generation im useing Jgraph2d an opensource libery
    the problem im haveing is that the image it produces is blank the program does seem to be drawing something but just a small clump of seemingly random white pixels any help would be apprechiated
    p.s. been copy pasteing alot of example code back and forth so please ignore some of the slighly random seeming comments.
        public static void main(String[]args){
            System.getProperties().setProperty("java.awt.headless", "true");
            Toolkit tk = Toolkit.getDefaultToolkit();
            GraphicsEnvironment ge =
                    GraphicsEnvironment.getLocalGraphicsEnvironment();
            System.out.println("Headless mode: " + ge.isHeadless());
            int width = 800;
            int height = 600;
            // Create a chart:
            Chart2D chart = new Chart2D();
            // Create an ITrace:
            ITrace2D trace = new Trace2DSimple();
            trace.setTracePainter$30c0137f(new TracePainterDisc());
            // Add all points, as it is static:
            Random random = new Random();
            for(int i=100;i>=0;i--){
                trace.addPoint(i,random.nextDouble()*10.0+i);
            // Add the trace to the chart:
            chart.addTrace(trace);
            chart.setSize(width,height);
            // add the chart to the frame:
            Panel panel = null;
            // Create an unshown frame
            panel = new Panel();
            panel.addNotify();
            panel.add(chart);
                    panel.setSize(width,height);
            BufferedImage awtImage = new BufferedImage(panel.getWidth(),panel.getHeight(),BufferedImage.TYPE_INT_RGB);
            Graphics g = awtImage.getGraphics();
            panel.printAll(g);
            try {
                File saveto = new File("e:/graph.png");
                ImageIO.write(awtImage, "png", saveto);
            } catch (Exception e) {
                e.printStackTrace();
        }

    Try hiding the panels first then adding them then show. I know its crazy but I have gotten better performance this way with 1.4.1x. Try it.
    current.setVisible(false);
    contentPanel.add(current);
    current.setVisible(false);

  • JLabel (icon Image) without picture?

    I am make applet containing JLabel (Icon Image). When I run this applet from server and used image-file "middle.gif" (from tutorial) - there was all Ok. After this I changed color of image on MS Photo Editor and now I get JLabel without icon and there is no errors. I don't understand what happens? Anybody know what is it?

    Of course. In directory "Images" I have follow files:
    green.gif
    middle.gif
    red.gif
    Files green.gif and red.gif are middle.gif but pictures on them have respective colors. This colors I get using MS Photo Editor.
    import javax.swing.*;
    import java.awt.*;
    import java.net.*;
    public class tLabImage extends JApplet{
    public void init () {
    JFrame f=new JFrame();
    URL url=null;
    try {
    // url=new URL("http://10.1.1.6/Images/middle-1.gif");
    url=new URL("http://10.1.1.6/Images/green.gif");
    catch (MalformedURLException e) {System.out.println (e.getMessage());}
    Image image=getImage(url);
    ImageIcon icon=new ImageIcon(image);
    JLabel l=new JLabel ("text", icon, JLabel.LEFT);
    f.setLocation(200,300);
    f.getContentPane().setLayout(new GridLayout(0,2));
    f.getContentPane().add(l);
    f.pack();
    f.setVisible(true);
    When I run this programm I get JLabel without icon (only text). Why? Who can answer?

  • Image Processing without AWT

    Hi everyone,
    Are there any libraries out there for image processing on J2ME devices? The device I am working on is JStamp, so it has not UI. Therefore no AWT. All image processing libraries seem to be based on AWT.
    When I try to upload Java classes using AWT, JStamp upload gives error, because there are native JNI methods in AWT.
    Thanks,

    Hi,
    I'm not quite sure what you are asking. What "image processing" could you possibly do on a system without a GUI? If you just mean storing or tranporting image files then you can treat it in the same way as any other data. If the system has no graphical ability then you obviously will not be able to display images (although I have seen an app once that converted a GIF into an ASCII art text file...)
    Please be more specific.
    Ben

  • Need help in displaying an Image in a JLabel

    Hi everyone,
    I am using a JLabel to display images on a particular screen. I am facing some problem while doing so..
    On my screen there are images of some garments. When the users select colors from a particular list, i should color this garment images and load it on the screen again with the colors. I have a floodfill class for filling the colors in the images. The problem I am facing is I am able to color the image properly with my floodfill class but when displaying the image on the same jlabel, the image gets distorted somehow.
    Everytime I color the image, I create an ImageIcon of the image and use the seticon method from the JLabel class. First I set the icon to null and then set it to the imageicon created. here is the code I use.
    If 'image' is the the image i have to load
    ImageIcon imgicon = new ImageIcon(image);
    jlabel.setIcon(null);
    jlabel.setIcon(imgicon);I am setting the icon to null because I have not found any other method to clear the previous image from the jlabel.
    Can anyone who has worked on images before and faced a similar situation help me with this?? Is there some other container I can use besides the JLabel to display the images perhaps?
    Thanks in advance.....
    Bharat

    And the thing is when I first go into that screen with the selected colors it is displaying the images perfectly.
    It is only giving problems when I pick different colors on the screenit really sounds like the problem is in your floodfill class.
    I have no idea what's in floodfill, but if you were e.g. using a JPanel and paintComponent,
    you would need to have as the first line in paintComponent()
    super.paintComponent(..);
    to clear the previous painting.
    if not, you would be just drawing over the top of the previous paintComponent(), and if the calculation of the
    painting area is not 100% exact, you may get the odd pixel not painted-over, meaning those pixels will display
    the old color.

  • Image (jpeg, gif) display in AWT layout manager

    Goodmorning All,
    I am looking for some help, a hint on my AWT Layout challenge i have.
    Example GUI_1:
    =========================
    Window border..................[_][x]..
    =========================
    [label]....|display_area|....[button].
    [label]....|display_area|....[button].
    ...............|display_area|....[button].
    ...............|display_area|....[button].
    ...............|display_area|..................
    =========================
    ...........................................[QUIT].....
    =========================
    I want to
    - display a picture in the "display area" of the this GUI
    - put labels left of it with some text
    - put a couple of buttons right of it, through which i am able to manipulate the image
    Questions:
    *1. Is it (even) possible to display an (jpeg,gif) image in the "display area" while using a layout manager?*
    Surfing over the internet...so far i only have found applet-examples that use the full gui surface of the applet to display an image via the g.drawImage (imagename, x,y); without any gui elements (labels, buttons) beside it.
    *2. What kind of AWT gui element do i need at the location of the "display area"?*
    Is is possible to use a CANVAS or do i need somethen else? (e.g. glue an image on a button)
    *3. Is is possible to display an ANIMATION (series of sequences jpeg, gifs) in the display area?*
    I already found out how to locate and load the images (via mediatracker).
    Now i need to find a way to "paint" the loaded images in the GUI.
    *4. Is this even possible with AWT layout or do i need to switch to SWING layout?*
    I have not used Swing yet, cause i'm working my way up through the oldest gui technologie first.
    *5. Do know any usefull websites, online tutorials (on awt and displaying images) that can help me tackle my challenge?*
    Thank you very much for your hints, tips and tricks

    A link as Gary pointed out is the best way to see what the problem may be.
    Did you save the image to your working folder and have you defined a site pointing to this folder.
    Defining a site helps Dreamweaver track and organize the files used in this site.
    http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14028
    If you can't see the image, this means that the path to the image is incorrect.
    Nadia
    Adobe Community Expert : Dreamweaver
    Unique CSS Templates | Tutorials | SEO Articles
    http://www.DreamweaverResources.com
    Web Design & Development
    http://www.perrelink.com.au
    http://twitter.com/nadiap

  • Setting the image size within a JFrame!

    This is the code i have implemented
    import javax.swing.*;
    import java.awt.*;
    class SampleJFrame extends JFrame
         JLabel l1;
         ImageIcon image;
         SampleJFrame()
              image=new ImageIcon("G:/java files1/images/aa.jpg");
              l1=new JLabel("DEDICATION",image,JLabel.RIGHT);
              l1.setSize(100,100);
              //this.setLayout(new FlowLayout(FlowLayout.RIGHT));
              this.add(l1);
    public class JFrame2
         public static void main(String args[])
              SampleJFrame samplejframe=new SampleJFrame();
              samplejframe.setTitle("FRAMES WITH JLABELS WITH IMAGEICON");
              samplejframe.setSize(400,400);
              samplejframe.setVisible(true);
    }When i run this the image occupies the entire JFrame.I want to resize it to a width of around 100,80 pixels.How can i do it?
    I know when i draw a image without linking to a label i can use drawImage of Graphics class to set the size of the image.But in this case i am linking the image to the JLabel and it's occupying the entire screen and the text with the JLabel is thrown somewhere out.

    Read it.Got a lot of info from that.But the trouble with mine is that i am linking the image to the JLabel and thats why i am unable to set its size because the image will be added to the JPanel when i add the JLabel to it?If i was directly printing the image i would have rather used Graphics.drawImage( ) where i can manually specify the width.

  • Problem Displaying an Image in a JScrollPane

    Hi All,
    I've placed a Toolbar at the bottom of a JFrame and above the toolbar I placed a JTabbedPane. In one of the tabs I want to display a full sized image.The size of the image that I want to display using a scroll pane is 595x842 pixels. Now the problem is that when I display the image in the scroll pane the bottom toolbar is overlapped with the scrollpane. I don't want to resize the image as it is spoiling the image quality.I used the below code
    JPanel imagepagepanel=new JPanel()
        protected void paintComponent(Graphics g)
              js=new JScrollPane();
              Point p = js.getViewport().getViewPosition();
              g.drawImage(demoicon.getImage(), p.x, p.y, null);
    mytabbedpane.addTab("View Image",js); //add the scrollpane to the tabI even tried using a label to display the image in the tabbedpane and I've got the same overlapping problem.
    I am able to embed the default browser in my application using JDIC API and the image display is fine in the browser without overlapping the bottom toolbar. But I don't want to use a web browser to display the image.
    It would be of great help if anyone could suggest a solution to the overlapping problem. I want the scroll pane to work similar to a web browser while displaying a large sized image.
    Thanks in advance.

    Override the paintComponent method to just draw the
    image at 0, 0, w, h.
    The rest is not needed, to say the least.Here's an easier way
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.awt.*;
    import java.io.File;
    import java.io.IOException;
    public class ImageInTabbedScrollTest extends JFrame {
        public ImageInTabbedScrollTest() {
            buildGUI();
        private void buildGUI() {
            JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new BorderLayout());
            JTabbedPane tabbedPane = new JTabbedPane();
            try {
                Image image = ImageIO.read(new File("images/terrain.jpg"));
                ImageIcon icon = new ImageIcon(image);
                JLabel label = new JLabel(icon);
                JPanel panel = new JPanel(new GridLayout(0,1,5,5));
                panel.add(label);
                JScrollPane jsp = new JScrollPane(panel);
                tabbedPane.addTab("Image",jsp);
                JPanel anotherPanel = new JPanel();
                JLabel label2 = new JLabel("Second Panel");
                anotherPanel.add(label2);
                 label2.setFont(new Font("San Serif",Font.BOLD, 40));
                tabbedPane.add("Label",anotherPanel);
                mainPanel.add(tabbedPane, BorderLayout.CENTER);
                JToolBar tBar = new JToolBar();
                tBar.add(new Button("OK"));
                tBar.add(new Button("Maybe"));
                tBar.add(new Button("No"));
                mainPanel.add(tBar, BorderLayout.SOUTH);
                  } catch (IOException e) {
                e.printStackTrace();
        public static void main(String[] args) {
            Runnable runnable = new Runnable() {
                public void run() {
                    ImageInTabbedScrollTest testFrame = new ImageInTabbedScrollTest();
                    testFrame.setSize(new Dimension(600,600));
                    testFrame.setLocationRelativeTo(null);
                    testFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    testFrame.setVisible(true);
            SwingUtilities.invokeLater(runnable);
    }

  • GIF images in JFrame

    hi all, i'm trying to put a gif image in JFrame. The problem is the gif images gets flickering(fluctuation) while it is placed in a frame. i had also placed some labels near the image and all of them gets disturbed becoz of this gif file in frame. plz tel me a solution.
    Thanks .
    //MY CODE
    //~~~~~~~~~~
    import java.awt.*;
    import java.awt.Color;
    import java.awt.event.*;
    import javax.swing.*;
    class Label_ON_G extends JFrame// implements MouseListener,MouseMotionListener
      private Image image;
      JLabel label1;
      JButton button1;
      Dimension dimension=Toolkit.getDefaultToolkit().getScreenSize();
      public Label_ON_G()
           super("Display image example");
           getContentPane().setBackground(Color.white);
           getContentPane().setSize(dimension);
        setResizable(true);
        getContentPane().setLayout(null);
         Toolkit tk = Toolkit.getDefaultToolkit ();
         image = tk.getImage ("singlearea.gif");
        label1= new JLabel("RADHA");
        label1.setBounds(120,110,80,30);
        label1.setEnabled(false);
        add(label1);
        button1= new JButton("VIEW LABEL");
        button1.addActionListener(new ActionListener(){
             public void actionPerformed(ActionEvent ae)
              label1.setEnabled(true);
             System.out.println("ActionPerformed");
        button1.setBounds(600,600,100,30);
        add(button1);
        setVisible(true);
        show();
    public void paint (Graphics g)
      g.drawImage(image, 100, 100, this);
      public static void main (String[] args)
      {     new Label_ON_G();     }
    }

    There is no need to do custom painting to display an image.
    [url http://java.sun.com/docs/books/tutorial/uiswing/components/label.html]How to Use Labels
    Unless you know what you are doing, never override the paint() method of the JFrame. There is no reason to do this.
    If you need to do custom painting then you override the paintComponent() method of a component that extends JComponent.

  • How can I draw on top of an image?

    I'm using a JApplet with three JPanel's inside of it.
    Inside one of those JPanel's I would like to place an image and a button. When the button is clicked, I want to draw an oval on top of the image . Each subsequent time the button is clicked, the oval will move to a different location.
    So here are my questions:
    1) What should I use to draw the image? (a JLabel with an ImageIcon on it?)
    2) Could I simply use g.drawOval() in paintComponent() to directly draw on top of the image/JLabel?
    Any help will be greatly appriciated.

    Here's a sample to study;-import java.awt.*;
    import java.awt.event.*;
    public class DrawOnImage extends java.applet.Applet{
      int xPos, yPos;
      Image img;
      public void init() {
        add(new Label("Hello World") );
        Button press = new Button("press");
        add(press);
        press.addActionListener(new ActionListener(){
          public void actionPerformed(ActionEvent e){
            xPos = (int)(Math.random()*270);
            yPos = (int)(Math.random()*170)+30;
            repaint();
        img = getImage(getDocumentBase(), "anImage.JPG");
      public void paint(Graphics g){
        g.drawImage(img,0,30,this);
        if(yPos>=30)g.fillOval(xPos, yPos, 45, 45);
    }

  • How  can I  load an  image  in a scene?

    I want to load an image in a scene and I have tried it using the
    steve morris example( HAVI example ) , I am using a STB and when I send my xlet I don�t see this imagen at the tv.
    Source code is available from
    http://www.interactivetvweb.org/resources/code/havi/HaviXlet.zip
    Somebody knows another way to do it ???

    I assume you mean a JLabel as an AWT Label cannot display an Image.
    // POINT THE IMAGE BACK TO THE SERVER FROM WHICH THE APPLET WAS DOWNLOADED
    // BY USING GETCODEBASE(). OMIT THAT AND YOU WILL SEE THAT YOU GET A SECURITY
    // EXCEPTION AS THE APPLET WILL TRY TO LOCTE THE IMAGE ON THE LOCAL MACHINE AND
    // APPLETS BY DEFAULT CANNOT ACCESS RESOURCES ON THE CLIENT
    // assumes .gif file exists in same directory as HTML running the Applet
    Image image = getImage(getCodeBase(), "ImageName.gif");
    ImageIcon icon = new ImageIcon(image);
    JLabel - new JLabel(icon);
    // check out the getScaledInstance() method of Image class to resize your image

  • My program always displays the same image, even when I change th image file

    I'm making a program that chooses an image file from a dialog, resize it and copy it into a folder. When the image is needed to be displayed, the image file is read and a JLabel displays it on screen.
    When I upload the first image, everything works fine. The problem appears when I upload another picture: the displayed image is still the first image, even when the old file doesn't exist anymore (because it has been overwritten). It looks like the image has been "cached", and no more image are loaded after the first one.
    This function takes the image picture chosen by the user, resizes it, and copy it into the pictures folder:
        private void changeProfilePicture() {
            JFileChooser jFileChooser = new JFileChooser();
            jFileChooser.setMultiSelectionEnabled(false);
            jFileChooser.setFileFilter(new ImageFileFilter());
            int result = jFileChooser.showOpenDialog(sdbFrame);
            if (JFileChooser.APPROVE_OPTION == result) {
                try {
                    //upload picture
                    File file = jFileChooser.getSelectedFile();
                    InputStream is = new BufferedInputStream(new FileInputStream(file));
                    //resize image and save
                    BufferedImage image = ImageIO.read(is);
                    BufferedImage resizedImage = resizeImage(image, 96, 96);
                    String newFileName = sdbDisplayPanel.getId() + ".png";
                    String picFolderLocation = db.getDatabaseLocation() + "/" +
                            PROFILE_PICTURE_FOLDER;
                    java.io.File dbPicFolder = new File(picFolderLocation);
                    if(!dbPicFolder.exists())  {
                        dbPicFolder.mkdir();
                    String newFilePath = picFolderLocation + "/" + newFileName;
                    File newFile = new File(newFilePath);
                    FileOutputStream fos = new FileOutputStream (newFilePath);
                    DataOutputStream dos = new DataOutputStream (fos);
                    ImageIO.write(resizedImage, "png", dos);
                    dos.close();
                    fos.close();
                    //set picture
                    sdbDisplayPanel.setImagePath(newFilePath);
                } catch (IOException ex) {
                    System.err.println("Could'nt print picture");
                }This other class actually displays the image file in a JLabel:
        public void setImagePath(String imagePath) {
            count++;
            speaker.setImagePath(imagePath);
            this.imagePath = imagePath;
            if(imagePath != null)   {
                //use uploaded picture
                try {
                    File tempFile = new File(imagePath);
                    System.out.println(tempFile.length());
                    java.net.URL imgURL = tempFile.toURI().toURL();
                    ImageIcon icon = new ImageIcon(imgURL);
                    pictureLbl.setIcon(icon);
                    // Read from a file
                } catch (IOException ex) {
                    Logger.getLogger(SDBEventClass.class.getName()).log(Level.SEVERE, null, ex);
            else    {
                //use default picture
                URL imgURL = this.getClass().getResource("/edu/usal/dia/adilo/images/noProfile.jpg");
                ImageIcon icon = new ImageIcon(imgURL, "Profile picture");
                pictureLbl.setIcon(icon);
        }

    When you flush() the image, you don't need to construct a new ImageIcon each time, a simple repaint() will suffice.
    Run this example after changing the URL to an image you can edit and update while the program is running.import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.*;
    public class FlushImage {
       Image image;
       JLabel label;
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new FlushImage().makeUI();
       public void makeUI() {
          try {
             ImageIcon icon = new ImageIcon(new URL("file:///e:/java/dot.png"));
             image = icon.getImage();
             label = new JLabel(icon);
             JButton button = new JButton("Click");
             button.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                   image.flush();
                   label.repaint();
             JFrame frame = new JFrame("");
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.add(label, BorderLayout.NORTH);
             frame.add(button, BorderLayout.SOUTH);
             frame.pack();
             frame.setLocationRelativeTo(null);
             frame.setVisible(true);
          } catch (MalformedURLException ex) {
             ex.printStackTrace();
    }db

  • JLabel + GUI problem

    Hello
    I have a JLabel2 which shows the spanish map. The thing is I do wanna draw lines on my spanish map and save it to as an image file in my desktop . I'm able to draw lines and save my JLabel2(spanish map) as an image in my Desktop. The problem is I'm not able to see any lines that I draw before in my image file. I can see those lines when I do click draw button but I can not see them when I save my file as an image to my desktop.Please help me.This problem killed me for two days..you can see how i converted to icon and how i save it as an image file below.Thank you for your helps from now.
    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    File file3;
    int returnVal = fc.showSaveDialog(routemap.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    try {
    File f3 = fc.getSelectedFile();
    ImageIcon icon = (ImageIcon) jLabel2.getIcon();
    System.out.println(icon.getIconHeight());
    BufferedImage buf = new BufferedImage(icon.getImage().getWidth(
    null), icon.getImage().getHeight(null),
    BufferedImage.TYPE_INT_RGB);
    buf.getGraphics().drawImage(icon.getImage(), 0, 0,
    icon.getIconWidth(), icon.getIconHeight(), null);
    ImageIO.write(buf, "jpg", new File(f3.getAbsolutePath()
    + ".jpg"));
    System.out.println(f3.getAbsolutePath());
    } catch (IOException e) {
    I have drawn lines by using draw function as you see below and I can not see those lines without any problem..Lines disapper in the image file when I do save it..Here is the draw button..
    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
    boolean go = true;
    if (OneClicked == false && go == true) {
    jLabel3.setText(jComboBox1.getSelectedItem() + " to ");
    view = jComboBox1.getSelectedItem().toString() + " to ";
    String m = jComboBox1.getSelectedItem().toString();
    int size1 = City.size();
    for (int i = 0; i < size1; i++) {
    if (City.get(i).equals(m)) {
    Index.add(i);
    OneClicked = true;
    go = false;
    if (OneClicked == true && go == true) {
    jLabel3.setText(view + jComboBox1.getSelectedItem());
    view = "";
    String m = jComboBox1.getSelectedItem().toString();
    int size1 = City.size();
    for (int i = 0; i < size1; i++) {
    if (City.get(i).equals(m)) {
    Index.add(i);
    Graphics g = jLabel2.getGraphics();
    g.setColor(Color.BLUE.darker());
    Graphics2D g2 = (Graphics2D) g;
    g2.setStroke(new BasicStroke(3));
    System.out.println(Index.size());
    System.out.println(Index.size() - 2);
    int m1 = Integer.parseInt(XCoordinate.get(Index
    .get(Index.size() - 2)));
    int n1 = Integer.parseInt(YCoordinate.get(Index
    .get(Index.size() - 2)));
    int m2 = Integer.parseInt(XCoordinate.get(Index
    .get(Index.size() - 1)));
    int n2 = Integer.parseInt(YCoordinate.get(Index
    .get(Index.size() - 1)));
    System.out.println(m1 + " " + n1 + " " + m2 + " " + n2);
    g2.drawLine(m1, n1, m2, n2);
    OneClicked = false;
    System.out.println("index im" + Index);
    }

    Cross-post: [java-forums: jlabel-gui-problem|http://www.java-forums.org/java-applets/15472-jlabel-gui-problem.html]
    To the original poster, cross-posting can frustrate anyone who tries to help you only to find out later that the same answer was given hours ago in a cross-posted thread. No one likes wasting their time, especially a volunteer. The polite thing to do would be to not do this, but if you feel that you absolutely must, to at least provide links in both cross-posts to each other.
    edit: all over the dang place: [javaranch: JLabel-GUI|http://www.coderanch.com/t/428887/Swing-AWT-SWT-JFace/java/JLabel-GUI]
    Now this could get folks wanting to not help you ever. Please take care here.
    Edited by: Encephalopathic on Jan 31, 2009 6:34 AM

Maybe you are looking for

  • XML file to B1 Sales Quotaion

    hello, I am trying to insert a sales quotation in XML file format into SAP B1. In the message log i get an error : Value too long in property 'CardCode' of 'Document' every time i use an Item code or a card code containing Hebrew characters , i get g

  • URGENT! - Browser scrollbar problem

    Hi every one! I have a flash site that is 660px wide but the height changes and can be to about 1800px. I want the browsers scrollbar to change depending on how much content is showing. I found this one http://hossgifford.com/downloads.htm, which see

  • How to disable the Optical Drive

    Hi, THere seems to be some problem with the optical drive. Is there a way to disable it till it gets resolved? I don't see any straight forward way to do that. Thanks, Manglu

  • Can Shuttles be based non-base  table ViewObjects with transient attributes

    Hello, Users have to select records from a data collection and a Shuttle looks most appropriate/nice for this purpose. We can introduce technical intersection tables in order to generate the Shuttles with JHeadstart 10g R3 if necessary, but there is

  • Is it possible to check DVD contents in Solaris 10 OK prompt?

    Hi All, Is it possible to check DVD contents in Solaris 10 OK prompt without going into OS level? Please advise. Regards, Pui Keong