Resizing image in JFrame

Im trying to get the following code to resize the image that is drawn in TrackPanel, im added a resize listener but am not sure how to get the image to resize when the frame is resized.
import javax.swing.*;
import java.awt.*;
import java.awt.Dimension;
import java.awt.event.*;
import java.net.URL;
public class MyFrame {
     public static void main(String[] args)
          Frame frame = new Frame();
class Frame extends JFrame {
     private Image track;
     public Frame() {
          Class cl = this.getClass();
          Toolkit T = this.getToolkit();
track = T.getImage("C:\\track6.gif");
          MediaTracker mediaTracker = new MediaTracker(this);
mediaTracker.addImage(track, 1);
try {
mediaTracker.waitForID(1);
catch (InterruptedException ie) {
System.err.println(ie);
          addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent evt) {
int width = getWidth();
          int height = getHeight();
          TrackPanel track1 = new TrackPanel(track);
          getContentPane().add(track1, null);
          pack();
          setVisible(true);
class TrackPanel extends JPanel {
     private Image track;
     private int imageWidth;
     private int imageHeight;
     public TrackPanel(Image tr)
          track = tr;
          setPreferredSize(new Dimension(800, 500));
     public void paintComponent(Graphics g)
          g.drawImage(track,0,0, 800,500,this);
}

import javax.swing.*;
import java.awt.*;
import java.awt.Dimension;
import java.awt.event.*;
import java.net.URL;
public class MyFrame {
     public static void main(String[] args)
          Frame frame = new Frame();
class Frame extends JFrame {
     private Image track;
     public Frame() {
          Class cl = this.getClass();
          Toolkit T = this.getToolkit();
        track = T.getImage("C:\\track6.gif");
          MediaTracker mediaTracker = new MediaTracker(this);
        mediaTracker.addImage(track, 1);
        try {
            mediaTracker.waitForID(1);
        catch (InterruptedException ie) {
            System.err.println(ie);
          addComponentListener(new ComponentAdapter() {
            public void componentResized(ComponentEvent evt) {
                int width = getWidth();
                  int height = getHeight();
          TrackPanel track1 = new TrackPanel(track);
          getContentPane().add(track1, null);
          pack();
          setVisible(true);
class TrackPanel extends JPanel {
     private Image track;
     private int imageWidth;
     private int imageHeight;
     public TrackPanel(Image tr)
          track = tr;
          setPreferredSize(new Dimension(800, 500));
     public void paintComponent(Graphics g)
          g.drawImage(track,0,0, 800,500,this);
}Sorry this should do it !!!

Similar Messages

  • Resizing Image when JFrame resized?

    I have a JFrame with a JPanel added to the contentPane (BorderLayout.CENTER). In the JPanel is a JLabel (BorderLayout.CENTER) with an ImageIcon set to it. The image is a subimage of a larger image whose width is scaled to fit the current JLabel width (which is dictated by the JPanel width and finally dictated by the JFrame width).
    When the user resizes the JFrame, the image of the ImageIcon should be replaced with a new image which has been scaled to fit the new width and that reflects the new portion of the larger source image that is visible.
    The JFrame already has a ComponentListener added for retaining the current JFrame size and screen position, but calling my resizeDisplay() method from componentResized() does not seem to have the updated JLabel size. I have added a ComponentListener to the JLabel and called my resizeDisplay() method from componentResized() but it does not seem to have the updated JLabel size either.
    How can my application properly react to JFrame resizes so that the method is retrieving the new size values?
    Thanks,
    Robert Templeton

    Its always easier to solve a problem when sample code (not a complete program) is posted with the question.
    Maybe I don't understand the question, but when I run the following code the output reflects the size of the label after it has been resized. I'm using JDK1.3 on Window 98.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestLabel extends JFrame
         public TestLabel()
              JPanel panel = new JPanel();
              setContentPane( panel );
              panel.setPreferredSize( new Dimension( 200, 200 ) );
              panel.setLayout(new BorderLayout() );
              final JLabel myLabel = new JLabel( new ImageIcon("dukeWaveRed.gif"), JLabel.CENTER );
              panel.add( myLabel );
              myLabel.addComponentListener( new ComponentAdapter()
                   public void componentResized(ComponentEvent e)
                        System.out.println( myLabel.getSize() );
         public static void main(String[] args)
              TestLabel frame = new TestLabel();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • Which approach to use for resizing image

    There are two ways of resizing images as I know:
    1. image.getScaledInstance(width,height,hint);
    Using hint like Image.SCALE_AREA_AVERAGING gives somehwat satisfactory resizing.
    2. static BufferedImage resize(GraphicsConfiguration gc, BufferedImage source, int w, int h, Object hintValue) {
    BufferedImage result = gc.createCompatibleImage(w, h, source.getTransparency());
    Graphics2D g2 = result.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hintValue);
    double sx = (double) w / source.getWidth(), sy = (double) h / source.getHeight();
    g2.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));
    g2.dispose();
    return result;
    where the hint passed is RenderingHints.VALUE_INTERPOLATION_BILINEAR ;
    Now which of the two method method should I use-using image.getScaledInstance() or using AffineTranform ? opr is there any other way which is faster but provides good result?
    i am creating an image editor, so the GUI dialog will have oprtion to choose the algorithm. I want the method which provides better result yet faster.
    Tanveer

    http://forum.java.sun.com/thread.jsp?forum=20&thread=522483

  • Problem with display an image on JFrame in Java 6

    I'm trying to display an image on JFrame in this way:
    1.) I'm creating a variable in the class:
        private Image imgSpeaker = null;2.) I'm overiting the paint method:
    public void paint(Graphics g) {
            super.paint(g);   
            g.drawImage(imgSpeaker, 330, 230, null);  
        }3.) In the constructor I'm using this code:
       imgSpeaker = Toolkit.getDefaultToolkit().getImage("D:\\speaker.gif");
            MediaTracker trop = new MediaTracker(this);
            trop.addImage(imgSpeaker,0);
            try {
                trop.waitForID(0);    // waiting untill downloading progress will be complite
            } catch (Exception e) {
                System.err.println(e);
            }        The Image will be displayed on form, but if I catch the window and move it (for example: down as possible)
    the image is not refreshed (repainted). What I'm doing wrong? I've been used this solution in Java 5 and everything
    works perfectly. Any of described methods aren't depricated... Anyone can help me?

    Thanks for your code, I've been tryed to apply your solution (with create a Buffered Image), but it still not working correctly. Firstly, the image isn't loading, and secondly the basic problem is not give in. Why have you been using "bg2d.draw(img, x, y, w, h, frame);" not in the paint method?
    I'm use "Free Design" layout. Below I put on completly code from Netbeans.
    import java.awt.Graphics;
    import java.awt.Image;
    import java.awt.MediaTracker;
    import java.awt.image.BufferedImage;
    public class ImageTest extends javax.swing.JFrame {
        private Image imgSpeaker = null;
        private BufferedImage bi = null;
        private MediaTracker trop = null;
        public ImageTest() { 
                initComponents();
                trop = new java.awt.MediaTracker(this);
                imgSpeaker = java.awt.Toolkit.getDefaultToolkit().getImage("D:\\speaker.gif");
                try {
                    trop.addImage(imgSpeaker, 0);
                    trop.waitForID(0);
                } catch (java.lang.Exception e) {
                    java.lang.System.err.println(e);
                bi = new java.awt.image.BufferedImage(100, 100, java.awt.image.BufferedImage.TYPE_INT_RGB);
                java.awt.Graphics2D bg2d = (java.awt.Graphics2D) bi.createGraphics();
                trop.addImage(bi, 1);
    //            java.io.File f = new java.io.File("D:\\speaker.gif");
    //            try {
    //                bi = javax.imageio.ImageIO.read(f);
    //            } catch (IOException e) {
    //               java.lang.System.err.println(e);
        public void paint(Graphics g) {
    //      super.paint(g);
           try {                                                   
                trop.waitForAll();                                 
            } catch (Exception e) {
                System.err.println(e);
            g.drawImage(bi, 50, 100, imgSpeaker.getHeight(this), imgSpeaker.getHeight(this), this);
        // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
        private void initComponents() {
            jButton1 = new javax.swing.JButton();
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            jButton1.setText("jButton1");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(283, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(44, 44, 44))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(252, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(25, 25, 25))
            pack();
        }// </editor-fold>
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new ImageTest().setVisible(true);
        private javax.swing.JButton jButton1;
    }

  • Inserting an image to Jframe and save it ,  in SQL database

    Hai guys,
    I just wanna know about the inserting image in to a Jframe (in netBeans) it will be a grate help if you tell me the way to call a image to Jframe through a Button click and save the image in MySQl database.
    Is anyone has a idea about this task, please tell me
    Thanks,

    Image class should work to get the data, then add it to a Canvas object, then you can save the bytes from the Image into an SQL statement through JDBC.
    The implementation details will vary based on which approch and database you select.

  • Need help on quality of resized image!!

    I am required to resize images to max 1240pixel (longest dimension) as a submission of work, though when work is viewed it will be at 30"x40".  Can not figure out a way to do this where images don't become quite pixelated when viewed at larger size.   Appreciate any suggestions. 

    Is there some software to verify if my graphics card is shotty?
    Techtool Pro has some testing, the AHT tests VRAM, but game benchmarks and stressing will tell you the most.
    Is re-seating the graphics card or memory worth trying?
    Absolutely. Just don't reinstall the graphics card until you clean it thoroughly.
    Cleaning the dust out of my machine?
    YES. A dust filled graphics card heatsink will cause the GPU to cook, and cause problems thet you describe.
    If I need a new graphics card, what are my options? Do I have to purchase it via Apple store? I would like to stick with an Nvidia card so am I stuck buying the same card I currently have or can I upgrade?
    You don't have to buy from Apple, but using with OS X limits your choices to Mac compatible or flashable PC versions.
    There is an awful lot of user input into this topic here:
    http://blog.macsales.com/602-testing-those-new-graphics-cards
    Card reviews can also help:
    http://www.anandtech.com/video/showdoc.aspx?i=3140&p=9
    http://www.tomshardware.com/reviews/radeon-hd-4870,1964.html

  • I need some help resizing my images on PS6. I am using a mac and have been trying to resize with same resolution and constaining proportions but for some reaseon the smaller resized image appears pizelated.

    I need some help resizing my images on PS6. I am using a mac and have been trying to resize with same resolution and constaining proportions but for some reaseon the smaller resized image appears pizelated. Heres an image of before and after. The first image I use is a JPG 72dpi 1500px x1500px and I want to downsize it to 600x600px same res, but it keeps pixelating, this has never happened before. Any suggestions, thoughts?
    thanks!

    I wouldn't say pixelated; more like blurry.
    Like ConnectedCreative said, what steps are you using? Are you using "bicubic sharper" when resizing down?

  • Upload and Resize Image not inserting filename in database

    I have a form that I created using the insert record form wizard. One of the fields is a file field and my form enctype is set to multipart/form-data. I then used the upload and resize image behavior and set the parameters. When testing the form the file uploads to the correct directory but no entry is made into the database for that particular field. The other fields are entered into the database just fine. If it helps, here is the code generated before the  tag:
    <br />
    <br /><?php require_once('../../Connections/test.php'); ?>
    <br /><?php<br />// Load the common classes<br />require_once('../../includes/common/KT_common.php');<br /><br />// Load the tNG classes<br />require_once('../../includes/tng/tNG.inc.php');<br /><br />// Make a transaction dispatcher instance<br />$tNGs = new tNG_dispatcher("../../");<br /><br />// Make unified connection variable<br />$conn_test = new KT_connection($test, $database_test);<br /><br />// Start trigger<br />$formValidation = new tNG_FormValidation();<br />$tNGs->prepareValidation($formValidation);<br />// End trigger<br /><br />//start Trigger_ImageUpload trigger<br />//remove this line if you want to edit the code by hand <br />function Trigger_ImageUpload(&$tNG) {<br />  $uploadObj = new tNG_ImageUpload($tNG);<br />  $uploadObj->setFormFieldName("picture");<br />  $uploadObj->setDbFieldName("picture");<br />  $uploadObj->setFolder("../images/");<br />  $uploadObj->setResize("true", 120, 0);<br />  $uploadObj->setMaxSize(1500);<br />  $uploadObj->setAllowedExtensions("gif, jpg, jpe, jpeg, png, bmp");<br />  $uploadObj->setRename("auto");<br />  return $uploadObj->Execute();<br />}<br />//end Trigger_ImageUpload trigger<br /><br />// Make an insert transaction instance<br />$ins_team = new tNG_insert($conn_test);<br />$tNGs->addTransaction($ins_team);<br />// Register triggers<br />$ins_team->registerTrigger("STARTER", "Trigger_Default_Starter", 1, "POST", "KT_Insert1");<br />$ins_team->registerTrigger("BEFORE", "Trigger_Default_FormValidation", 10, $formValidation);<br />$ins_team->registerTrigger("END", "Trigger_Default_Redirect", 99, "../team.php");<br />$ins_team->registerTrigger("AFTER", "Trigger_ImageUpload", 97);<br />// Add columns<br />$ins_team->setTable("team");<br />$ins_team->addColumn("id", "NUMERIC_TYPE", "POST", "id");<br />$ins_team->addColumn("sort", "NUMERIC_TYPE", "POST", "sort");<br />$ins_team->addColumn("name", "STRING_TYPE", "POST", "name");<br />$ins_team->addColumn("title", "STRING_TYPE", "POST", "title");<br />$ins_team->addColumn("description", "STRING_TYPE", "POST", "description");<br />$ins_team->addColumn("picture", "FILE_TYPE", "FILES", "picture");<br />$ins_team->setPrimaryKey("id", "NUMERIC_TYPE");<br /><br />// Execute all the registered transactions<br />$tNGs->executeTransactions();<br /><br />// Get the transaction recordset<br />$rsteam = $tNGs->getRecordset("team");<br />$row_rsteam = mysql_fetch_assoc($rsteam);<br />$totalRows_rsteam = mysql_num_rows($rsteam);<br />?>

    If the reason is about memory, warning message should be happened when upload the image, because "show thumbnail" means resize at second time, how come you failed to resize the picture that system let it upload succeed at the first time by the same resize process?
    upload procedure
    a.jpg: 2722x1814, 1.2mb
    upload condition: fixed width 330px, 1.5mb
    "upload and resize" a.jpg -> file upload -> "resize engine" -> passed (but not work and no warning message)
    "show thumbnail" a.jpg -> "resize engine" -> failed (not enough memory)
    it doesn't make sense.
    and you miss an important key point, I upload the same picture myself, and resize work, so I said it happened at random, and that's why I am so worried.

  • Resize image in pdf file

    I need to resize image in pdf ,
    I get this [http://www.java2s.com/Tutorial/Java/0419__PDF/Positionandresizeanimage.htm]
    I try to put the code in my servlet
    but I get error on not static method on PdfContentByte cb = writer.getDirectContent(); how to deal this problem
    Thank You

    PdfContentByte cb = writer.getDirectContent();There is no such method in the JDK or the Servlet API.
    Ask whoever provides it.

  • Resizing images published through flickr, but I don't want it to.

    I set up a flickr connection with LR3, very cool. However it resized the image to 1024x768, though I have nothing set under 'resize'. Why is it doing that?  Do I have to set it to resize everything to 9000 pix and not enlarge for it to keep the original size?

    Setting the resolution to 9000 x 9000 wont make any difference. Or at least it did not for me.
    It could be a limitation of Flickr (no Pro account). Perhaps it is different with a Pro account.size file is being uploaded if you dont resize on output but you wont see it if you dont have a Pro account.
    In fact, from the Flickr site: Only smaller (resized) images accessible (though the originals are saved in case you upgrade later)
    This would suggest that your original size file is being uploaded if you dont resize on output but you wont see it if you dont have a Pro account.

  • Problem with getting resized image's bytes

    I've got a problem with getting correct bytes of a newly resized image. The flow is that I retrive an image from the filesystem. Due to the fact that it is large I resize it to a 50x50px thumbnail. I can display this thumbnail in #benchmark1 (see code below). Unfortunately something's wrong with my imageToBytes funtion which returns reasonably small size of image but is totally useless - I can't make an image of it anymore so at #benchmark2 the application either crashes or keeps freezing. I saved this byte array on my disk and tried to preview under Windows how does it look but I got a message "Preview unavailabe". I did some digging in the Internet and I supposed that it's because I don't use any jpg or png encoders to save the file. Actually I think that it's not the case, as the bytes returned from method imageToBytes look weird - I cannot even make a new image of them and display it without any saving in memory.
                                  byte[] bytes = FileHandler.readFile (
                                          FileHandler.PHOTOS_PATH, fileName);
                                  Image img2 = Image.createImage (bytes, 0, bytes.length);
                                  img2 = ImageHandler.getInstance ().resize (img2);
                                                    //#benchmark1
                                  bytes = ImageUtils.imageToBytes (img2);
                                  img2 = Image.createImage (bytes, 0, bytes.length);
                                                    //#benchmark2my imageToBytes function is as follows:
         public static byte[] imageToBytes (Image img)
              int[] imgRgbData = new int[img.getWidth () * img.getHeight ()];
              byte[] imageData = null;
              try
                   img.getRGB (imgRgbData, 0, img.getWidth (), 0, 0, img.getWidth (),
                           img.getHeight ());
              catch (Exception e)
              ByteArrayOutputStream baos = new ByteArrayOutputStream ();
              DataOutputStream dos = new DataOutputStream (baos);
              try
                   for (int i = 0; i < imgRgbData.length; i++)
                        dos.writeInt (imgRgbData);
                   imageData = baos.toByteArray ();
                   baos.close ();
                   dos.close ();
              catch (Exception e)
              return imageData;
    I've run totally out of any idea what's wrong, please help!
    Edited by: crawlie on Jul 17, 2010 6:21 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hey Crawlie,
    Please note that simply writing int values into ByteArrayOutputStream will not suffice. Please have a look at the following conversion from int pixel value into byte[4]:
    public static final byte[] intToByteArray(int value) {
            return new byte[] {
                    (byte)(value >>> 24),
                    (byte)(value >>> 16),
                    (byte)(value >>> 8),
                    (byte)value
    }Good Luck!
    Daniel

  • 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.

  • Inserting image to jFrame and save it in a sql database

    Hai guys, I have a problem in inseting a image in jfame and save it in database (my sql)
    does any one have an idea about this task reply me pls
    thanks
    bay !

    Use BLOB (Binary Large Object) to save your image to a database.
    As far as displaying a image on Jframe, search the forum.

  • Resizing Image and Not Keep Aspect Ratio

    Is there a free program to resize images and not keep the original aspect ratio?
    I need to resize loads of images to 100x100 pixels and have tried Image well and IResize yet they do not seem to have an option to not keep the original aspect ratio.
    Thank you
    20" Intel 2GHz Core Duo imac, 2GB Ram, 250 GB HD    

    Hi, Downsize does not seem all that great according to reviews. Why not see if you can buy PS E' 3 mac -- maybe ebay/amazon (if I remember I only paid about $70 for PS E3) As PS E4 just came out I'm sure someone has PS E3 for sale. You will then have no problems completing your image resizing.
    2 other questions for you..are you using the Mac side of your intel or Windows?
    if your using the Windows side I can let you have PS 6 (PC) ..freegratus.

  • Resizing images

    I am using Photoshop CS (older version).
    I am having a problem with resizing images. Prior to sending this, everything was working okay and now nothing will resize. my file path was file menu > automate > batch > and then I would choose my source and destination for the resized images. In the end, all the newly resized images would stay the same size as before. Can someone please help me with this???

    Neil,
    Have you selected the "resizing" action in the Batch dialog?

Maybe you are looking for

  • I am trying to update iMovie to version 9.0.8

    Hi I am trying to complete the update to iMovie version 9.0.8 on Mountain Lion. The problem is that in my country the available bandwidth is not good and the download from the App Store is so slow that the download takes 16 to 20 hours. When the down

  • Resetting Document  ? ? ? ? ?

    Dear All, Experts, Can any one tell me what is Resetting the document ? And what is Resetting the cleared document ? Please explain in detail. Thanks in advance ! Regards, Sharvari.

  • How to customize & enlarge default Save-As dialog

    I have a large monitor. Is there a way to customize the default Save-As dialog, so that it: - always opens in the expanded form (with folders etc.) - opens with a bigger initial size (so I can see most of my left bar) Thanks

  • Error PC Sync Not connected (after upgarde)

    I have now managed to get PC Suite to recognise all connection types by using the PC connectivity repair programme in Windows Add/Remove programmes Now everything works apart from sync with outlook. I get the above error - PC sync not connected. The

  • Shared photos on icloud

    I have deleted the photos from my photo stream, but have photos that are on 'shared streams' on my icloud.  As these are now in my iphotos and saved on my computer and my passport, is there any way I can delete thenm from my phone?  When I try it tel