Image resize problem in Swing Application

Hi All
I need a help on resizing and adjustment of Image in Swing application.
I am developing a Swing Application. There I am displaying a image on header.
I am finding it difficult to manage the image, as I want the image to perfectly fit horizontal bounds(Even on window resize).
The current code given below is unable to do so.. Even it's not able to fit the horizontal bounds by default.
========================================
//code for image starts
        BufferedImage myPicture;
        JLabel picLabel = null;
        try {
             myPicture = ImageIO.read(new File("artes_header.png"));
                picLabel = new JLabel(new ImageIcon(myPicture));
          } catch (Exception e) {
        GridBagLayout gLayout = new GridBagLayout();
        getContentPane().setLayout(gLayout);
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 1;
        c.gridy = 1;
        c.weightx = 1;
        c.fill = GridBagConstraints.BOTH;
        c.insets = new Insets(0, 0, 0, 0);
        panelTop.setBackground(Color.white);
        getContentPane().add(picLabel, c);
        c.gridx = 1;
        c.gridy = 2;
        c.weightx = 1;
        c.weighty = 1;
        getContentPane().add(tabPane, c);========================================
Kindly anyone help me solve the same issue.
Many thanks in advance.
Regards,
Gaurav
Edited by: user7668872 on Jul 31, 2011 6:25 AM
Edited by: user7668872 on Aug 4, 2011 3:56 AM

Your questions doesnt make a whole lot of sence so not sure if this is what you want...
This is a class to display an image on a jpanel. You can then use layout managers to make sure it is centrally alligned
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
class testImagePanel{
    public static void main(String[] args){
        BufferedImage image = null;
        ImagePanel imagePanel = null;
        try{
            image = ImageIO.read(new File("image.jpg"));
            imagePanel = new ImagePanel(image);
            imagePanel.setLayout(new BorderLayout());
        }catch(IOException  e){
             System.err.println("Error trying to read in image "+e);
        JFrame frame = new JFrame("Example");
        frame.add(imagePanel);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);               
public class ImagePanel extends JPanel {
    private BufferedImage image;
    private Dimension size;
    public ImagePanel(BufferedImage image) {
        this.image = image;
        this.size = new Dimension();
        size.setSize(image.getWidth(), image.getHeight());
        this.setBackground(Color.WHITE);
    @Override
    protected void paintComponent(Graphics g) {
        // Center image in this component.
        int x = (getWidth() - size.width)/2;
        int y = (getHeight() - size.height)/2;
        g.drawImage(image, x, y, this);
    @Override
    public Dimension getPreferredSize() { return size; }
}

Similar Messages

  • Including images in JAR for Swing Application

    I am using a couple of images in a Swing application. When I create the JAR file I include all the images. The JAR executes fine but the images are missing. When I put the images in the same directory as the JAR file the images are properly displayed.
    The code I use to display the images is:
    JLabel label = new JLabel(new ImageIcon("pleaseWait.gif"));
    Can anyone let me know what I need to do to get the image from the JAR? Do I need to look at ResourseBundle's?
    Thanks for any help..

    Does anybody know what is the reason of my problem??
    I created a package called test in my eclipse env. and in that package I placed folder named graph in which there is a file Help.png.
    Here is all the code I run in eclipse and it runs properly. When I create a jar file (using eclipse wizard) to execute without eclipse it can not execute and shows nothing (process starts and I have to kill it by myself in OS). Maybe there is some mistake with making jar... I do not know
    So let someone try tu run my class or build jar file and try to execute and share his observations (solutions) ??
    package test;
    import java.awt.Toolkit;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.UIManager;
    public class TestWindow extends JFrame {
         private JButton jButton1 = new JButton(new JARImage().getImage("Help.png"));
         public TestWindow() {
              this.getContentPane().add(jButton1);
              this.validate();
              this.setVisible(true);
         private class JARImage {
              protected ImageIcon getImage(String imageName) {
                   ImageIcon image = new ImageIcon();
                   try {
                        image.setImage((Toolkit.getDefaultToolkit().getImage(getClass()
                                  .getResource("graph/" + imageName))));
                   } catch (Exception ex) {
                        System.out.println("Image Error: " + ex);
                        ex.printStackTrace();
                   return image;
         public static void main(String[] args) {
              try {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
              } catch (Exception e) {
                   e.printStackTrace();
              new TestWindow();
    }

  • Thread problem in swing application?

    Hi,
    I have a doubt in GridLayout and Threads. I�m doing one small application which is accepting images and Alphabets. Actually, What I�m doing running images and alphabets(combinedly) in frequent intervals. For this I used GridLayout and Thread concept. But I have a problem in paint method. How to call the GridLayout frequently. In GridLayout , I�m putting Images and alphabets. Acutually in paint method , there are only drawString or drawImage or other methods. Is it possible to call my layout. Is so, can anybody help me in this regard. Is there any way to do it . please suggest me.
    Thanks,
    -Balaji
    My code follows:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    import java.awt.Color;
    import javax.swing.*;
    import java.applet.Applet;
    import java.util.*;
    import java.io.*;
    public class GridLayEx2 extends Applet implements Runnable {
    private Random r = new Random();
    private Thread imageThread = null;
    GridLayout glt;
    public void init() {
    glt = new GridLayout(3,3);
    setLayout(glt);
    } // end of init method
    public void start(){
    if (imageThread == null) {
    imageThread = new Thread(this, "GridLayEx2");
    imageThread.start();
    } // end of start method
    public void run(){
    Thread myThread = Thread.currentThread();
    while (imageThread == myThread) {
    repaint();
    try {
    Thread.sleep(1000);
    } catch (InterruptedException e){ }
    }// end of run method
    public void paint(Graphics g){
    Font boldFont = new Font("Helvetica", Font.BOLD, 25);
    Font plainDerived =
    boldFont.deriveFont(Font.PLAIN, 25);
    JLabel myLabel[] = new JLabel[9];
    String myUrl = "C:\\Regoti\\Vision\\AP\\Project\\Version1\\images\\duke1.gif";
    myLabel[0] = new JLabel(new ImageIcon(myUrl));
    myLabel[1] = new JLabel("A");
    myLabel[2] = new JLabel("A");
    myLabel[3] = new JLabel("A");
    myLabel[4] = new JLabel("A");
    myLabel[5] = new JLabel("A");
    myLabel[6] = new JLabel("A");
    myLabel[7] = new JLabel("A");
    myLabel[8] = new JLabel("A");
    myLabel[1].setFont(boldFont);
    myLabel[2].setFont(boldFont);
    myLabel[3].setFont(boldFont);
    myLabel[4].setFont(boldFont);
    myLabel[5].setFont(boldFont);
    myLabel[6].setFont(boldFont);
    myLabel[7].setFont(boldFont);
    myLabel[8].setFont(boldFont);
    int values[] = new int[9];
    values = gen_pos_uni_ran_num(0,8);
    for(int i = 0; i < 9; i++)
    add(myLabel[values]);
    } // end of paint method
    public void stop(){
    imageThread = null;
    } // end of stop method
    public int[] gen_pos_uni_ran_num(int min, int max)
    int results[] = new int[Math.abs(max - min) + 1];
    for(int i = 0; i < results.length; ++i)
    results = -1;
    outer_loop:
    for(int i = 0; i < results.length; ++i)
    int random_int = (int)((Math.random() * results.length) + min);
    for(int j = 0; j < results.length; ++j)
    if(results[j] == random_int)
    random_int = (int)((Math.random() * results.length) + min);
    j = -1;
    continue;
    if(j == results.length - 1)
    results = random_int;
    continue outer_loop;
    return results;
    } // generate unique random numbers
    public static void main( String args[])
    Frame GridLayFrame = new Frame ( " Grid Layout Frame ");
    GridLayEx2 gl = new GridLayEx2();
    gl.init();
    GridLayFrame.add(gl);
    GridLayFrame.pack();
    GridLayFrame.setSize(GridLayFrame.getPreferredSize());
    GridLayFrame.show();
    GridLayFrame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    } // end of main method

    hi,
    i got one doubt in the previous application. i want to put labels in the circle manner while changing my label positions. Now it is rectangular type. And also i want to change my background color of JFrame. Please see my code ...
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Graphics;
    import java.awt.Color;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    import java.net.URL;
    import java.net.MalformedURLException;
    import java.util.GregorianCalendar;
    public class GridLayEx6 extends JApplet{ 
       private Random r = new Random(); 
       private ActionListener taskPerformer;
       private javax.swing.Timer timer;  
       private GridLayout glt;  
       private JLabel[] myLabel;     
       GregorianCalendar todayDate = new GregorianCalendar();     
       long fromTime,toTime,elapsedTime;
       public void init() {     
            glt = new GridLayout(3,3);     
          Font boldFont = new Font("Helvetica", Font.BOLD, 25);     
          Font plainDerived = boldFont.deriveFont(Font.PLAIN, 25);     
             myLabel = new JLabel[9];     
             String myUrl = "C:\\Regoti\\Vision\\AP\\Project\\Version1\\images\\MyArrow.jpg";
             String myUrlA = "C:\\Regoti\\Vision\\AP\\Project\\Version1\\images\\MyA.jpg";     
             URL url = null;     
       try{
       myLabel[0] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);     
       myLabel[1] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
       myLabel[2] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
       myLabel[3] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
       myLabel[4] = new JLabel("+", SwingConstants.CENTER);     
       myLabel[5] = new JLabel(new ImageIcon(myUrlA), SwingConstants.CENTER);
       myLabel[6] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
       myLabel[7] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
       myLabel[8] = new JLabel(new ImageIcon(myUrl), SwingConstants.CENTER);
       myLabel[2].setVerticalAlignment(SwingConstants.NORTH);     
       myLabel[4].setFont(boldFont);     
       getContentPane().setLayout(glt);     
      } catch( Exception e)
        { System.out.println(" Exception occurs "+e);}
       int delay = 20000; //milliseconds     
       ActionListener taskPerformer = new ActionListener() {     
       public void actionPerformed(ActionEvent evt) {      
                 randomDuke();
       timer = new javax.swing.Timer(delay, taskPerformer);     
       addKeyListener(new KeyAdapter()      {        
          public void keyPressed(KeyEvent e){           
                 GridLayEx6 gl2 = (GridLayEx6)e.getSource();           
                     switch(e.getKeyCode())
                           case(KeyEvent.VK_ENTER): 
                                gl2.randomDuke();                 
                                break;
                       case(KeyEvent.VK_SPACE):              
                            if(gl2.timer.isRunning())                    
                              { gl2.timer.stop();                 
                                    toTime = System.currentTimeMillis();
                                 elapsedTime = toTime - fromTime;
                                 System.out.println("toTime : "+toTime);
                                 System.out.println("elapsedTime : "+elapsedTime);
                                  gl2.timer.start();
                                   gl2.randomDuke();
                               break;
                       case(KeyEvent.VK_KP_RIGHT):case(KeyEvent.VK_KP_UP):              
                       case(KeyEvent.VK_RIGHT):case(KeyEvent.VK_UP):              
                         int delay = gl2.timer.getDelay();
                         if(delay > 0)                    
                            gl2.timer.setDelay(delay - 100);                 
                            break;
                       case(KeyEvent.VK_KP_LEFT):case(KeyEvent.VK_KP_DOWN):              
                       case(KeyEvent.VK_LEFT):case(KeyEvent.VK_DOWN):
                            int delay = gl2.timer.getDelay();                  
                            if(delay < 10000)                    
                                 gl2.timer.setDelay(delay + 100);                  
                                 break;
                       //timer.start();  
             } // end of init method  
             public void start()   {     
                  timer.start();     
                    while(!isFocusOwner())        
                            requestFocus(); 
             } // end of start method     
             public void stop(){    
                  timer.stop();
            } // end of stop method     
             /** To make sure we have focus in application *  
             * mode if JFrame loses focus control          *  
             * - non standard usage of paintComponent      */    
             public void paintComponent(Graphics g)   {
                  while(!isFocusOwner())        
                       requestFocus();  
            public void randomDuke()   {     
                  fromTime = System.currentTimeMillis();
                  System.out.println("fromtime : "+fromTime);     
                  getContentPane().removeAll();     
                  int[] values = new int[9];     
                  int temp;
                  values = gen_pos_uni_ran_num(0,8);     
                  for ( int i=0; i<=8;i++)
                          if ( values[i] == 4)
                                 temp = 4;
                                 values[i] = values[4];
                                 values[4] = temp;
                  for(int q = 0; q < 9; q++)   
                        getContentPane().add(myLabel[values[q]]);    
                       myLabel[0].revalidate();
                       myLabel[1].revalidate();
                       myLabel[2].revalidate();
                       myLabel[3].revalidate();
                       myLabel[5].revalidate();
                       myLabel[6].revalidate();
                       myLabel[7].revalidate();
                       myLabel[8].revalidate();
                    } // end of randomDuke method  
              public int[] gen_pos_uni_ran_num(int min, int max)   {     
                  int results[] = new int[Math.abs(max - min) + 1];     
                  for(int q = 0; q < results.length; ++q) 
                       results[q] = -1;     
                  outer_loop:     
                  for(int q = 0; q < results.length; ++q)  
                       int random_int = (int)((Math.random() * results.length) + min);        
                    for(int j = 0; j < results.length; ++j)       
                        if(results[j] == random_int)            {              
                            random_int = (int)((Math.random() * results.length) + min);              
                            j = -1;
                      continue;           
                     if(j == results.length - 1)
                          results[q] = random_int;              
                          continue outer_loop;
                  return results;  
                  } // generate unique random numbers  
                  public static void main( String args[])
                        JFrame GridLayFrame = new JFrame ( " Grid Layout Frame ");     
                       GridLayFrame.setSize(500,500);     
                       GridLayEx6 gl = new GridLayEx6();     
                       gl.init();     
                       GridLayFrame.getContentPane().add(gl);     
                       //GridLayFrame.setBackgroundColor(Color.white);
                       GridLayFrame.setVisible(true);
                       gl.start();     
                       GridLayFrame.addWindowListener(new WindowAdapter()      
                         public void windowClosing(WindowEvent e)         
                        System.exit(0);         }      });  
                  } // end of main method
                  }

  • Image Resizing Problem

    Hello,
    I am working on image project. The task which I want to do is to resize the image. I am using normal java.awt.image package. The classes which I am using are AffineTransformOp for scaling an image, Graphics and BufferedImage etc. The problem is when I scaled down an image of large image to low image (e.g. 800 x 800 to 160x160), The image gets blued or some pixels are looking stretched. I have tried severl other 3rd party APIs but failed. However if i conver 400x400 image to 160x160 .. it works fine. I need quick help..plz if somebody can suggest any solution..
    Thanks

    try {
         AffineTransformOp op = null;
    BufferedImage tempImage;
    double xScale = (double)((double)x/(double)width);
    double yScale = (double)((double)y/(double)height);
              BufferedImage outImage;
              OutputStream os;          
    op = new AffineTransformOp(AffineTransform.getScaleInstance(xScale,yScale),AffineTransformOp.TYPE_BILINEAR);     tempImage = op.filter(original, null);           
    } catch (ImagingOpException e) {
    e.printStackTrace();
    System.out.println("Exception while creating imgages");
         }

  • Image resize problem

    For the life of me I can't figure out why this isn't working properly. I've been resizing images this way for months now and I must have changed some setting or whatever cause it simply doesn't work. Please be kind if I'm posting improperly as this is my first time posting here.
    Here's the situation. I have an image below at resolution 5000x2048.
    When I trim the canvas everything works properly as seen below.
    Due to the Trim canvas, the image is now 2071x1252. I want to resize the entire image to 1680 & keep proportions as shown below.
    Here's where I run into problems. I've never had it do this before, and I can't figure out how to fix it. When I resize the image, I get the following.
    As you can see, the canvas resized properly, but the vectors resized a whole lot smaller. Any help would be greatly appreciated.
    Message was edited by: A. Buskov

    That's perplexing. Just out of curiousity: Is everything a vector, or is it a mix of vectors and bitmaps? It appears that some of the components resized properly, where others did not.
    Since you know what dimensions you're shooting for, you could try reversing the order of things: resize, then trim. First figure out the percentage by which you were reducing the trimmed image size: 1680 / 2071 = 81.12%. Now apply that percentage to your initial image size: 5000 x 2048 becomes 4056 x 1661. Do the same sizing discrepancies occur? If not, then apply the Trim Canvas command, and you should be good to go.
    Alternatively, if you're resizing this graphic for output, you could simply use the Image Preview dialog instead (after trimming).
    Another troubleshooting idea: Have you tried saving the graphic immediately after applying the Trim command, and then resizing?
    Finally, how about using Modify > Transform > Numeric Transform... and then choosing either Resize or Scale?

  • Photoshop CS5 - Image resize problem with move tool

    Hi People
    Here's my problem
    When I try to resize an layer using the move tool (as opposed to the Free Transform tool), while I'm in the process of moving the scaling handles, the bounding box reflects my movement but the layer preview stays at it's original size. When I stop moving the handles there is a few seconds delay and then the new scale size shows up. If I try to move the handles again, without commiting to the transform, the layer preview reverts back to it's original size until I've finished moving the handles.
    I didn't have this problem with CS4 and I've only recently upgraded. I work around this problem by using the proper Free Transform tool (ctrl+t) but it would be nice to know why the hell this happens. It seems to me to be more of a graphical glitch than a software preference but I thought I'd check just-in-case.
    Specs:
    Photoshop CS5 V12.1 x64
    PC
    Intel Xeon W3505 @2.53GHz
    Nvidia Quadro FX580
    12 GB RAM

    ace591 wrote:
    Hi People
    Here's my problem
    When I try to resize an layer using the move tool (as opposed to the Free Transform tool), while I'm in the process of moving the scaling handles, the bounding box reflects my movement but the layer preview stays at it's original size. When I stop moving the handles there is a few seconds delay and then the new scale size shows up. If I try to move the handles again, without commiting to the transform, the layer preview reverts back to it's original size until I've finished moving the handles.
    I also read you you tried updating your video dirvers and your syste crashed and you had to roll back.   Make sure you have downloaded the latest correct drivers. If that does not work try turning off Open GL in photoshops preferences.
    On my old XP 32 bit system CS5 movet tool with transform dialog does not fail like on your system. I can move the handles time and time again without commiting the transform. The only way to have Photoshop revert the transform back to the original state is to press the ESC key to cancel the uncommitted transform.

  • Display Problem in Swing application

    I have a java application.I am running it in Windows XP sp2.In this i see that some of the icons are missing and also not properly displayed.Can anybody tell me what is the reason behind this.

    I think you can go ahead and ignore that RA by talking to Edmond Denis

  • Java Swing application problem in Windows vista

    When we execute the Swing application in windows vista environment.
    The look and feel of the swing components are displayed improperly.
    Do we need to put any specific look and feel for windows vista environment or any specific hardware configuration is required to setup windows vista environment.
    Please give some inputs to solve the problem.
    We have tried with the following sample code to run in windows vista.
    * Vista.java
    * Created on December 5, 2006, 5:39 PM
    public class Vista extends javax.swing.JFrame {
    /** Creates new form Vista */
    public Vista() {
    initComponents();
    pack();
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
    jButton1 = new javax.swing.JButton();
    jToggleButton1 = new javax.swing.JToggleButton();
    jPanel1 = new javax.swing.JPanel();
    jCheckBox1 = new javax.swing.JCheckBox();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    getContentPane().setLayout(null);
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jButton1.setText("Button 1");
    getContentPane().add(jButton1);
    jButton1.setBounds(20, 20, 170, 30);
    jToggleButton1.setText("Togle btn");
    getContentPane().add(jToggleButton1);
    jToggleButton1.setBounds(100, 80, 90, 20);
    jPanel1.setLayout(null);
    jCheckBox1.setText("jCheckBox1");
    jCheckBox1.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 0, 0, 0));
    jCheckBox1.setMargin(new java.awt.Insets(0, 0, 0, 0));
    jPanel1.add(jCheckBox1);
    jCheckBox1.setBounds(10, 40, 130, 13);
    getContentPane().add(jPanel1);
    jPanel1.setBounds(10, 150, 200, 130);
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    getContentPane().add(jScrollPane1);
    jScrollPane1.setBounds(210, 150, 164, 94);
    jTextField1.setText("jTextField1");
    getContentPane().add(jTextField1);
    jTextField1.setBounds(240, 30, 140, 30);
    pack();
    }// </editor-fold>//GEN-END:initComponents
    * @param args the command line arguments
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new Vista().setVisible(true);
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JCheckBox jCheckBox1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JToggleButton jToggleButton1;
    // End of variables declaration//GEN-END:variables
    }

    When we execute the Swing application in windows
    vista environment.
    The look and feel of the swing components are
    displayed improperly.Improperly means what? You must be aware that Vista's native L&F certainly isn't supported yet.

  • Problem with "find" mode in adf/swing application

    Hi all,
    I'm working on ADF Swing application which uses MS SQL Server 2005 (JDeveloper 10g 10.1.3)
    I think that my issue might be well-known…sorry if it has been already discussed somewhere else…
    I have a problem with the “find” mode for a detail panel in a master-detail form…(To make it clear the “find” mode is switched on when clicking on the special button on a navigation panel).
    So this mode works well in a master panel, but it demonstrates strange behavior on a detail panel, i.e. it takes me two attempts to find the necessary child object and it doesn’t switch back in a simple way from this mode to the normal mode….say if we are in the department 10 (Dept is a master form) we can’t simply find KING employee (Emp is a detail form)…is there any workaround for this?
    Thanks in advance. Alex.

    Hi Frank, please look this issue

  • Problem in Opening HTML Page in Internet Explorer from my Swing Application

    Hi,
    I am opening a HTML file in Internet Explorer from my swing application.I am using the code given below
    private final static String WIN_FLAG = "url.dll,FileProtocolHandler";
    private final static String WIN_PATH = "rundll32";
    String cmd = WIN_PATH + " " + WIN_FLAG + " " + url;
    // url is HTML file Path
    Process p = Runtime.getRuntime().exec( cmd );
    Here there are two things i need to address ...
    1)The HTML file is opening up,but it always opens behind the swing application,that makes me every time to maximize the HTML file after it being opened up.I want to open it in front of the Swing Application.I need to implement "Always On Top" functionality for the html page.
    2)Whenever i trigger action to open different HTML page,it opens in new Internet Explorer window.
    I need to open it in same IE window.
    how to solve out these problems ??? any help would be greatly appreciated .Thanks in advance.
    - Manikandan

    any idea about this ????

  • Open image in Swing Application

    Hi,
    I'm having trouble getting an image to open into my swing application and I cant figure out whats wrong. In response to selecting the "Open" button or menu item a JFileChooser opens up and i select an image but the image doesn't actually load. If anyone could help i'd really appreciate it.
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.swing.border.*;
    import javax.imageio.*;
    class PhotoEditor extends JPanel implements ActionListener {
         * Create the GUI and show it.  For thread safety,
         * this method should be invoked from the
         * event-dispatching thread.
        JMenu imageMenu, effectsMenu;
        JFileChooser fc = new JFileChooser();
        BufferedImage img = null;
           public JMenuBar createMenuBar() {     
         JMenuBar menuBar = new JMenuBar();
        /* Build the first menu: */
        JMenu fileMenu = new JMenu("File");
        menuBar.add(fileMenu);
        fileMenu.setMnemonic(KeyEvent.VK_F);
        //a group of JMenuItems under the File option:
            String[] menuItems1 = {"Open", "Save","Save As..", "Close"};
        String[] menuIcons1 = {"Open.gif", "Save.gif", "", ""};
        for (int i = 0; i<menuItems1.length; i++)
                  JMenuItem fileMI = new JMenuItem(menuItems1, new ImageIcon(menuIcons1[i]));
              fileMI.addActionListener(this);
              fileMenu.add(fileMI);
    //adding a separator to the drop down menu list
    fileMenu.addSeparator();
    JMenuItem exitMI = new JMenuItem("Exit", new ImageIcon("Exit.gif"));
    exitMI.addActionListener(this);
    fileMenu.add(exitMI);
    /* Code which builds all the menu here */
    return menuBar;
         public JToolBar createToolBar() {     
         JToolBar toolB = new JToolBar(FlowLayout.LEFT);
    toolB.setLayout(new FlowLayout());
    // contentPane.add(toolB, "North");
    JButton newButton = new JButton(new ImageIcon("new24.gif"));
    newButton.addActionListener(this);
    toolB.add(newButton);
    newButton.setToolTipText("New");
    newButton.setActionCommand("New");
    //adding a separator to the drop down menu list
    toolB.addSeparator();
    JButton openButton = new JButton(new ImageIcon("open24.gif"));
    openButton.addActionListener(this);
    toolB.add(openButton);
    openButton.setToolTipText("Open");
         openButton.setActionCommand("Open");
    /* More code building the toolbar*/
    return toolB;
         public void actionPerformed(ActionEvent e) {
    Object eventSource = e.getSource();
    if ((eventSource instanceof JMenuItem) || (eventSource instanceof JButton));{
    String label = (String) e.getActionCommand();
    //Sets up the Action Listeners
    if (label.equals("Exit")) {
    System.exit(0);
    // Closes application
    else if (label.equals("Open")) {
         openImage();
    /* More codes for each button or menu item */
    protected void openImage() {
              int returnVal = fc.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
    File file = fc.getSelectedFile();
         try {
                   img = ImageIO.read(file);
                        catch (IOException e1) {
    public void paintComponent(Graphics g) {
         super.paintComponent(g);
    g.drawImage(img, 500, 500, null);
    private static void createAndShowGUI() {
    //Create and set up the window.
    JFrame frame = new JFrame("Photo Editor");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    //Create a main label to put in the content pane.
    JLabel main = new JLabel();
    // main.setOpaque(true);
    // main.setBackground(new Color(128, 128, 128));
    main.setPreferredSize(new Dimension(800, 600));
    //Set the menu bar and add the label to the content pane.
    PhotoEditor mainmenu = new PhotoEditor();
    frame.setJMenuBar(mainmenu.createMenuBar());
         frame.getContentPane().add(mainmenu.createToolBar(), BorderLayout.PAGE_START);
    frame.getContentPane().add(main, BorderLayout.CENTER);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();

    Your PhotoEditor class extends JPanel. In that class you override paintComponent(). But you never add the panel to the GUI, so that method is never invoked.
    Personally I would have the PhotoEditor class extend JFrame. Then in the constructor you build all the components for the frame
    a) build the menu
    b) build the toolbar
    Then I would create a PhotoPanel class that you extend and override the paintComponent(). Then you add this panel to the GUI as your main panel.
    For a simple example of drawing a background image on a panel search the forum for my BackgroundImage example.

  • Displaying image on the swings application

    Hi All,
    I want to display images onto my swing application. I was using ImageIcon and Class to getResource(filename). It can only provide me images that i have placed in my package not outside my package.
    Please help me, how to to do?
    Thanks in advance.

    [url http://java.sun.com/docs/books/tutorial/uiswing/components/icon.html]How to Use Icons

  • Preview Application Resizing Problem

    Preview Application Resizing Problem
    Microsoft platforms have two significant advantages. The first is the concept of an operating system that can function with hardware that ranges from cellular phones to desktop computers. The second is that Microsoft has excellent software development tools
    for creating and testing computer programs.
    Software compatibility across hardware platforms requires not only meeting CPU and memory requirements. Application programs must be able to automatically adjust Window and control sizes to meet the needs of available window sizes, video display unit sizes
    and screen resolutions, switching between vertical and horizontal viewing, vertical and horizontal scrolling, changes in font sizes , and variations in the available screen space due to usage of vertical and horizontal toolbars.
     Software developers must be careful that resizing doesn’t squeeze controls too close together or make them so small that they cannot be finger or stylus selected when used with touch screens.
    Some of the required automatic resizing options are provided by the Microsoft software compilers and the Windows operating system.  Softgroup Component’s “.NET  Forms Resize” is an example of one of the third party applications that provide advanced
    resizing functionality.
    Many of the resizing functions are programmer options and, if not properly enabled, an application may not have the required resizing functionality. At the current state of the art, application programs are highly variable in their capability to do the “intelligent
    resizing” that is required to handle different display environments.
    A case in point is the Microsoft Preview Application for Windows 10. When entering lengthy comments, the send button becomes positioned off the end of the program window. It is possible to scroll to the button, but the display automatically resets when scroll
    is released. The result is that the text cannot be sent. You can try a "blind" TAB to the SEND button. This appeared to work after several tries, but the comment was apparently not received,
    RERThird

    Hi,
    What do you see when you open the same PDF file in Acrobat Reader? Are the words still squeezed than?
    Dimaxum

  • Swing application w/images

    Hello,
    Java Image I/O provides ways to load and save images into swing applications. Does anyone know of other APIs? We're using Spring/RMI with a Swing client. The images would be stored on the server by index or something. Whats the best approach to write such an application? something that will provide the most flexibility (multiple image formats... viewing, saving, printing etc.) . thanks

    Thanks for the response. Can i incorporate the ability to view TurboCad sketches (.tcw files) using this API?

  • UI problem when run java swing application on MAC OSX

    Hello,
    I have problem when i run my java swing application on MAC OSX.
    Dialog box is not properly visible in MAC means ita size increses.
    its size incresed and and some content or buttons on that dialog are not fully visible.
    I can only see partial message or button.
    If any one have idea about this problem then give the solution.
    Thanks :)
    Shweta

    I am using following way to create dialog
    JOptionPane optionpane = new JOptionPane(new Object[]{lblMsgUp}, JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE, null, choices, "Save");
    JDialog dialog = optionpane.createDialog(parent, "Save");
    dialog.setSize(450, 125);
    dialog.setVisible(true);

Maybe you are looking for

  • Installing CAD 7.5(8) on Windows 7

    I'm trying to install CAD 7.5(8) on Windows 7.  This version is supposed to be compatible with Windows 7.  However, when I try to install I get the following error: File 'sllapi.dll' can not be found.  Make sure the file is on target system or instal

  • EBS functional specification

    Hi Guru's I am looking functioanl specification on following 1) For creating new report 2) For any screen field change at the movement i am looking this, by any change if i get all functional specifications i will be happy. the main reasin that i am

  • Proble with Alt-keys

    I have a problem with my keyboard: both Alt-keys work "wrong": the left only writes the following letters: äASDF© And the right one puts the aktive screen to the left side of the display (when I click on the side-bar it appears again...) Can someone

  • Keywords and albums

    After a recent crash I had to reinstall elements 6.  Now the keyword and album pallette controls are really slow.  Dragging icons onto one or one hundred selected images isn't a problem, but if I attempt to expand or collapse the keyword window it ta

  • I need to know if i have to put in the apple id credit card number

    i need to know if i have to put in the apple id credit card number