Fit image to JLabel or JButton

I have searched the topic and found some instances of the Image package being used to resize images.
I have a DB of images (think photos) that I want to display based on user input. The display size will be the same but the actual picture dimensions stored in the DB won't necessarily be.
My experience is that the amount of image displayed in the JLabel is entirely based on the size of the image itself (i.e. a small image is completely displayed while a large image is partially displayed.
I wish to have the image fit to the JLabel (or JButton) dynamically.
Is there an obvious method I am overlooking?
TIA,
Sil

Here is the code for getting the image from the DB. As you can see it is a byte[].
private static byte[] image = retrieveImage2;
private static byte[] retrieveImage2() throws Exception
        String query = "SELECT GifBlob FROM Blobfile WHERE Name = ?";
        ResultSet rs = null;
        PreparedStatement pstmt = null;
        Blob blob = null;
        try
           pstmt = conn.prepareStatement(query);
           pstmt.setString(1,"7.jpg");
           rs = pstmt.executeQuery();
           rs.next();
           blob = rs.getBlob("GifBlob");
           byte[] gifBlob = blob.getBytes(1, (int) blob.length());
           return gifBlob;
        }I then call the method to place the image on the JLabel
public void addImage(byte[] byteImage) {  
        javax.swing.Icon iconImage = new javax.swing.ImageIcon(byteImage);
        jLabel1.setIcon(iconImage);I don't see where I can set the size of an ImageIcon. Should I be using a different way of converting the image?
Thanks again,
Sil

Similar Messages

  • How to set icon that fit(stretch) to JLabel?

    Let say i have aa image(w = 50, h = 50) and JLabel(w = 100, h = 100)
    how to fit the image to JLabel by JLabel.setIcon(image)?
    thx..

    Ooop... sorry u mean getScaledInstance right, by the way which the faster way to scale image? code 1 or code 2
    Code 1.
    public ImageIcon create_Thumbnail(ImageIcon img,int w , int h ){
            img = new ImageIcon(img.getImage().getScaledInstance(w, h, BufferedImage.SCALE_SMOOTH));
            return  img;
    }Code 2
        public ImageIcon create_Thumbnail(ImageIcon img,int w , int h ){
            BufferedImage bi;
            bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2 = bi.createGraphics();     
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2.drawImage(img.getImage(), 0, 0, w, h, null);
            g2.dispose();
            return new ImageIcon(bi);
        }

  • Getting values from JLabel[] with JButton[] help!

    Hello everyone!
    My problem is:
    I have created JPanel, i have an array of JButtons and array of JLabels, they are all placed on JPanel depending from record count in *.mdb table - JLabels have its own value selected from Access table.mdb! I need- each time i press some button,say 3rd button i get value showing from 3rd JLabel in some elsewere created textfield, if i have some 60 records and 60 buttons and 60 labels its very annoying to add for each button actionlistener and for each button ask for example jButton[1].addActionListener() ...{ jLabel[1].getText()......} and so on!
    Any suggestion will be appreciated! Thank you!

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    class Testing
      public void buildGUI()
        final int ROWS = 10;
        JPanel[] rows = new JPanel[ROWS];
        final JLabel[] labels = new JLabel[ROWS];
        JButton[] buttons = new JButton[ROWS];
        JPanel p = new JPanel(new GridLayout(ROWS,1));
        final JTextField tf = new JTextField(10);
        ActionListener listener = new ActionListener(){
          public void actionPerformed(ActionEvent ae){
            tf.setText(labels[Integer.parseInt(((JButton)ae.getSource()).getName())].getText());
        for(int x = 0; x < ROWS; x++)
          labels[x] = new JLabel(""+(int)(Math.random()*10000));
          buttons[x] = new JButton("Button "+x);
          buttons[x].setName(""+x);
          buttons[x].addActionListener(listener);
          rows[x] = new JPanel(new GridLayout(1,2));
          rows[x].add(labels[x]);
          rows[x].add(buttons[x]);
          p.add(rows[x]);
        JFrame f = new JFrame();
        f.getContentPane().add(p,BorderLayout.CENTER);
        f.getContentPane().add(tf,BorderLayout.SOUTH);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      public static void main(String[] args)
        SwingUtilities.invokeLater(new Runnable(){
          public void run(){
            new Testing().buildGUI();
    }

  • A script to increase the minimum canvas size? (Like Fit Image, but with just my canvas)

    For starters to be clear, I'm looking to manipulate canvas size. Not image size.
    I want to create a script to automatically increase the width and height of my canvas in Photoshop to a specific size when necessary. I only want this to happen if my canvas is less than that specified size. For example: Let's say my canvas size is 300x250. I want the canvas to be at LEAST 600x600. If I run my action it will increase the canvas size to 600x600 for me. If I run this same script on an image where the canvas size is already 700x700, it won't do anything at all to it because both the width and height are equal to or greater than my target size.
    It would also need to work with the height and width on an individual basis. If my image is 400x800, the action would increase my width from 400 to 600, but it would leave the height of 800 alone. So the final canvas size will end up being 600x800.
    It's kind of like the "Fit Image" option in Photoshop, but I only want to manipulate my canvas size, NOT my image size.

    It is possible.
    But if you hope that the dialog remembers the last settings that would require storing those values (which could be done with a txt-file at some pre-defined location), but it would make the Script a bit more complicated.
    // resize canvas in either direction if it is below a defined minimum;
    // 2011; use it at your own risk;
    #target photoshop
    if (app.documents.length > 0) {
    // dialog;
    var dlg = new Window("dialog", "increase width and height if under", [500,300,750,380]);
    // filter for checking if entry is numeric, thanks to xbytor;
    numberKeystrokeFilter = function() {
              if (this.text.match(/[^\-\.\d]/)) {
                        this.text = this.text.replace(/[^\d]/g, "")
              if (Number(this.text <= 0)) {this.text = 5};
              this.text = Math.round(Number(this.text));
    // fields for entry;
    dlg.hor = dlg.add("edittext", [14,15,88,35], "600", {multiline:false});
    dlg.hor.onChange = numberKeystrokeFilter;
    dlg.horText = dlg.add("statictext", [93,15,118,35], "px", {multiline:false});
    dlg.ver = dlg.add("edittext", [129,15,210,35], "600", {multiline:false});
    dlg.ver.onChange = numberKeystrokeFilter;
    dlg.verText = dlg.add("statictext", [215,15,240,35], "px", {multiline:false});
    dlg.hor.active = true;
    // ok- and cancel-button;
    dlg.buildBtn = dlg.add("button", [13,45,118,68], "OK", {name:"ok"});
    dlg.cancelBtn = dlg.add("button", [128,45,240,68], "Cancel", {name:"cancel"});
    // show dialog;
    dlg.center();
    // show dialog;
    var myReturn = dlg.show ();
    // proceed if ok-ed;
    if (myReturn == 1) {
    var myDocument = app.activeDocument;
    // set to pixels;
    var originalRulerUnits = app.preferences.rulerUnits;
    app.preferences.rulerUnits = Units.PIXELS;
    // set the minimum values;
    var minWidth = Number(dlg.hor.text);
    var minHeight = Number(dlg.ver.text);
    // get current ones;
    var theWidth = myDocument.width;
    var theHeight = myDocument.height;
    // resize canvas;
    myDocument.resizeCanvas(Math.max(minWidth, theWidth), Math.max(minHeight, theHeight), AnchorPosition.MIDDLECENTER);
    // reset;
    app.preferences.rulerUnits = originalRulerUnits;

  • How to print JTextPane containing JTextFields, JLabels and JButtons?

    Hi!
    I want to print a JTextPane that contains components like JTextFields, JLabels and JButtons but I do not know how to do this. I use the print-method that is available for JTextComponent since Java 1.6. My problem is that the text of JTextPane is printed but not the components.
    I wrote this small programm to demonstrate my problem:
    import javax.swing.*;
    import javax.swing.text.*;
    import java.awt.*;
    import java.awt.print.PrinterException;
    public class TextPaneTest2 extends JFrame {
         private void insertStringInTextPane(String text,
                   StyledDocument doc) {
              try {
                   doc.insertString(doc.getLength(), text, new SimpleAttributeSet());
              catch (BadLocationException x) {
                   x.printStackTrace();
         private void insertTextFieldInTextPane(String text,
                   JTextPane tp) {
              JTextField tf = new JTextField(text);
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(tf);
         private void insertButtonInTextPane(String text,
                   JTextPane tp) {
              JButton button = new JButton(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(button);
         private void insertLabelInTextPane(String text,
                   JTextPane tp) {
              JLabel label = new JLabel(text) {
                   public Dimension getMaximumSize() {
                        return this.getPreferredSize();
              tp.setCaretPosition(tp.getDocument().getLength());
              tp.insertComponent(label);
         public TextPaneTest2() {
              StyledDocument doc = new DefaultStyledDocument();
              StyledDocument printDoc = new DefaultStyledDocument();
              JTextPane tp = new JTextPane(doc);
              JTextPane printTp = new JTextPane(printDoc);
              this.insertStringInTextPane("Text ", doc);
              this.insertStringInTextPane("Text ", printDoc);
              this.insertTextFieldInTextPane("Field", tp);
              this.insertTextFieldInTextPane("Field", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertButtonInTextPane("Button", tp);
              this.insertButtonInTextPane("Button", printTp);
              this.insertStringInTextPane(" Text ", doc);
              this.insertStringInTextPane(" Text ", printDoc);
              this.insertLabelInTextPane("Label", tp);
              this.insertLabelInTextPane("Label", printTp);
              this.insertStringInTextPane(" Text Text", doc);
              this.insertStringInTextPane(" Text Text", printDoc);
              tp.setEditable(false);
              printTp.setEditable(false);
              this.getContentPane().add(tp);
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setSize(400,400);
              this.setVisible(true);
              JOptionPane.showMessageDialog(tp, "Start printing");
              try {
                   tp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
              try {
                   printTp.print();
              } catch (PrinterException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              new TextPaneTest2();
    }First the components are shown correctly in JTextPane, but when printing is started they vanish. So I created another textPane just for printing. But this does not work either. The components are not printed. Does anybody know how to solve this?
    Thanks!

    I do not know how I should try printComponent. From the API-Doc of JComponent of printComponent: This is invoked during a printing operation. This is implemented to invoke paintComponent on the component. Override this if you wish to add special painting behavior when printing. The method print() in JTextComponent is completely different, it starts the print-job. I do not understand how to try printComponent. It won't start a print-job.

  • The trial version of Adobe photoshop 13 does not have the Crop And Straighten Photos option  under file and automate....... all it has is "Fit Image".......   would really like to have that feature.... is it something they eliminated?

    I am scanning in many old photos and there are several photos on one page.... I read about a feature that was suppose to be available under adobe photo shop elements 13 that would allow multiple cropping under the file, automate, Crop And Straighten Photos....... the only thing that displays on the version 13 that I have is "Fit Image"...... which doesn't help me......    have they removed this tool or do you have to crop and save one image at a time?    Thanks for your help?

    You want Image>Divide Scanned Photos

  • Changing images in JLabels

    I am creating a program which needs to display a grid of 7 by 7 images, as i am new to swing and fairly new to java i decided to use JLabels to show these images.
    I also need to be able to change these images, when buttons are clicked, i have set up the listeners for the buttons and the initial grid is correct however i cannot get the images to change?
    The JLabels are done as an array so each JLabel can be identified seperately.
    I have tried changing the labels eg Images=new JLabel("newimage.gif");
    and also I have tried creating other JLabels and doing things like
    Images[i]=newLabel //newLabel has the icon i want to use.
    I have repainting the screen and if i use the setText method on the JLabels then the text is displayed, however new images aren't
    do i need to not use JLabels, if so what can i use to do this?

    i tried using the setIcon function on my screen capture program and was unable to get it to update the image as long as the old image file was the same filename as the new image file. however if you change the image file name i got it to work fine......you just can't refresh an image of the same name if you've changed the content......

  • Displaying Image using JLabel in swings

    I am not understanding how to display a image in swing using JLabel Component.
    I am writing in the following manner:
    // importing necessary packages
    in init() method
    public void init()
    Container cp= getContentPane()
    JLabel jl=new JLabel("Image",new ImageIcon("<image>.gif"),JLabel.CENTER);
    cp.add(jl);
    applet is running and only label msg is displaying but not the image.
    Please help me so that i can solve this problem.where the image is to be placed??and how it has to be included?
    Please provide me the solution.

    cp.add(new JLabel("Image",new ImageIcon(new java.net.URL (getCodeBase(),"Test.gif")),JLabel.CENTER));

  • "Fit Image" CS-5 upresing with "don't enlarge" checked

    I have been trying to use the new "fit image" action and embedding it in an action. Even with the "don't enlarge" box checked it will make an image bigger.
    Is this a known issue? Am I doing something wrong.
    I'm trying to limit images of mixed resolutions to a maximum of 4600px on the long side. I have an action with 4600x4600 fit image embedded (with "don't enlarge" checked) and it will make a file that's 2000x3000,  4600 on the long side.
    Then I tested Fit Image stand alone. With the "don't enlarge" box checked it will still enlarge an image even one at a time. It seems like the "don't enlarge" check box does nothing at all.
    ARRRGGGG.
    Any suggestions.
    Thanks,
    Tom

    Thank you.
    Please, please let the people in India in Tech support know. I spent more than an hour with them trying to make them understand it wasn't something wrong with my installation and that there had to be a bug in the software.
    Tom

  • Can I do a "Fit Image" ala Photoshop in Illustrator

    I have need to be able to make different size and orientation images fit into a 1.25" x 2.15" area.
    I can do this easily in Photoshop with the "Fit Image" command. However, I haven't been able to figure out how to do this in Illy. I have created an action which can change the dimensions, but some are too tall or too wide for my confined area.
    Can anyone offer insight, please?
    Thanks!

    First no advertising on the forum you might want to edit your last post and remove all that crap.
    Now you your problem make an action, very simple.
    it goes like this start recording and the
    1. Select All
    2. Enter in the control panel width field the width you want
    3. Enter in the control panel the height you want stop recording
    Ok this might not be quite what you want because some are more vertical and some more horizontal and in the action click the  constrain proportion icon.
    so the you do two separate actions and you have to separate the vertical and the horizontal files into separate folders.
    You can use the bridge to select all the horizontal and Vertical artwork files. The bridge show a review of the art in Illy files.
    Now you can batch the two.
    It is a good feature request.
    The only other way would be to write a script with a true and false argument for width and height parameters.
    Then you would only need to run the script or have ti associated with a folder and drop the files in the folder.
    You can visit the scripting forum there maybe one that already exist.

  • Fit image: always in centimeters instead of pixels?!

    Hi
    I'm desperatly looking for a solution to following problem: I want to batch resize images WITHOUT using the "image processor". So I recorded some "Fit Image" steps. In the past they actually got recorded with the unit "pixels" but with CS4 all pixel values get recorded as cm. I already set my ruler units to pixels but it doesn't matter. All actions get recorded in centimeters.
    This also happens with other actions.
    How can I record my actions in pixels?
    Thanks

    Thanks.
    Yes but it gets recorded like this (in centimeters):
    I'm recording either via the record button in the actions windows or by double clicking the entry you see above. It DOES work on my machine but as I often record actions for co-workers these actions won't correctly run on their installations.
    The problem with the Image Processor is that I can't control when the resizing is done. If I want to do some actions before resizing I can't do it with the IP.

  • Images in jlabel

    hi,
    I found a problem in bringing out images in jlabel.
    thanks for peio for your sample code.
    I found an error "cannot resolve symbol"
    for frame.getContentPane().I extended JFrame in the
    class I implemented this init() method.
    getContentPane is working correctly when called simply.
    Being a UG student undertaking a training in java
    swings I have a little maturity in java bugs.
    please guide me.
    yours friendly,
    mohan raj

    ImageIcon caches the previously loaded images and won't reload an image from the same source. Unfortunately, this is not documented in the public API but only in the source of ImageIcon.java.public class ImageIcon implements Icon, Serializable, Accessible {
        /* Keep references to the filename and location so that
         * alternate persistence schemes have the option to archive
         * images symbolically rather than including the image data
         * in the archive.
         */Use ImageIO#read to return an Image and the constructor of ImageIcon that takes an Image as parameter and you'll be set.
    db
    edit Next itme, no help. I dislike cross posters.
    [http://forums.sun.com/thread.jspa?threadID=5340651]
    Edited by: Darryl.Burke

  • Fit Image action stops on some jpgs

    I need to batch thousand of images w different file size dimensions & formats (.eps, .tif, .jpg) to have a print dimension 3"x2" @ 300 dpi (900x600 pixels). Fit Image seems to be the "perfect" feature for this task as long the image starting resolution is 300 dpi.  If the image starting resolution is 72 dpi I have to uncheck "resample image"  change document dimensions to 3"x2", check "resample image" & then change the resolution to 300 dpi to meet our print requirements.
    From Bridge CS5 I select the images that have resolution of 300 dpi> Tools> Photoshop> Batch> I select the action Fit Image.  The problem I'm having is w the jpgs. Sometimes I get the JPG options window. (See attached) which stops the batch to keep processing images until I select OK. I noticed this doesn't happen w every jpg. Is there any way to automate this task without getting any windows?
    I have learned a lot reading posts related to the Fit Image feature. I want to thank all the Photoshop gurus out there.
    PS.: I tried Image Processor... but I think Fit Image work better for my purposes. I'm using PS CS5

    Thank You c.pfaffenbichler for your quick response.
    I was searching for Fit Image in the forums & spent a good amount of time yesterday trying to find answer.  I guess I have to keep looking why I'm still getting the JPG options window.
    c.pfaffenbichler wrote:
    I think there have been previous threads about this, but you’d have to check them out to see if a workable solution was offered.
    Re-saving jpgs seems less than adviseable to me in any case.
    And I wonder why you find Fit Image more convenient than Image Processor in this case?
    In Bridge I select all the images that are 300 ppi including jpg, eps & tiff files. If the original file is a jpg  using Image Processor was Ok but when I'm processing eps & tif converting those files to jpg using Image Processor I noticed that the picture quality changed (blur)  & I have to sharpen the pictures.
    I would like to hear your opinion about Image Processor & why do you think is a better approach than Fit Image action

  • How to fit image inside canvas Container?

    Hi All,
    I want to fit an image inside a canvas.
    Making x and y to 0 of image is not working.
    My problem is I am rotating image at 90 and I want to save that image. If i save normally it is not taking rotation.
    So I am adding that image in a canvas and saving that canvas with rotated image.
    Somehow some portion of canvas still remains empty after adding image to it.
    Any idea how to perfectly fit image inside canvas?
    Or How to rotate image bitmap data with maintainig aspect ratio?
    Thank in advance

    Mx component don't handle rotation very well.  Spark Group should handle it
    better.
    You may need to set the y to the height of the rotated image (its original
    width).

  • Photoshop CC "Fit Image" option

    In CS5 and CS6 I used the "Fit Image" command/option in an action to batch resize images according to the longest dimension, regardless of aspect ratio or portrait/landscape orientation. So far in Photoshop CC, I am unable to locate the command/option by that name (Fit Image) or an equivalent. Can somebody help, please?

    OK, folks... my bad. I found the command under the same name under "File > Automate..." Since I made an action to include that command way back there, I very likely forgot the menu string it comes from. Sorry for the wasted space.
    ACB

Maybe you are looking for

  • My brand new iPod Touch 4th generation will not sync with iTunes on my Windows Vista computer!  Please help!

    I have tried every trick in the book and read every thread on why my version of Windows Vista will not allow me to get at the iTunes Store.  I cannot even get this new iPod Touch to sync with iTunes.  I've rebooted, soft restart, hard restart, remove

  • LSMW for Customer master text upload

    Hi I would want to upload the customer master text using LSMW. I see a message type /DSD/HH_CUSTMASTEXT (Customer master additions) being available. has anybody used this for text upload?? I am not sure how it works, i dont see the provision to enter

  • How to hightlight the process in BPM

    In the BPM workspace, a user can have many processes. If the due time of a process is less than one hour, this process should be highlight. For example, the text color becomes red. The background color of expired process is set to yellow. How to do t

  • What's the fastest C function for writing binary data to disk?

    I'm acquiring data at high speeds across multiple boards and I'm having a hard time writing the data to disk fast enough to keep up. I'm programming in C in Visual Studios and I'm currently using fwrite. I have a similar system set up in LabView and

  • Changing mm/dd/yyyy hh:mm:ss to mm/dd/yyyy in OBIEE

    Hi Guys, I have a filter that is in DateTime format(mm/dd/yyyy hh:mm:ss) in Answers but its hard to use because the filter is so specific(up to seconds) so I want to change it in Date format(mm/dd/yyyy). I've already tried to change its Datatype in t