Image setting in JFrame

The following code is for setting an image in my JFrame..
import java.awt.*;
import javax.swing.*;
class FA extends JFrame
     JFrame frmMain=new JFrame("Test");
     Graphics g;
     FA()
          frmMain.setDefaultLookAndFeelDecorated(true);
          g=frmMain.getGraphics();
          frmMain.setResizable(false);
          frmMain.setBounds(20,60,700,460);
          frmMain.getContentPane().setLayout(null);
          frmMain.setVisible(true);
          g=frmMain.getGraphics();
          Graphics2D g2d=(Graphics2D)g;
          g2d.setStroke(new BasicStroke(2.0f));
          g2d.drawRect(30,60,420,340);
          Image i=new ImageIcon("images\\marea.gif").getImage();
          g.drawImage(i,30,60,420,340,this);
     public static void main(String args[])
          FA f=new FA();
By using this code i can set an image into my frame... but when i take the frame after once minimizing it will not display the image...
how to overcome this problem??

To make a slight change, I recommend calling super.paintComponent at the beginning to allow the JPanel to paint itself first:
    class MyJPanel extends JPanel
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g.drawImage(theimage, 0, 0, this);
    }

Similar Messages

  • Setting the background image in a JFrame

    Hi all,
    I have a .gif that I want to display as the background image in a JFrame. How do I do that?
    regards,
    Mat

    Check out this thread:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=288769

  • Putting an image in a JFrame

    I'm trying to paint an image onto a JFrame. Im making a monopoly game and need to paint the board, and repaint it after every turn. I dont know how to put an image onto a JFrame and was wondering if anyone could give me a basic algorithm or code example of how to do this. Thanks.

    Here is the basic algorithm to paint to a JFrame:
    Don't do it!
    Set the preferred size of a JPanel and add the JPanel to the JFrame. Paint to the JPanel by extending the paintComponent method. When you're ready to display, then remember to pack the JFrame and setVisible appropriately.
    You can read about doing this in the Java Tutorial.
    public void paintComponent(Graphics g){ //override in JPanel
      super.paintComponent(g);
      //do what ever you need to do here to draw your graphics.
    }I prefer to do all of my drawing to a BufferedImage and then use drawImage to show the image (off screen rendering):
    public void paintComponent(Graphics g){ //override in JPanel
      g.drawImage(myImage, 0, 0, this);
    }

  • Problem Displaying Images in a JFrame

    I am writing a program that displays images on a JFrame window. I have been reading the other postings about this topic however I have not been able to make my code work. I am hoping there is some obvious solution that I am not noticing. Please help, I am very confused!
    public class WelcomeWindow {
    private JLabel label;
    private ImageIcon logo;
    public WelcomeWindow() {
    label = new JLabel();
    logo = new ImageIcon("/images/logo.gif");
    label.setIcon(logo);
    this.getContentPane().add(label);

    Instead of a JLabel, have you tried to use a JButton containing the Icon?
    Also (but I think you've done it already), you could do that :
    File iconFile = new File("/images/logo.gif");
    if (!iconFile.isFile()) {
    System.out.println("Not a file");
    That way you'll be certain that the path given is correct.
    Hope this helps.

  • Inserting image in a jframe

    is it possible to insert an image into a jframe?
    as far as i noe, i can insert a jlabel, and etc. but how about an image?
    if it is possible, can someone please teach me how to do it and post me the codes.
    Thank you.

    You could use g.drawImage, but the simplest solution would be to add the image to a JLabel and add the JLabel to the JFrame.
    JLabel myLabel = new JLabel(new ImageIcon("yourimage.gif"));
    getContentPane().add(myLabel);

  • HOW TO SET A JFRAME TO NOT MOVIBLE

    How can I set a JFrame that contains several JPanel's not movible?
    Thanks.

    store the location of frame, when frame is moved set the location back
    to the original location.

  • 'Image Set' in Contacts print function not working for envelopes

    I'm using 'Image Set' in Apple Contacts to insert a pic into my Christmas address labels, which works fine, but when I try to use the same function to try and print envelopes the 'set image' function will not work, and no image will appear. Ive tried quitting and restarts to no avail - any thoughts?

    I used to use this to print a report:
    ...but it doesn't work on my Windows 7 computers.  So, now I use this:
    ...and I'm happy again.    You may be, too, if you're using Windows 7.  I found this post helpful when I experienced this problem.
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice

  • How to set the JFrame to be Full screen

    yup.. how to set the JFrame to be Full screen mode??

    Hi,
    You can get the current size of desktop and resize your application to match it.
    //Get desktop screen size
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize()
    //Set bounds for main window
    setBounds(0, 0, screenSize.width, screenSize.height);     Br,
    J

  • Keeping track of the image sets

    Is there a way to keep track of which image sets have already been processed
    (profiles generated) ?  I've been processing them in groups and would like to be
    able to verify that a particular combination (focus distance/f stop/focal length) has indeed been added to the profile.
    Also, is there a way to compare your own profiles to the available ones other than by comparing how they process images?

    >Is there a way to keep track of which image sets have already been processed
    (profiles generated) ?
    Not currently. I think it is a good idea.
    >Also, is there a way to compare your own profiles to the available ones other than by comparing how they process images?
    No. You can open up the result lcp file in a text editor to inspect yourself .

  • How to have a box layout on a JDialog, with an image set as background

    Hi,
    I need to have a JDialog in which there is a background image set (I already did this part, but only with the default layout). I further need to add text to the lower part of the JDialog. (For this, I guess I need to have a box layout.). I am not able to do so, because if I do so, I wont be able to set image background to the entire JDialog. Please help me out with how to solve this issue?
    Thanks,
    Joby

    Hi jduprez,
    Thanks for the reply. I checked Rob Camick's blog. It gives a nice way to add an image to a panel (*master panel*) and to use it.
    I still have my problem open. The above solution gives panel that I can add to my JDialog. But on the bottom half of the image (as you said, BorderLayout.South), I need to add another structured set of components using a Border Layout again.!, ie, one more panel with a BorderLayout. So when I add
    this panel, to the master panel containing the image, then the image gets cut off, at that point. I tried using component.setOpaque(false) on my sub-panel, still it does not work. Any idea, how to achieve this...?
    Following is the code I have adapted.
    public class BackgroundPanel extends JPanel
         public static final int SCALED = 0;
         public static final int TILED = 1;
         public static final int ACTUAL = 2;
         private Paint painter;
         private Image image;
         private int style = SCALED;
         private float alignmentX = 0.5f;
         private float alignmentY = 0.5f;
         private boolean isTransparentAdd = true;
         public static void main(String[] args) {
              Image img = getImage("D:/imgs/Snowdrop.jpg");
              BackgroundPanel panel = new BackgroundPanel(img);
              JDialog dlg = new JDialog();
              dlg.setLayout(new BorderLayout());
              dlg.add(panel);
              panel.setTransparentAdd(true);
              Panel nPanel = new Panel();
              nPanel.setLayout(new BorderLayout());
              JLabel label = new JLabel();
              //label.set
              label.setText("<html>HI<br>This is another line<br><br><br><br><br><br><br><br><br><br></html>");
              nPanel.add(label, BorderLayout.NORTH);
              panel.add(nPanel/*label*/,BorderLayout.SOUTH);
              dlg.setSize(600, 500);
              dlg.setVisible(true);
         private static Image getImage(String fileName){
              File file = new File(fileName);
             Image image = null;
             try{
                  image = ImageIO.read(file);     
             catch(IOException ioe){
                  /*JOptionPane.showMessageDialog(dlg, "Error in loading image file",
                            "Error", JOptionPane.ERROR_MESSAGE, null);*/
             return image;
          *  Set image as the background with the SCALED style
         public BackgroundPanel(Image image)
              this(image, SCALED);
          *  Set image as the background with the specified style
         public BackgroundPanel(Image image, int style)
              this(image,style,-1,-1);
          *  Set image as the backround with the specified style and alignment
         public BackgroundPanel(Image image, int style, float alignmentX, float alignmentY)
              setImage( image );
              setStyle( style );
              if (alignmentX  > 0){
                   setImageAlignmentX( alignmentX );     
              if (alignmentY  > 0){
                   setImageAlignmentY( alignmentY );     
              setLayout( new BorderLayout() );
          *  Use the Paint interface to paint a background
         public BackgroundPanel(Paint painter)
              setPaint( painter );
              setLayout( new BorderLayout() );
          *     Set the image used as the background
         public void setImage(Image image)
              this.image = image;
              repaint();
          *     Set the style used to paint the background image
         public void setStyle(int style)
              this.style = style;
              repaint();
          *     Set the Paint object used to paint the background
         public void setPaint(Paint painter)
              this.painter = painter;
              repaint();
          *  Specify the horizontal alignment of the image when using ACTUAL style
         public void setImageAlignmentX(float alignmentX)
              this.alignmentX = alignmentX > 1.0f ? 1.0f : alignmentX < 0.0f ? 0.0f : alignmentX;
              repaint();
          *  Specify the horizontal alignment of the image when using ACTUAL style
         public void setImageAlignmentY(float alignmentY)
              this.alignmentY = alignmentY > 1.0f ? 1.0f : alignmentY < 0.0f ? 0.0f : alignmentY;
              repaint();
          *  Override method so we can make the component transparent
         public void add(JComponent component)
              add(component, null);
          *  Override method so we can make the component transparent
         public void add(JComponent component, Object constraints)
              if (isTransparentAdd)
                   makeComponentTransparent(component);
              super.add(component, constraints);
          *  Controls whether components added to this panel should automatically
          *  be made transparent. That is, setOpaque(false) will be invoked.
          *  The default is set to true.
         public void setTransparentAdd(boolean isTransparentAdd)
              this.isTransparentAdd = isTransparentAdd;
          *     Try to make the component transparent.
          *  For components that use renderers, like JTable, you will also need to
          *  change the renderer to be transparent. An easy way to do this it to
          *  set the background of the table to a Color using an alpha value of 0.
         private void makeComponentTransparent(JComponent component)
              component.setOpaque( false );
              if (component instanceof JScrollPane)
                   JScrollPane scrollPane = (JScrollPane)component;
                   JViewport viewport = scrollPane.getViewport();
                   viewport.setOpaque( false );
                   Component c = viewport.getView();
                   if (c instanceof JComponent)
                        ((JComponent)c).setOpaque( false );
          *  Add custom painting
         protected void paintComponent(Graphics g)
              super.paintComponent(g);
              //  Invoke the painter for the background
              if (painter != null)
                   Dimension d = getSize();
                   Graphics2D g2 = (Graphics2D) g;
                   g2.setPaint(painter);
                   g2.fill( new Rectangle(0, 0, d.width, d.height) );
              //  Draw the image
              if (image == null ) return;
              switch (style)
                   case SCALED :
                        drawScaled(g);
                        break;
                   case TILED  :
                        drawTiled(g);
                        break;
                   case ACTUAL :
                        drawActual(g);
                        break;
                   default:
                     drawScaled(g);
          *  Custom painting code for drawing a SCALED image as the background
         private void drawScaled(Graphics g)
              Dimension d = getSize();
              g.drawImage(image, 0, 0, d.width, d.height, null);
          *  Custom painting code for drawing TILED images as the background
         private void drawTiled(Graphics g)
                 Dimension d = getSize();
                 int width = image.getWidth( null );
                 int height = image.getHeight( null );
                 for (int x = 0; x < d.width; x += width)
                      for (int y = 0; y < d.height; y += height)
                           g.drawImage( image, x, y, null, null );
          *  Custom painting code for drawing the ACTUAL image as the background.
          *  The image is positioned in the panel based on the horizontal and
          *  vertical alignments specified.
         private void drawActual(Graphics g)
              Dimension d = getSize();
              Insets insets = getInsets();
              int width = d.width - insets.left - insets.right;
              int height = d.height - insets.top - insets.left;
              float x = (width - image.getWidth(null)) * alignmentX;
              float y = (height - image.getHeight(null)) * alignmentY;
              g.drawImage(image, (int)x + insets.left, (int)y + insets.top, this);
    }Thanks,
    Joby

  • Image setting under export

    Under file:export I no longer have the option to change the image setting, (eg the resolution) Has it been moved to another part of lightroom or is there a way to bring it back under Export?

    It is there, still, just not for DNG or Original Export Choices.
    Don
    Don Ricklin, MacBook 2Ghz Duo 2 Core running 10.4.10 & Win XP, Pentax *ist D
    See LR Links list at my
    Blog for related sites.

  • Print as Image - Set in Registry?

    We have been resigned for some years to use the "Print as Image" setting in Adobe Reader to assure successful printing. I normally have to instruct all our users how to set this.  Is there a setting in the Windows XP registry that controls the "Print as Image" setting?  I have searched without any success.  It would sure make it a lot easier if I could use a registry edit for my users.

    I have found the solution at this link:
    http://forums.adobe.com/thread/393479
    We are an automated machine engineering company and we have about 40 mechanical and electrical engineers.  They open and print many PDF manuals and documents from everywhere. I have found that "Print to Image" corrects all of the problems 100% of the time. No need to troubleshoot or figure out what is wrong with a document, it just works.
    Thank you very much for your reply.
    Don Michaels

  • Adding .jpg image to the JFrame

    I want to add an image in the JFrame
    My code is as follows:
    import java.awt.*;
    import javax.swing.*;
    public class test extends JPanel
         JProgressBar pb1 = new JProgressBar(JProgressBar.HORIZONTAL,0,100);
    public test(String image)
    ImageIcon imgIco = new ImageIcon(image);
    JLabel imgLbl = new JLabel(imgIco);
    imgLbl.setPreferredSize(new Dimension(500,500));
    JPanel p1 = new JPanel();
    p1.add(pb1);
    setLayout(new GridLayout(1,1));
    add(imgLbl);
    add(p1);
    public void salman()
              int i=0;
              while(i<=100)
                   try
                        pb1.setValue(i);
                        pb1.setForeground(Color.lightGray);
                        pb1.setBackground(Color.blue);
                        pb1.setBorderPainted(true);
                        pb1.setStringPainted(true);
                        Thread.sleep(55);
                   catch(Exception e)
                        System.out.println("Exception Occured!!!");
                   i++;     
    public static void main(String[] args)
    JFrame f = new JFrame();
    test img = new test("pills.jpg");
    f.getContentPane().add(img);
    f.setSize(450,470);
    f.setVisible(true);
    img.salman();
    Thanks for you co-operation.
    Regards
    Salman Pirzada

    you use
    test img = new test("pills.jpg");where it finds pills.jpg????
    try something like this:
    String imageName = "pills.jpg";
    img = Toolkit.getDefaultToolkit().getImage(Test.class.getResource(imageName));And make sure, pills.jpg is in the same directory where Test class is

  • How to set image icon to JFrame

    Hi all,
    how to set image icon in the title bar of JFrame
    Thank for your help in advance

    thanks
    I have done as:
    Image image;
    image=getToolkit().getImage("database_yellow.png");
    if(image==null)System.out.println("fault
    n("fault image");
    this.setIconImage(image);
    but when I run my application, I can't see the database_yellow.png in the
    title barHm, strange ... from the code snippet you just posted I can't find the error.
    This may seem weird, but try to load a small .gif image instead ...
    Are you sure the Image is not equal to null?
    kind regards,
    Jos

  • Resizing JFrame on button click to show an image on the JFrame

    Dear All,
    I have a JFrame which has an empty label. On button click I want to set an icon for the label and want the JFrame to be resized to show that icon. I am using frame.pack() and I am not using any other sizing function. The code that I have right now, prints the image on the panel, but does not resize the frame to show the image. Pleae could someone help.package gui;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import javax.swing.ImageIcon;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    public class ComponentDemo extends JPanel implements ActionListener,
    ItemListener, MouseListener, KeyListener {
         private JTextArea textarea;
         private JButton button;
         private final static String newline = "\n";
         private JLabel imageIcon;
         public ComponentDemo() {
              button = new JButton("JButton welcomes you  to CO2001");
              button.addActionListener(this);
              add(button);
              textarea = new JTextArea(10, 50);
              textarea.setEditable(false);
              addMouseListener(this);
              textarea.addKeyListener(this);
              JScrollPane scrollPane = new JScrollPane(textarea);
              add(scrollPane);
              imageIcon = new JLabel();
              add(imageIcon);
              setBackground(Color.pink);
              new JScrollPane(this);
          * Create the GUI and show it. For thread safety, this method should be
          * invoked from the event-dispatching thread.
         private static void createAndShowGUI() {
              // Create and set up the window.
              JFrame frame = new JFrame("Simple FrameDemo");
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setLocation(700, 200);
              // get the content pane and set the background colour;
              frame.add(new ComponentDemo());
         //     frame.setSize(screenSize);
              // frame.getContentPane().setBackground(Color.cyan);
              // Display the window.
              frame.pack();
              frame.setVisible(true);
              frame.setResizable(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();
         @Override
         public void actionPerformed(ActionEvent e) {
              // TODO Auto-generated method stub
              if (e.getSource() instanceof JButton) {
                   // System.out.println(e.getSource());
                   String text = ((JButton) e.getSource()).getText();
                   textarea.append(text + newline);
                   textarea.setBackground(Color.cyan);
                   textarea.setForeground(Color.BLUE);
                   textarea.setCaretPosition(textarea.getDocument().getLength());
                   imageIcon.setIcon(createImageIcon("SwingingDuke.png",
                   "Image to be displayed"));
         @Override
         public void itemStateChanged(ItemEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseClicked(MouseEvent arg0) {
              textarea.append("A Mouse click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.green);
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void mouseEntered(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseExited(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mousePressed(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void mouseReleased(MouseEvent arg0) {
              // TODO Auto-generated method stub
         @Override
         public void keyPressed(KeyEvent e) {
              System.out.println(e.getKeyChar());
              textarea.append("The key " + e.getKeyChar()
                        + " click welcomes you to CO2001" + newline);
              textarea.setBackground(Color.YELLOW);
              textarea.setFont(new Font("Arial", Font.ITALIC, 16));
              textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyReleased(KeyEvent e) {
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.green);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         @Override
         public void keyTyped(KeyEvent e) {
              // TODO Auto-generated method stub
              System.out.println(e.getKeyChar());
              // textarea.append("The key "+
              // e.getKeyChar()+" click welcomes you to CO2001" + newline);
              // textarea.setBackground(Color.blue);
              // textarea.setCaretPosition(textarea.getDocument().getLength());
         /** Returns an ImageIcon, or null if the path was invalid. */
         protected ImageIcon createImageIcon(String path, String description) {
              java.net.URL imgURL = getClass().getResource(path);
              if (imgURL != null) {
                   System.out.println("found");
                   return new ImageIcon(imgURL, description);
              } else {
                   System.err.println("Couldn't find file: " + path);
                   return null;
    }

    myJPanel.setPerferredSize(new Dimension(new_width, new_hight));
    myJFrame.pack();

Maybe you are looking for

  • Account group and Account Type.

    Hi all, Could you please tell me the diferences between <b>GL Account group</b>  (<i>by example cash, expense, revenue</i> ....) which we define in IMG - Financial Accounting - General Ledger Accounting - G/L Accounts - Master Records - Preparations

  • PDF as default selection for Select printing cotrol (for Web)

    Hi Can someone point me to righ direction? What we are trying to do is, in Infoview, set PDF as default selection for "Select printing Control (for Web)", so that each user does not have to do this in preferences in infoview. Is it possible to do so?

  • Just A Thank You To Jamie At Customer Options Team

    So basically BT have apparently found the problem to hand its the package im on cuasing problems pushing to much down my line  So i had the engi notes to hand explained the problem to a gentleman named Jamie  completed a new order for Infinity Option

  • Registering Discoverer Reports to a Portal/Portlet?

    Can anybudy give me an idea how to register discoverer reports (workbok/worksheet) to Portal/Portlet?

  • GPO to kill disconnected and idle RDP connections

    Hello I'm looking for a way to Kill RDP connection with idle & disconnected state. the server's owners usually connect to the servers from their PCs to the servers using the Remote Desktop Connection and they forget to disconnect properly. some left